Android JNI Aes加密
2018-07-10 本文已影响11人
_凌浩雨
/*
* AES 加密工具类
* Created by mazaiting on 2018/7/3.
*/
#include <jni.h>
#include <cstring>
#include <android/log.h>
//#include "openssl/evp.h"
#include <openssl/evp.h>
#include <openssl/buffer.h>
#define TAG "AES_CPP"
#define LOGD(FORMAT, ...) __android_log_print(ANDROID_LOG_DEBUG,TAG,FORMAT,##__VA_ARGS__);
// 命名空间
//using namespace std;
extern "C" {
// 初始化key
const unsigned char *_key = (const unsigned char *) "0123456789012345";
// 初始化iv
const unsigned char *_iv = (const unsigned char *) "0123456789012345";
/**
* Use EVP to Base64 encode the input byte array to readable text
*/
char *base64(const unsigned char *inputBuffer, int inputLen) {
EVP_ENCODE_CTX ctx;
int base64Len = (((inputLen + 2) / 3) * 4) + 1; // Base64 text length
// int pemLen = base64Len + base64Len/64; // PEM adds a newline every 64 bytes
char *base64 = new char[base64Len];
int result;
EVP_EncodeInit(&ctx);
EVP_EncodeUpdate(&ctx, (unsigned char *) base64, &result, (unsigned char *) inputBuffer,
inputLen);
EVP_EncodeFinal(&ctx, (unsigned char *) &base64[result], &result);
return base64;
}
/**
* Use EVP to Base64 decode the input readable text to original bytes
*/
char *unbase64(char *input, int length) {
EVP_ENCODE_CTX ctx;
int orgLen = (((length + 2) / 4) * 3) + 1;
char *orgBuf = new char[orgLen];
int result, tmpLen;
EVP_DecodeInit(&ctx);
EVP_DecodeUpdate(&ctx, (unsigned char *) orgBuf, &result, (unsigned char *) input, length);
EVP_DecodeFinal(&ctx, (unsigned char *) &orgBuf[result], &tmpLen);
result += tmpLen;
return orgBuf;
}
JNIEXPORT jobjectArray JNICALL
Java_com_mazaiting_aesdemo_Encrypt_setValues(JNIEnv *env, jclass type) {
// 待加密的数据
const unsigned char *vItem = (const unsigned char *) "mazaiting";
// 源数据长度
int inLen = (int) strlen((const char *) vItem);
// 加密长度
int encLen = 0;
// 输出长度
int outlen = 0;
// 加密数据长度
unsigned char encData[1024] = {0};
LOGD("source: %s\n", vItem);
// 创建加密上下文
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
// 初始化加密上下文
EVP_CipherInit_ex(ctx, EVP_aes_256_ecb(), NULL, _key, _iv, 1);
// 加密数据
EVP_CipherUpdate(ctx, encData, &outlen, vItem, inLen);
// 拼接长度
encLen = outlen;
// 结束加密
EVP_CipherFinal(ctx, encData + outlen, &outlen);
// 拼接
encLen += outlen;
// 释放
EVP_CIPHER_CTX_free(ctx);
// base64编码
char *baseEnc = base64(encData, encLen);
LOGD("encrypted : %s\n", baseEnc);
// base64解码
char *encData1 = unbase64(baseEnc, (int) strlen(baseEnc));
// 解密长度
int decLen = 0;
// 解码数据长度
outlen = 0;
// 解码后的数据
unsigned char decData[1024];
// 创建解密上下文
EVP_CIPHER_CTX *ctx2 = EVP_CIPHER_CTX_new();
// 初始化解密
EVP_CipherInit_ex(ctx2, EVP_aes_256_ecb(), NULL, _key, _iv, 0);
// 执行解密
EVP_CipherUpdate(ctx2, decData, &outlen, (const unsigned char *) encData1, encLen);
// 设置长度
decLen = outlen;
// 结束解密
EVP_CipherFinal(ctx2, decData + outlen, &outlen);
// 拼接长度
decLen += outlen;
// 释放
EVP_CIPHER_CTX_free(ctx2);
// 设置字符串结尾标识
decData[decLen] = '\0';
LOGD("decrypt: %s\n", decData);
}
}