I needed some simple string encryption, so I wrote the following code (with a great deal of \"inspiration\" from here):
// create and initialize a crypto
Yes, this is to be expected, or at least, its exactly what happens when our crypto routines get non-decryptable data
I experienced a similar "Padding is invalid and cannot be removed." exception, but in my case the key IV and padding were correct.
It turned out that flushing the crypto stream is all that was missing.
Like this:
MemoryStream msr3 = new MemoryStream();
CryptoStream encStream = new CryptoStream(msr3, RijndaelAlg.CreateEncryptor(), CryptoStreamMode.Write);
encStream.Write(bar2, 0, bar2.Length);
// unless we flush the stream we would get "Padding is invalid and cannot be removed." exception when decoding
encStream.FlushFinalBlock();
byte[] bar3 = msr3.ToArray();
If you want your usage to be correct, you should add authentication to your ciphertext so that you can verify that it is the correct pasword or that the ciphertext hasn't been modified. The padding you are using ISO10126 will only throw an exception if the last byte doesn't decrypt as one of 16 valid values for padding (0x01-0x10). So you have a 1/16 chance of it NOT throwing the exception with the wrong password, where if you authenticate it you have a deterministic way to tell if your decryption is valid.
Using crypto api's while seemingly easy, actually is rather is easy to make mistakes. For example you use a fixed salt for for you key and iv derivation, that means every ciphertext encrypted with the same password will reuse it's IV with that key, that breaks semantic security with CBC mode, the IV needs to be both unpredictable and unique for a given key.
For that reason of easy to make mistakes, I have a code snippet, that I try to keep reviewed and up to date (comments, issues welcome):
Modern Examples of Symmetric Authenticated Encryption of a string C#.
If you use it's AESThenHMAC.AesSimpleDecryptWithPassword(ciphertext, password)
when the wrong password is used, null
is returned, if the ciphertext or iv has been modified post encryption null
is returned, you will never get junk data back, or a padding exception.