定义JNI方法
companion object{
init {
System.loadLibrary("jnitest")
}
}
external fun encryptAES(data :ByteArray): ByteArray?
external fun decryptAES(data :ByteArray): ByteArray?
使用OpenSSL方法实现AES加密和解密
#include "include/openssl/aes.h"
const char* key_data = "0123456789abcdef";
extern "C"
JNIEXPORT jbyteArray JNICALL
Java_com_test_jnitest_TestLib_encryptAES(JNIEnv *env, jobject thiz, jbyteArray data_) {
size_t len = strlen(key_data); // 数据长度
unsigned char* unsigned_key_data = new unsigned char[len]; // 分配内存空间
// 将数据复制到内存空间中
memcpy(unsigned_key_data, key_data, len);
jbyte *data = env->GetByteArrayElements( data_, NULL);
jsize data_length = env->GetArrayLength( data_);
// 创建 AES 上下文对象
AES_KEY aes_key;
if (AES_set_encrypt_key(unsigned_key_data, len * 8, &aes_key) < 0) {
return NULL;
}
// 分配加密结果缓冲区
int out_size = data_length + AES_BLOCK_SIZE;
unsigned char *encrypted_data = (unsigned char *) malloc(out_size);
if (encrypted_data == NULL) {
return NULL;
}
// 执行加密操作
AES_cbc_encrypt((unsigned char *) data, encrypted_data, data_length, &aes_key,
unsigned_key_data, AES_ENCRYPT);
// 将加密结果转换为 Java 中的 byte 数组返回
jbyteArray result = env->NewByteArray( out_size);
env->SetByteArrayRegion( result, 0, out_size, (jbyte *) encrypted_data);
// 释放内存
free(encrypted_data);
env->ReleaseByteArrayElements( data_, data, JNI_ABORT);
return result;
}
extern "C"
JNIEXPORT jbyteArray JNICALL
Java_com_test_jnitest_TestLib_decryptAES(JNIEnv *env, jobject thiz, jbyteArray data_) {
size_t len = strlen(key_data); // 数据长度
unsigned char* unsigned_key_data = new unsigned char[len]; // 分配内存空间
// 将数据复制到内存空间中
memcpy(unsigned_key_data, key_data, len);
jbyte *data = env->GetByteArrayElements( data_, NULL);
jsize data_length = env->GetArrayLength( data_);
// 创建 AES 上下文对象
AES_KEY aes_key;
if (AES_set_decrypt_key(unsigned_key_data, len * 8, &aes_key) < 0) {
return NULL;
}
// 分配解密结果缓冲区
int out_size = data_length - AES_BLOCK_SIZE;
unsigned char *decrypted_data = (unsigned char *) malloc(out_size);
if (decrypted_data == NULL) {
return NULL;
}
// 执行解密操作
AES_cbc_encrypt((unsigned char *) data, decrypted_data, data_length, &aes_key,
unsigned_key_data, AES_DECRYPT);
// 将解密结果转换为 Java 中的 byte 数组返回
jbyteArray result = env->NewByteArray( out_size);
env->SetByteArrayRegion( result, 0, out_size, (jbyte *) decrypted_data);
// 释放内存
free(decrypted_data);
env->ReleaseByteArrayElements( data_, data, JNI_ABORT);
return result;
}
应用
var testLib = TestLib()
var encrpy = testLib.encryptAES("HelloWorld!!!!!!".toByteArray())
encrpy?.let {
var decrpy = testLib.decryptAES(it)
decrpy?.let {
Log.i(TAG, String(it))
}
}