我正在尝试使用 Crypto ++ 使用 AES256 为内存文件创建字节数组加密/解密。
我需要加密一个无符号字符字节数组,并且也将加密的数据作为无符号字符字节数组!与解密相同。 >
我尝试了很多在网上找到的解决方案,但无法使其正常工作。输出文件和长度错误。
我如何使其工作?
block_aes.h:
const unsigned char original_Data[42] = {
0x54, 0x48, 0x49, 0x53, 0x20, 0x49, 0x53, 0x20, 0x54, 0x45, 0x53, 0x54,
0x20, 0x44, 0x41, 0x54, 0x41, 0x20, 0x49, 0x54, 0x20, 0x43, 0x41, 0x4E,
0x20, 0x42, 0x45, 0x20, 0x41, 0x4E, 0x59, 0x20, 0x46, 0x49, 0x4C, 0x45,
0x20, 0x44, 0x41, 0x54, 0x41, 0x2E
};
const unsigned char iv[16] = {
0xAE, 0x50, 0x95, 0xEB, 0xC5, 0x76, 0x20, 0x1A, 0xA4, 0x84, 0xB6, 0xB0,
0x51, 0x03, 0xEE, 0xE8
};
const unsigned char key[32] = {
0xDA, 0x1F, 0x84, 0x85, 0xBD, 0x62, 0x2D, 0xB1, 0x45, 0x13, 0x84, 0x20,
0xCF, 0x02, 0x47, 0xB9, 0x85, 0xEC, 0x78, 0xD7, 0x85, 0xEF, 0x07, 0xD7,
0xA8, 0x15, 0x11, 0x6E, 0x11, 0xDF, 0xEE, 0x39
};
block_aes.cpp:
int _tmain(int argc, _TCHAR* argv[])
{
/// Encrypt
vector<CryptoPP::byte> cipher;
CBC_Mode<AES>::Encryption enc;
enc.SetKeyWithIV(key, sizeof(key), iv, sizeof(iv));
cipher.resize(sizeof(original_Data)+AES::BLOCKSIZE);
ArraySink cs(&cipher[0], cipher.size());
ArraySource(original_Data,sizeof(original_Data), true,
new StreamTransformationFilter(enc, new Redirector(cs)));
cipher.resize(cs.TotalPutLength());
/// Test
DWORD tmp;
HANDLE File_Out = CreateFileA(
"Encrypted.File",
GENERIC_ALL,
FILE_SHARE_WRITE,
NULL,
CREATE_NEW,
FILE_ATTRIBUTE_NORMAL,
&tmp
);
WriteFile(File_Out, &cipher, sizeof(cipher), &tmp, NULL);
/// Decrypt
vector<CryptoPP::byte> recover;
CBC_Mode<AES>::Decryption dec;
dec.SetKeyWithIV(key, sizeof(key), iv, sizeof(iv));
recover.resize(cipher.size());
ArraySink rs(&recover[0], recover.size());
ArraySource(cipher.data(), cipher.size(), true,
new StreamTransformationFilter(dec, new Redirector(rs)));
recover.resize(rs.TotalPutLength());
/// Test
HANDLE File_Out2 = CreateFileA(
"Decrypted.File",
GENERIC_ALL,
FILE_SHARE_WRITE,
NULL,
CREATE_NEW,
FILE_ATTRIBUTE_NORMAL,
&tmp
);
WriteFile(File_Out2, &recover, sizeof(recover), &tmp, NULL);
}
答案 0 :(得分:1)
在您的WriteFile
调用中,您写出cipher
变量的内容,而不是向量中存储的内容。保存您需要的向量
WriteFile(File_Out, cipher.data(), cipher.size(), &tmp, NULL);
并且:
WriteFile(File_Out2, recover.data(), recover.size(), &tmp, NULL);
由于您使用了address-of
运算符,因此这里是另一种写法:
WriteFile(File_Out, &cipher[0], cipher.size(), &tmp, NULL);
&cipher[0]
是在C ++ 03和C ++ 11中获取非常量指针(可写)的唯一方法。 (但是这里不需要,因为const指针(可读)工作正常)。