1,BIO加密解密
BIO库由于链式特性,可以很方便的实现 加密+base64 操作
void OpensslTool::initEvp()
{
this->evp_key = (unsigned char*)"1234567890123456";
this->evp_iv = (unsigned char*)"0000000000000000";
}
//public
std::string OpensslTool::aesEncode(const char *in )
{
CCLOG("=====aesEncode=========in == %s",in);
std::string retStr = this->bioAesEncode(in);
CCLOG("=======11111 aesEncode====%s",retStr.c_str());
return retStr.c_str();
}
// private
std::string OpensslTool::bioAesEncode(const char *in )
{
int len = strlen(in);
char* out;
int outLen = this->bioAesEncode(in, len, &out);
std::string retStr(out);
if (out) {
delete[] out;
}
return retStr;
}
int OpensslTool::bioAesEncode(const char *in, int inLen, char **out )
{
//内存型bio,存储加密后数据
BIO* bmem = BIO_new(BIO_s_mem());
//base64型bio,用于base64
BIO* b64 = BIO_new(BIO_f_base64());
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
BIO_push(b64, bmem);
//filter型bio,用于加密,可以在这里修改加密策略
BIO* bCipher = BIO_new(BIO_f_cipher());
BIO_set_cipher(bCipher, EVP_aes_128_ecb(), this->evp_key, this->evp_iv, 1);
BIO_push(bCipher, b64);
//writer操作:通过bio链 将原始数据->加密->base64->内存->返回
int len = BIO_write(bCipher, in, inLen);
int result = BIO_get_cipher_status(bCipher);
// CCLOG("=====result ==== %d=======len === %d",result,len);
BIO_flush(bCipher);
//将内存数据取出,memcpy到out
BUF_MEM* bptr = nullptr;
BIO_get_mem_ptr(bCipher, &bptr);
int outLen = bptr->length;
*out = new char[outLen+1];
memcpy(*out,bptr->data, outLen);
out[outLen] = 0;
BIO_free_all(bCipher);
return outLen;
}
2,解密: 原始数据->base64解码 -> 解密
std::string OpensslTool::aesDecode(const char *in)
{
CCLOG("aesDecode========in===%s",in);
std::string out = this->bioAesDecode(in);
CCLOG("11111111 aesDecode===== %s...len== %lu",out.c_str(),out.length());
return out.c_str();
}
//private:
std::string OpensslTool::bioAesDecode(const char *in)
{
int len = strlen(in);
char* out;
int outLen = this->bioAesDecode(in, len, &out);
std::string retStr(out);
if (out) {
delete[] out;
}
return retStr;
}
int OpensslTool::bioAesDecode(const char *in, int inLen, char **out)
{
BIO* bmem = BIO_new_mem_buf(in, inLen);
BIO* b64 = BIO_new(BIO_f_base64());
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
BIO_push(b64, bmem);
BIO* bCipher = BIO_new(BIO_f_cipher());
BIO_set_cipher(bCipher, EVP_aes_128_ecb(), this->evp_key, this->evp_iv, 0);
BIO_push(bCipher, b64);
int result = BIO_get_cipher_status(bCipher);
BUF_MEM* buffer = nullptr;
BIO_get_mem_ptr(bmem, &buffer);
*out = new char[inLen];
memset(*out, 0, inLen);
//read操作:内存数据->base64解码->解密操作->返回数据
int len = BIO_read(bCipher, *out, inLen);
// CCLOG("=====result === %d.....len = %d",result,len);
BIO_free_all(bCipher);
// CCLOG("=====out === %s",*out);
return inLen;
}
二,EVP加密解密
事实上BIO_f_cipher封装了EVP_CipherInit、EVP_CipherUpdate、EVP_CipherFinal三种方法,后续会补充EVP库加密解密