[英]Get hexadecimal encrypted string in AES 256 Crypto++
我正在尝试使用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的脚本和字符串中 :
有时,邮件列表会收到有关交叉验证的问题。 例如,请参阅AES CTR Chiper。 PHP-mcrypt和Crypto ++之间的输出不同。 在问题中,PHP-mcrypt字符串的用法如下:
$key = "1234567890123456789012345678901234567890123456789012345678901234"; $key = pack("H".strlen($key), $key); $iv = "1111111111222222222233333333334444444444555555555566666666667777"; $iv = pack("H".strlen($iv), $iv);
避免输入错误的最简单方法之一是通过复制/粘贴和HexDecoder:
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
和iv
是十六进制(即二进制)字符串,而不是可打印(即ASCII)字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.