I am using the following:
RijndaelManaged rm = new RijndaelManaged();
encryptor = rm.CreateEncryptor(key, vector);
decryptor = rm.CreateDecryptor(key, vector);
rm.Padding = PaddingMode.None;
This works good for me. However when I try to intentionally use an incorrect key I get an exception when decoding here:
public byte[] Decrypt(byte[] buffer) {
MemoryStream decryptStream = new MemoryStream();
using (CryptoStream cs = new CryptoStream(decryptStream, decryptor, CryptoStreamMode.Write)) {
cs.Write(buffer, 0, buffer.Length);
}
return decryptStream.ToArray();
}
System.Security.Cryptography.CryptographicException was unhandled by user code
Message=Padding is invalid and cannot be removed.
Is there some way I can cleanly manage this and is this to be expected if I on purpose use the WRONG key?
Now I changed this to the following based on a suggestion below:
public byte[] Decrypt(byte[] buffer)
{
try {
MemoryStream decryptStream = new MemoryStream();
using (CryptoStream cs = new CryptoStream(decryptStream, decryptor, CryptoStreamMode.Write))
{
cs.Write(buffer, 0, buffer.Length);
}
return decryptStream.ToArray();
} catch(CryptographicException e){
//... do something with it ...
return null;
}
}
How can I pass up the exception to the next method which is:
public string DecryptFromUrl(string encrypted)
{
return Decrypt(HttpUtility.UrlDecode(encrypted));
}