获取 AES 256 Crypto++ 中的十六进制加密字符串

2024-06-28

我正在尝试在 MS Visual Studio 中使用 Crypto++ 实现 AES 256 算法。操作系统是Windows 7(64位)。

我需要以十六进制字符串形式提供密钥,以字符串形式提供密码,最后我希望加密的字符串也是十六进制字符串。

这是我正在尝试做的事情:

我的加密方法:

std::string encrypt(const std::string &password)
{
    std::string plain = password;
    std::string ciphertext;
    char * decodedKey= "729308A8E815F6A46EB3A8AE6D5463CA7B64A0E2E11BC26A68106FC7697E727E37011";

    byte key[ CryptoPP::AES::MAX_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
    CryptoPP::StringSource( reinterpret_cast<const char *>(decodedKey), true,
              new  CryptoPP::HashFilter(*(new  CryptoPP::SHA256), new CryptoPP::ArraySink(key, CryptoPP::AES::MAX_KEYLENGTH)) );
    memset( iv, 0x00,  CryptoPP::AES::BLOCKSIZE );

    CryptoPP::CBC_Mode<CryptoPP::AES>::Encryption Encryptor( key, sizeof(key), iv );
    CryptoPP::StringSource( plain, true, new CryptoPP::StreamTransformationFilter( Encryptor,
              new CryptoPP::HexEncoder(new CryptoPP::StringSink( ciphertext ) ) ) );

    std::cout<<"Ciphertext:" << ciphertext;
    return ciphertext;
}

来自主方法

int main(int argc, char* argv[]) {

    encrypt("test");
    return 0;
}

目前我对密钥进行硬编码只是为了调试目的。我的密钥是十六进制字符串,如下所示。我需要将输出加密字符串作为十六进制字符串。


我需要以十六进制字符串形式提供密钥,以字符串形式提供密码,最后我希望加密的字符串也是十六进制字符串。

Crypto++ wiki 中对此进行了介绍(其中有很多示例可供复制/粘贴)。从HexDecoder 的脚本和字符串 http://www.cryptopp.com/wiki/HexDecoder#Scripting_and_Strings:

有时,邮件列表会收到以下问题: 交叉验证。例如,请参阅 AES CTR Chiper。输出不同 PHP-mcrypt 和 Crypto++ 之间。在问题中,PHP-mcrypt 字符串 使用如下:

$key = "1234567890123456789012345678901234567890123456789012345678901234";
$key = pack("H".strlen($key), $key);
$iv = "1111111111222222222233333333334444444444555555555566666666667777";
$iv = pack("H".strlen($iv), $iv);

避免拼写错误的最简单方法之一是通过复制/粘贴和 十六进制解码器:

string encodedKey = "1234567890123456789012345678901234567890123456789012345678901234";
string encodedIv = "1111111111222222222233333333334444444444555555555566666666667777";
string key, iv;

StringSource ssk(encodedKey, true /*pumpAll*/,
    new HexDecoder(
        new StringSink(key)
    ) // HexDecoder
); // StringSource

StringSource ssv(encodedIv, true /*pumpAll*/,
    new HexDecoder(
        new StringSink(iv)
    ) // HexDecoder
); // StringSource

运行上面的代码后,key and iv是十六进制(即二进制)字符串而不是可打印(即 ASCII)字符串。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

获取 AES 256 Crypto++ 中的十六进制加密字符串 的相关文章

随机推荐