Hi,
I have been experimenting with the RijndaelManaged Cryptography class in C#
and have stumbled upon a "peculiarity".
Following code is standalone Console App that demonstrates
using System;
using System.Text;
using System.IO;
using System.Security.Cryptography;
namespace EncryptTheMAC
{
class Program1
{
static void Main(string[] args)
{
string Password = "password";
string MAC = "00:01:36:09:32:88";
SymmetricAlgorithm myAlg = new RijndaelManaged();
byte[] saltValueBytes = Encoding.ASCII.GetBytes(Password);
PasswordDeriveBytes passwordKey = new
PasswordDeriveBytes(Password, saltValueBytes, "SHA1", 3);
myAlg.Key = passwordKey.GetBytes(myAlg.KeySize / 8);
myAlg.IV = passwordKey.GetBytes(myAlg.BlockSize / 8);
byte[] Data = Encoding.ASCII.GetBytes(MAC);
ICryptoTransform myEncrypter = myAlg.CreateEncryptor();
MemoryStream mStream = new MemoryStream();
CryptoStream csEncrypt = new CryptoStream(mStream, myEncrypter,
CryptoStreamMode.Write);
csEncrypt.Write(Data, 0, Data.Length);
csEncrypt.FlushFinalBlock();
csEncrypt.Close();
mStream.Close();
byte[] EncryptedData = mStream.ToArray();
//
// De-Encrypt the Data
//
string Password1 = "password1";
SymmetricAlgorithm myAlg1 = new RijndaelManaged();
byte[] saltValueBytes1 = Encoding.ASCII.GetBytes(Password1);
PasswordDeriveBytes passwordKey1 = new
PasswordDeriveBytes(Password1, saltValueBytes1, "SHA1", 3);
myAlg1.Key = passwordKey1.GetBytes(myAlg1.KeySize / 8);
myAlg1.IV = passwordKey1.GetBytes(myAlg1.BlockSize / 8);
ICryptoTransform myDecryptor = myAlg1.CreateDecryptor();
MemoryStream msOutput = new MemoryStream(EncryptedData);
CryptoStream DecryptStream = new CryptoStream(msOutput,
myDecryptor, CryptoStreamMode.Read);
StreamReader sr = new StreamReader(DecryptStream);
string ab = sr.ReadLine();
Console.WriteLine(ab);
Console.ReadLine();
}
}
}
If I change the definition of variable "Password1" to be something different
from the original value at the start of the program, the third line from the
end
string ab = sr.ReadLine();
causes an Exception
"Padding is invalid and cannot be removed"
The only way it appears that I can get around this is to put a
try...catch... around the sr.ReadLine().
I would have expected the sr.ReadLine() line to have returned random data,
not raise an exception. I have searched on MSDN and various other sources
and cannot find any thing of value. Is it possible that I am using the
cryptography API's incorrectly. Code above is duplicated in places to show
the error.
Thanks in advance