Search code examples
.netencryptionpasswordsrijndaelmanaged

Does Rijndael always throw an exception if the password isn't correct?


I'm using Rijndael to encrypt/decrypt some sensitive images that will be used on some documents. I'm trying to be absolutely sure that the password provided works and that, by some quirk of fate, an incorrect password will result in a corrupted image that ends up on the document. If I don't catch it before this point, lots of documents and money will end up getting thrown away.

My current plan is to create a MD5 checksum to store along with the images. If the decrypted stream's MD5 is different than the original stream, I know the password was incorrect. However, in testing, it appears that an incorrect password results in an exception being thrown.

Is that true 100% of the time? Can I do away with the checksum and just catch an exception?


Solution

  • With all symmetric key algorithms in .Net the verification occurs at the last block, which contains the padding info (usually PKCS7). If the last decrypted block does not contain a valid padding info, it will be assumed that the data is 'bad' (or the key is 'bad'). For cipher chainning block modes, this method is fairly good, as there is a very low probability of a accidental colission that matches a valid padding info format. For ECB modes things change, but ECB mode is broken anyway and should never be used.

    Many applications use 'magic' numbers and text at the start of the data to validate the decrypted content format. 100%, bulletproof accuracy would require that you probably add an HMAC of your own to the data. If you have control over your format, then I'd highly recommend signing the encrypted data.