我在使用openssl的aes(cbc)加密字节超过96的字符串后,在解密就会少字符,下面是我写的代码,求大神指点下什么问题,AES一次加密的明文是有长度限制么?
CooloiAES::CooloiAES()
: MSG_LEN(0)
{
for(int i = 0; i < AES_BLOCK_SIZE; i++)
{
key[i] = 32 + i;
}
}
CooloiAES::~CooloiAES()
{
}
std::string CooloiAES::aes_encrypt(std::string msg)
{
int i = msg.size() / 16;
MSG_LEN = ( i + 1 ) * 16;
//MSG_LEN = msg.size() + 16;
char in[MSG_LEN];
char out[MSG_LEN];
memset((char*)in,0,MSG_LEN);
memset((char*)out,0,MSG_LEN);
//strncpy((char*)in,msg.c_str(),msg.size());
//memcpy((char*)in,msg.data(),msg.size());
strcpy((char*)in,msg.c_str());
unsigned char iv[AES_BLOCK_SIZE]; //加密的初始化向量
for(int j = 0; j < AES_BLOCK_SIZE; ++j)
{
iv[j] = 0;
}
AES_KEY aes;
if(AES_set_encrypt_key((unsigned char*)key, 128, &aes) < 0)
{
return NULL;
}
size_t len = strlen(in);
std::cout << "LEN ::::: " << len << std::endl;
AES_cbc_encrypt((unsigned char*)in,(unsigned char*)out,len,&aes,iv,AES_ENCRYPT);
std::string encrypt_msg(&out[0],&out[MSG_LEN+16]);
for(int i= 0;out[i];i++){
printf("%x",(unsigned char)out[i]);
//std::cout << dstStringTemp[i];
}
std::cout << std::endl;
return encrypt_msg;
}
std::string CooloiAES::aes_decrypt(std::string msg)
{
MSG_LEN = msg.size();
char in[MSG_LEN];
char out[MSG_LEN+16];
memset((char*)in,0,MSG_LEN);
memset((char*)out,0,MSG_LEN+16);
//strncpy((char*)in,msg.c_str(),msg.size());
memcpy((char*)in,msg.data(),msg.size());
for(int i= 0;in[i];i++){
printf("%x",(unsigned char)in[i]);
//std::cout << dstStringTemp[i];
}
std::cout << std::endl;
unsigned char iv[AES_BLOCK_SIZE]; //加密的初始化向量
for(int j = 0; j < AES_BLOCK_SIZE; ++j)
{
iv[j] = 0;
}
AES_KEY aes;
if(AES_set_decrypt_key((unsigned char*)key, 128, &aes) < 0)
{
return NULL;
}
//int len = msg.size();
size_t len = strlen(in);
AES_cbc_encrypt((unsigned char*)in,(unsigned char*)out,len,&aes,iv,AES_DECRYPT);
std::string decrypt_msg = out;
return decrypt_msg;
}