基于openssl的aes_ecb加密
aes
AES五种加密模式(CBC、ECB、CTR、OCF、CFBecb是aes加密的多种模式中的一种, 这种模式是将整个明文分成若干段相同的小段,然后对每一小段进行加密。
基于openssl的aes_ecb加密
int32_t Encrypt(const string& content, string& strOut)
{
int len = content.length() / 16 + 1;
byte userkey[16] = { 1, 2, 3, 4, 6, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2};
char* data = (char*)malloc(AES_BLOCK_SIZE * len);
unsigned char* cipher = (unsigned char*)malloc(AES_BLOCK_SIZE * len + 33);
unsigned char* plain = (unsigned char*)malloc(AES_BLOCK_SIZE * len);
AES_KEY key;
memset((void*)data, 0, AES_BLOCK_SIZE * len);
memset((void*)cipher, 0, AES_BLOCK_SIZE * len + 33);
memset((void*)plain, 0, AES_BLOCK_SIZE * len);
strcpy_s(data, AES_BLOCK_SIZE * len, content.c_str());
/*aes (key,content)*/
AES_set_encrypt_key(userkey, 256, &key);
for (int i = 0; i < len; i++) //每次加密16个字节
AES_ecb_encrypt((byte*)(data + i * AES_BLOCK_SIZE), cipher + i * AES_BLOCK_SIZE, &key, AES_ENCRYPT);
strOut = cipher ;
free(data);
free(cipher);
free(plain);
return 0;
}
基于openssl的aes_ecb解密
int32_t Decode(const string& strSrc, string& res)
{
byte userkey[16] = { 1, 2, 3, 4, 6, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2}; //解密密钥与加密密钥相同
auto pres = new char[strSrc.length()];
memset(pres, '\0', strSrc.length());
AES_KEY key;
AES_set_decrypt_key(userkey, 256, &key);
for (int32_t i = 0; i < (strSrc.length()/16); i++)
AES_ecb_encrypt((byte*)(strSrc.c_str() + i * AES_BLOCK_SIZE), (byte*)(pres + i * AES_BLOCK_SIZE), &key, AES_DECRYPT);
res = string(pres);
delete[] pres;
return 0;
}