Click to See Complete Forum and Search --> : PKCS7 padding is invalid and cannot be removed


d00_ape
November 29th, 2004, 03:36 AM
Hi. I’m trying to dectypt a string I got from my supplier.

We have a common password and I got a string to decrypt using

System.Security.Cryptography.RijndaelManaged

Here is my decrypt function:

public string DecryptWithRijndael( string Key, string strDecode )
{

ASCIIEncoding textConverter = new ASCIIEncoding();
RijndaelManaged myRijndael = new RijndaelManaged();
// set mode
myRijndael.Mode = CipherMode.ECB; // Set mode
myRijndael.Padding = PaddingMode.PKCS7; // Set padding
byte[] key = textConverter.GetBytes(Key); //Create a new key and initialization vector

// Get final key and initialization vector
myRijndael.Key=key;
myRijndael.GenerateIV();

byte[] IV = myRijndael.IV;

byte[] encrypted = Convert.FromBase64String( strDecode );

//Get a decryptor that uses the same key and IV as the encryptor.
ICryptoTransform decryptor = myRijndael.CreateDecryptor(key, IV);


//Now decrypt the previously encrypted message using the decryptor
// obtained in the above step
MemoryStream msDecrypt = new MemoryStream(encrypted);
CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
byte[] fromEncrypt = new byte[encrypted.Length];

//Read the data out of the crypto stream

csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);

//Convert the byte array back into a string
string sDecoded = textConverter.GetString(fromEncrypt);
return sDecoded;
}
On the line:
“csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);”

I got the following message:

An unhandled exception of type 'System.Security.Cryptography.CryptographicException' occurred in mscorlib.dll
Additional information: PKCS7 padding is invalid and cannot be removed.

Any tip on what I may have done wrong… ?