前言
我会在小专栏和简书一起分享。
最近在忙其他事情,今天想起JNI做加解密不错,于是我调查了一下AES使用JNI实现,试验过程发现用C或者C++出了很多问题,于是发现有人使用一种巧妙的方式,用Java做加解密,只是把加解密的Key放在SO库中,这里我要讲的就是这种方式。
正文
新建java类
public class AESjni {
public static native String myEncrypt(String str);
public static native String myDecrypt(String str);
}
还是使用我们的Tools工具生成.h
文件
接着编写c文件
#include "com_crayfish_ndkproject_AESjni.h"
#include <stdlib.h>
const char *DES_KEY = "12345678912345678912345678912345";
/*
* Class: com_jzp_myapplication_JniUtils
* Method: getString
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_crayfish_ndkproject_AESjni_myEncrypt
(JNIEnv *env, jclass jclass1, jstring jstr)
{
if (jstr == NULL) {
return NULL;
}
jstring key;
jstring result;
jclass AESencrypt;
jmethodID mid;
AESencrypt = (*env)->FindClass(env, "com/crayfish/ndkproject/AESjni");
if (NULL == AESencrypt) {
return NULL;
}
mid = (*env)->GetStaticMethodID(env, AESencrypt, "encrypt",
"(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;");
if (NULL == mid) {
(*env)->DeleteLocalRef(env, AESencrypt);
return NULL;
}
key = (*env)->NewStringUTF(env, DES_KEY);
result = (*env)->CallStaticObjectMethod(env, AESencrypt, mid, key, jstr);
(*env)->DeleteLocalRef(env, AESencrypt);
(*env)->DeleteLocalRef(env, key);
return result;
}
JNIEXPORT jstring JNICALL Java_com_crayfish_ndkproject_AESjni_myDecrypt
(JNIEnv *env, jclass jclass1, jstring jstr)
{
if (jstr == NULL) {
return NULL;
}
jstring key;
jstring result;
jclass AESencrypt;
jmethodID mid;
AESencrypt = (*env)->FindClass(env, "com/crayfish/ndkproject/AESjni");
if (NULL == AESencrypt) {
return NULL;
}
mid = (*env)->GetStaticMethodID(env, AESencrypt, "decrypt",
"(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;");
if (NULL == mid) {
(*env)->DeleteLocalRef(env, AESencrypt);
return NULL;
}
key = (*env)->NewStringUTF(env, DES_KEY);
result = (*env)->CallStaticObjectMethod(env, AESencrypt, mid, key, jstr);
(*env)->DeleteLocalRef(env, AESencrypt);
(*env)->DeleteLocalRef(env, key);
return result;
}
看到c
代码中有读取java类中encrypt
和decrypt
两个方法了吧,我们把它们补上,这里就是真正的加解密逻辑。
public static String encrypt(String key,String palinText) throws Exception{
//加密
return "";
}
public static String decrypt(String key,String palinText) throws Exception{
//解密
return "";
}
记得配置Android.mk
和build.gradle
include $(CLEAR_VARS)
LOCAL_MODULE := AESjni
LOCAL_SRC_FILES := aesjni.c
include $(BUILD_SHARED_LIBRARY)
ndk{
moduleName "AESjni" //生成的so名字
//abiFilters "armeabi", "armeabi-v7a", "x86" //输出指定三种abi体系结构下的so库。目前可有可无。
}
结尾
今天的内容很简单,到这就结束了。
网友评论