我使用 openssl
编码了一个文本文件,如下所示:
openssl enc -nosalt -aes-128-cbc -k mypass -in "test.txt" -out "test_enc.txt" -p
它返回 key 和 iv,如下所示:
key=A029D0DF84EB5549C641E04A9EF389E5
iv =A10CE9C4682486F8622F2F18E7291367
这是我用来解密文件的代码:
int main() {
streampos size;
char * indata;
ifstream file ("test_enc.txt", ios::in|ios::binary|ios::ate);
ofstream outfile ("test_decoded.txt",std::ofstream::binary);
if (file.is_open())
{
size = file.tellg();
indata = new char [size];
file.seekg (0, ios::beg);
file.read (indata, size);
file.close();
unsigned char* outdata=new unsigned char [size];
unsigned char ckey[] = "\xA0\x29\xD0\xDF\x84\xEB\x55\x49\xC6\x41\xE0\x4A\x9E\xF3\x89\xE5";
unsigned char ivec[] = "\xA1\x0C\xE9\xC4\x68\x24\x86\xF8\x62\x2F\x2F\x18\xE7\x29\x13\x67";
AES_KEY key;
AES_set_decrypt_key(ckey, 256, &key);
AES_cbc_encrypt((unsigned char*) indata, outdata, size, &key, ivec, AES_DECRYPT);
outfile.write ((char*) outdata,size);
delete[] indata;
delete[] outdata;
}
else{
cout << "Unable to open file";
cerr << "Error: " << strerror(errno);
}
outfile.close();
file.close();
return 0;
}
此代码完美运行。但是,当我按照以下命令在编码时使用 salt 时:
openssl enc -aes-128-cbc -k mypass -in "test.txt" -out "test_enc.txt" -p
并适当替换代码中的key和ivec,整个文件正确解密但前16个字节!我从其他有类似问题的帖子中了解到,我知道 iv 值是错误的,但我不知道正确的 iv 值应该是多少。我只使用加密后返回的 key 和 iv 值,我也没有考虑盐值(实际上我不知道该怎么做)。正确的 iv 值应该是多少?
最佳答案
从您的问题症状来看,在我看来,您的以下逻辑可能正在释放您程序中稍后的代码正在读取的内存。这导致了这种情况。通常会发生这种情况,因为在释放内存后,堆管理器通常会写入一些内务处理信息以供自己使用。
关键是我们不应该在释放内存后使用它,因为它是悬空的。
//Allocate the memory
unsigned char* outdata=new unsigned char [size];
// It appears to me that here the outdata is getting freed. I do not see anywhere
// else this memory is getting freed.
AES_cbc_encrypt((unsigned char*) indata, outdata, size, &key, ivec, AES_DECRYPT);
// Due to this, while accessing it we are seeing the 16 bytes corrupted.
outfile.write ((char*) outdata,size);
您可以使用任何动态工具来识别此类问题。
关于c++ - 使用 AES 解密时前 16 个字节损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25603091/