问题
I am trying to implement the AES 256 algorithm using Crypto++ in MS visual studio. Operating system is Windows 7 (64 bit).
I need to provide the key as a hexadecimal string, password as string and finally i want the encrypted string to also be hexadecimal string.
Here is what I am trying to do:
My encrypt method:
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;
}
From main method
int main(int argc, char* argv[]) {
encrypt("test");
return 0;
}
At present I am hardcoding the key just for debugging purposes. My key is hexadecimal string as seen below. I need to get the output encrypted string as hex string.
回答1:
I need to provide the key as a hexadecimal string, password as string and finally i want the encrypted string to also be hexadecimal string.
This is covered in the Crypto++ wiki (there's lots of examples in there ready for copy/paste). From HexDecoder's Scripting and Strings:
On occasion, the mailing list will receive questions on cross-validation. For example, see AES CTR Chiper. Different output between PHP-mcrypt and Crypto++. In the question, PHP-mcrypt strings are used as follows:
$key = "1234567890123456789012345678901234567890123456789012345678901234"; $key = pack("H".strlen($key), $key); $iv = "1111111111222222222233333333334444444444555555555566666666667777"; $iv = pack("H".strlen($iv), $iv);
One of the easiest ways to avoid typos is via Copy/Paste and a 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
After running the above code, key
and iv
are hexadecimal (i.e., binary) strings rather than printable (i.e., ASCII) strings.
来源:https://stackoverflow.com/questions/21896874/get-hexadecimal-encrypted-string-in-aes-256-crypto