Hello everyone,
Im developing an application in C# for a school project that encrypts data in text form using a password and vice versa, and i' d need some help with something.
The program encrypts fine taking as input 1)the data (reading it from textbox) and 2)the password, and stores the encrypted data to a text file.
When decrypting it asks for a password. Here is the case: If the password is correct, it decrypts the text file and shows the original data. If the password is wrong, normally the algorithm should work and return wrong data... but in my case, it doesnt.
I get the following error (when wrong pass for decryption) : "Padding is invalid and cannot be removed"
I would need some help, here is the source code for the encrypt/decrypt methods:
public static string EncryptData(string text, string password)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Mode = CipherMode.CBC;
rijndaelCipher.Padding = PaddingMode.PKCS7;
rijndaelCipher.KeySize = 128;
rijndaelCipher.BlockSize = 128;
byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(password);
byte[] keyBytes = new byte[16];
int len = pwdBytes.Length;
if (len > keyBytes.Length) len = keyBytes.Length;
System.Array.Copy(pwdBytes, keyBytes, len);
rijndaelCipher.Key = keyBytes;
rijndaelCipher.IV = keyBytes;
ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
byte[] plainText = Encoding.UTF8.GetBytes(text);
byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);
return Convert.ToBase64String(cipherBytes);
}
public static string DecryptData(string text, string password)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Mode = CipherMode.CBC;
rijndaelCipher.Padding = PaddingMode.PKCS7;
rijndaelCipher.KeySize = 128;
rijndaelCipher.BlockSize = 128;
byte[] encryptedData = Convert.FromBase64String(text);
byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(password);
byte[] keyBytes = new byte[16];
int len = pwdBytes.Length;
if (len > keyBytes.Length) len = keyBytes.Length;
System.Array.Copy(pwdBytes, keyBytes, len);
rijndaelCipher.Key = keyBytes;
rijndaelCipher.IV = keyBytes;
ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length); [B]//Debugger shows error is here[/B]
return Encoding.UTF8.GetString(plainText);
}
I would appreciate some help,
Thanks,
Perry