"PKCS7 padding is invalid and cannot be removed" solution/explanation



I believe this error is due to the use of a variable width stream.
Until the stream has been closed it's size is variable. It must
therefore be converted into a fixed buffer before being used for
decryption. For example:

MemoryStream keyContainer = new MemoryStream();

Console.Write("Enter a string to encrypt: ");
text = Console.ReadLine();

// if text is smaller than the min block size it must
// be padded
// note: this assumes 1byte/char - the default UTF8 uses 2
bytes/char
if ( (text.Length*8) < alg.LegalBlockSizes[0].MinSize )
text = text.PadLeft(alg.LegalBlockSizes[0].MinSize / 8);

Console.WriteLine("Padded text to {0}", text);

CryptoStream cstream = new CryptoStream(keyContainer,
alg.CreateEncryptor(key, initializationVector),
CryptoStreamMode.Write);
StreamWriter encWriter = new StreamWriter(cstream, Encoding.ASCII /*
1 byte/character */);

encWriter.Write(text);
encWriter.Close();

byte[] encBytes = keyContainer.ToArray();
StreamReader encReader = new StreamReader(new
MemoryStream(encBytes), Encoding.ASCII);
string encText = encReader.ReadToEnd();
Console.WriteLine("Encrypted textlength={0}, text={1}",
encText.Length, encText);

.