Search code examples
securityencryptioncryptographyaescrypto++

Is a "block padding" exception expected when using the wrong key during decryption?


I am currently working on a password manager for my own and the encryption process of the database is working perfectly fine comparing the result I get with test vector.

To decrypt the ciphertext, I am trying to use code I found on the web but if I give the program the wrong decryption key, I get an exception. I wanted to know if it is safe to catch this exception or if it's something I'm doing wrong.

The code I have is :

CryptoPP::CBC_Mode<CryptoPP::AES>::Decryption aesDecryption;
aesDecryption.SetKeyWithIV(derivedKey, sizeof(derivedKey), initVector);

// The StreamTransformationFilter removes
//  padding as required.
CryptoPP::StringSource ss(encryptedString, true,
    new CryptoPP::StreamTransformationFilter(aesDecryption,
        new CryptoPP::StringSink(decryptedData)
    ) // StreamTransformationFilter
); // StringSource

where derivedKey is an unsigned char* generated by PBKDF2, initVector is also an unsigned char*, encryptedString is a string containing the data I want to decrypt and decryptedData is a string to put the decrypted data.

If I execute this code using the right derivedKey, everything works fine. But if I try using a wrong derivedKey, I get the following error from Crypto++:

StreamTransformationFilter: invalid PKCS #7 block padding found

I'd like to know if this is normal when the key given to the StreamTransformationFitler isn't the right one, or if this error can occur from something else.


Solution

  • Yes, this can happen with wrong keys.

    If the correct key gives this exception too, your code is wrong, but apparently this isn't happening.

    But note that this exception is not guaranteed to occur with wrong keys. Some data with some wrong key will generate the exception, others won't (then the decrypted data is garbage). If you want a reliable way to dedect wrong keys, you'll an additional "checksum" part, just in a secure way. Eg. CBC-MACs with a different key.

    What this exception means:
    AES works with data blocks of 16 byte size. If the data length is no a multiple of 16 (eg. 16, 32, 48 is ok, but not 1, 20, 45 etc.), then it's necessary to add some byte to your original data before encrypting it, so that it becomes a multiple of 16. This is called padding. After decrypting, this padding data must be removed again to get your original data.
    The "problem" is now that when encrypting, the library uses specific byte values for it's padding data; and after decrypting, it checks if the values match. If not, you'll get this exception. And with a wring key, giving wrong data when decrypting, it's unlikely that the padding part is correct.