gpt4 book ai didi

c++ - 使用 CryptoPP 库加密和解密字节数组/vector

转载 作者:行者123 更新时间:2023-11-28 04:52:52 26 4
gpt4 key购买 nike

我正在尝试加密已解析为字符串的字节数组。这似乎适用于所有情况,但字节数组包含 0x00 的情况除外。

int main()
{
byte cipherTextWithZeroByte[32] = {
0xD3, 0xFA, 0xD6, 0xEC, 0x84, 0x4E, 0xD3, 0xD8,
0x2B, 0x76, 0x6C, 0xE8, 0x02, 0xF2, 0xB2, 0x6F,
0x00, 0xE8, 0x99, 0x8C, 0xEC, 0x4B, 0x3C, 0x7D,
0xAC, 0xDE, 0x86, 0x02, 0x51, 0xAB, 0x3F, 0x04
};

string cipherText((char *)cipherTextWithZeroByte);
string plainText = decrypt(cipherText, sizeof(cipherTextWithZeroByte));

return 1;
}

string decrypt(string cipherText, int size)
{
string decryptedText;

CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption(aesDecryption, iv);

CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption,
new CryptoPP::HexEncoder(
new CryptoPP::StringSink(decryptedText)));

stfDecryptor.Put(reinterpret_cast<const unsigned char*>(cipherText.c_str()), size);
stfDecryptor.MessageEnd();

return decryptedText;
}

在这种情况下,字节数组包含 0x00。这会导致 cipherText 被截短,从而导致长度无效。抛出异常说明:“StreamTransformationFilter:找到无效的 PKCS #7 block 填充

所以我认为最好使用 ArraySourceArraySink 来确保字符串不以零结尾。

int main()
{
byte cipherTextWithZeroByte[32] = {
0xD3, 0xFA, 0xD6, 0xEC, 0x84, 0x4E, 0xD3, 0xD8,
0x2B, 0x76, 0x6C, 0xE8, 0x02, 0xF2, 0xB2, 0x6F,
0x00, 0xE8, 0x99, 0x8C, 0xEC, 0x4B, 0x3C, 0x7D,
0xAC, 0xDE, 0x86, 0x02, 0x51, 0xAB, 0x3F, 0x04
};

vector<byte> cipherTextData(cipherTextWithZeroByte, cipherTextWithZeroByte + sizeof(cipherTextWithZeroByte) / sizeof(cipherTextWithZeroByte[0]));
vector<byte> plainTextData = decrypt(cipherTextData);

return 1;
}

vector<byte> decrypt(vector<byte> cipherText)
{
vector<byte> plainText;
plainText.resize(cipherText.size());

CryptoPP::CBC_Mode<CryptoPP::AES>::Decryption decryptor;
decryptor.SetKeyWithIV(key, sizeof(key), iv, sizeof(iv));


CryptoPP::ArraySource ss(&cipherText[0], cipherText.size(), true,
new CryptoPP::HexEncoder(
new CryptoPP::StreamTransformationFilter(decryptor,
new CryptoPP::ArraySink(plainText.data(), plainText.size()))));

return plainText;
}

在这种情况下,会抛出密文不是 key 长度的倍数的异常,这里显然不是这种情况。 ( key = 16 字节,密文 = 16 字节)。我认为该库将字节数组强制转换为一个字符串,在 0x00 字节之后省略了所有数据。

我做错了什么?

最佳答案

加密是二进制字节而不是字符操作。因此,加密输出不能转换为字符串。如果您需要字符串输出,请将加密数据编码为字符串兼容格式,常见格式为 Base64 和十六进制。

特别是按照“C”中的约定,字符串中的空字节类似于信号语言字符串的末尾。

即加密时将二进制数据编码为字符串格式,解密时首先使用编码操作的逆运算将字符串表示解码为二进制数据。

关于c++ - 使用 CryptoPP 库加密和解密字节数组/vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47791590/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com