首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用CryptoPP库加密和解密字节数组/向量

问使用CryptoPP库加密和解密字节数组/向量
EN

Stack Overflow用户
提问于 2017-12-13 11:10:12
回答 1查看 1.7K关注 0票数 0

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

代码语言:javascript
复制
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块填充找到‘

因此,我认为最好使用ArraySource和ArraySink来确保字符串不以零结尾。

代码语言:javascript
复制
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 = 16字节,密文= 16字节)。我认为库将字节数组转换为字符串,忽略了0x00字节之后的所有数据。

我做错了什么?

EN

回答 1

Stack Overflow用户

发布于 2017-12-13 14:11:27

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

特别是,字符串中的空字节按约定在"C“中使用,就像信号语言一样,字符串的结尾。

也就是说,对二进制数据进行加密,将二进制数据编码成字符串格式,并在解密时首先使用编码操作的逆序将字符串表示解码为二进制数据。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47791590

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档