I am encryption/decryption some plain text using following code.
private static string EncryptionKey = "@#$%^&*()2343";
private static byte[] Salt = Encoding.ASCII.GetBytes(EncryptionKey.Length.ToString());
public static string EncryptIt(string Input)
{
RijndaelManaged Cipher = new RijndaelManaged();
byte[] TextByteArray = Encoding.Unicode.GetBytes(Input);
PasswordDeriveBytes Key = new PasswordDeriveBytes(EncryptionKey, Salt);
using (ICryptoTransform Transform = Cipher.CreateEncryptor(Key.GetBytes(32), Key.GetBytes(16)))
{
using (MemoryStream MS = new MemoryStream())
{
using (CryptoStream CS = new CryptoStream(MS, Transform, CryptoStreamMode.Write))
{
CS.Write(TextByteArray, 0, TextByteArray.Length);
CS.FlushFinalBlock();
return Convert.ToBase64String(MS.ToArray());
}
}
}
}
public static string DecryptIt(string Input)
{
RijndaelManaged Cipher = new RijndaelManaged();
byte[] EncryptedByteArray = Convert.FromBase64String(Input);
PasswordDeriveBytes Key = new PasswordDeriveBytes(EncryptionKey, Salt);
using (ICryptoTransform Transform = Cipher.CreateDecryptor(Key.GetBytes(32), Key.GetBytes(16)))
{
using (MemoryStream MS = new MemoryStream(EncryptedByteArray))
{
using (CryptoStream cryptoStream = new CryptoStream(MS, Transform, CryptoStreamMode.Read))
{
byte[] TransformedText = new byte[EncryptedByteArray.Length];
int Count = cryptoStream.Read(TransformedText, 0, TransformedText.Length);
return Encoding.Unicode.GetString(TransformedText, 0, Count);
}
}
}
}
In most of the cases, this code works fine. However in some cases when I try to decrypt the encrypted text, I get following exception when byte[] EncryptedByteArray = Convert.FromBase64String(Input)
is called in DecryptIt
methods.
The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters.
Any idea what could be causing this exception. What I am finding more puzzling is that why this excpetion is not thrown on every cases and only few cases.
EDIT : Sample Input to DecryptIt method that throws exception is below. Please note that I have changed the value of EncryptionKey variable in my sample above.
oaOQ6qWWDwWby3C04N7HJAiqQgILBifqdHq4OQ5KDDRA3F2ZlBITu31a8mJJQ8sKn4g3vODFEJbigtNZozv6ockAdsDChhHwaaLL4l8MJPKbV1EiUE3rL30y+xHz/S1a8mJJQ8sKn4g3vODFEJbigtNZozv6ockAdsDChhHwaaLL4l8MJPKbV1EiUE3rL30y+oz/eR9OzXn+3Lepo0tRqH5BsfvEtJ/IcqRu3gJiIBTMAM0TmVxa2EZSj2mn6jZlgvlOEFCWzNKS3R9OzXn+In1br14venJmpApXyt930khz35UE5BtWn3Fq7jyer6mY2l60P/cI4z