AES CBC および CTR モードを使用してデータを復号化しようとしています。暗号文の前に 16 バイトの IV が付加されています。
次の形式の暗号文データがあります。
vector<vector<byte>> CBCMessages;
vector<vector<byte>> CBCKeys;
vector<vector<byte>> CTRMessages;
vector<vector<byte>> CTRKeys;
Crypto++ を使用してデータを復号化しています。これは私のコードです:
for (int i = 0; i < CBCMessages.size(); i++)
{
std::string decryptedtext;
// split IV from ciphertext
byte iv[16];
std::copy(CBCMessages[i].begin(), CBCMessages[i].begin()+16, iv);
CBCMessages[i].erase(CBCMessages[i].begin(), CBCMessages[i].begin()+16);
// this block works fine
AES::Decryption aesDecryption(&(CBCKeys[i][0]), CBCKeys[i].size());
CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );
StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
stfDecryptor.Put( reinterpret_cast<const unsigned char*>( &(CBCMessages[i][0]) ), CBCMessages[i].size() );
stfDecryptor.MessageEnd();
std::cout << decryptedtext << std::endl;
}
for (int i = 0; i < CTRMessages.size(); i++)
{
std::string decryptedtext;
// split IV from ciphertext
byte iv[16];
std::copy(CTRMessages[i].begin(), CTRMessages[i].begin()+16, iv);
CTRMessages[i].erase(CTRMessages[i].begin(), CTRMessages[i].begin()+16);
// this block produces junk
AES::Decryption aesDecryption(&(CTRKeys[i][0]), CTRKeys[i].size());
CTR_Mode_ExternalCipher::Decryption ctrDecryption( aesDecryption, iv );
StreamTransformationFilter stfDecryptor(ctrDecryption, new CryptoPP::StringSink( decryptedtext ) );
stfDecryptor.Put( reinterpret_cast<const unsigned char*>( &(CTRMessages[i][0]) ), CTRMessages[i].size() );
stfDecryptor.MessageEnd();
std::cout << decryptedtext << std::endl;
// try again with different method - this works fine
decryptedtext.clear();
CTR_Mode< AES >::Decryption d;
d.SetKeyWithIV( &(CTRKeys[i][0]), CTRKeys[i].size(), iv, 16 );
StringSource( reinterpret_cast<const unsigned char*>( &(CTRMessages[i][0]) ), CTRMessages[i].size(), true,
new StreamTransformationFilter( d,
new StringSink( decryptedtext )
)
);
std::cout << decryptedtext << std::endl;
}
ご覧のとおり、中央のブロック (CTR 復号化の最初のブロック) はジャンク出力を生成します。このブロックは、実際には CBC 復号化に使用されるブロックとほぼ同じである必要があることに注意してください。
CBC 復号化に使用されるブロックは、基本的にこの FAQ エントリからコピーされます (2005-Oct-21 10:38am jeffrey までに回答)。次に、このブロックを変更して、機能しないときの CTR 復号化に使用しました。2 番目の CTR ブロックは、こちらの「サンプル プログラム」セクションに触発されています。
最初の CTR コード ブロックの問題は何ですか?