المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Decrypting a text using Rijndael



C# Programming
02-24-2010, 04:21 AM
Hi all, i have been using a Rijndael algorithm to encrypt and decrypt a sequence of bytes, but when i run the code i get the following exeption "Padding is invalid and cannot be removed.", this exeption belongs to decrypt function at line int decryptedByteCount = cryptoStream.Read(pTextBytes, 0, pTextBytes.Length);



i writ my code here:

public static byte[] Encrypt(byte[] clearData)
{
System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
//Get your key from config file to open the lock!
string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));

MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
byte[] keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
hashmd5.Clear();

Rijndael rijKey = Rijndael.Create();
rijKey.Mode = CipherMode.ECB;
rijKey.Padding = PaddingMode.PKCS7;
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms,rijKey.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(clearData, 0, clearData.Length);
cs.FlushFinalBlock();
byte[] cipherTextBytes = ms.ToArray();
ms.Close();
cs.Close();

return cipherTextBytes;
}

public static byte[] Decrypt(byte[] encryptedData)
{
System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
//Get your key from config file to open the lock!
string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
byte[] keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
hashmd5.Clear();

Rijndael rijKey = Rijndael.Create();
rijKey.Mode = CipherMode.ECB;
rijKey.Padding = PaddingMode.PKCS7;
MemoryStream memoryStream = new MemoryStream(encryptedData);
CryptoStream cryptoStream = new CryptoStream(memoryStream, rijKey.CreateDecryptor(),
CryptoStreamMode.Read);
byte[] pTextBytes = new byte[encryptedData.Length];
int decryptedByteCount = cryptoStream.Read(pTextBytes, 0, pTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return pTextBytes;
}
thanks.....................http://www.barakasoft.com/script/Forums/Images/rose.gif