Search code examples
c++encryptioncryptographycrypto++

AES decryption and 'invalid pkcs #7 block padding'


I have this code to try decryption:

byte key[AES::DEFAULT_KEYLENGTH];
string key_s = "essasenhaehfraca";

for (int i = 0; i < key_s.size(); i++)
    key[i] = (byte) key_s[i];

string ciphertext = "A506A19333F306AC2C62CBE931963AE7DFCFFA940360A40FFD5DC69B9C2E53AD"
string decryptedtext;

try
{
    ECB_Mode< AES >::Decryption decryptor;
    decryptor.SetKey(key, sizeof(key));
    CryptoPP::StringSource(ciphertext, true,
            new CryptoPP::StreamTransformationFilter( decryptor,
                new CryptoPP::StringSink( decryptedtext )
            )
    );

}
catch(const CryptoPP::Exception& e)
{
    cerr << e.what() << endl;
    system("pause");
    exit(1);
}

return 0;

When I execute it, I get the exception StreamTransformationFilter: invalid pkcs #7 block padding found. I searched and didn't find anything. Someone knows why I get this error? Every example I found in the internet is in this same way and none of them mention this error.


Solution

  • It looks like your Cipher text is hex-encoded. You need to add a HexDecoder to your decryption stream:

    CryptoPP::StringSource ss(ciphertext, true,
        new CryptoPP::HexDecoder(
            new CryptoPP::StreamTransformationFilter( decryptor,
                new CryptoPP::StringSink( decryptedtext ) ) ) );