Fixed by replacing AesManaged with equivalent Rijndael (BlockSize = 16 bytes, KeySize = 32 bytes). The error has gone. Mono cryptography is just broken.
Remind me please, why we are still stuck to out-of-date, suboptimal, and buggy version of Mono?
It appears that not every encryption mode is supported by .net 2.0 subset, switching to full .net 2.0 api compatibility or choosing a different encryption mode might work.
AesCryptoServiceProvider not supported by .net 2.0 subset.
AesManaged supported.
I tried DES then. For DES “Bad PKCS7 padding. Invalid lengh x” exception was fixed by specifying padding in encryptor and decryptor methods for DesCryptoServiseProvider.
I get the other error,when do Decrypt.
Error is : CryptographicException: Bad PKCS7 padding. Invalid length 154.
at System.Security.Cryptography.CryptoStream.Read
Can anyone please share a solution? I am running into the same issue. What makes me curious is that it is a sometimes issue and doesn’t happen on the editor (or maybe not enough lucky to see it appear on the editor?). My code is pasted below:
private const string KeyString = "my-32-byte-secret-key-go-here...";
public static byte[] EncryptToByte(string plainText)
{
byte[] cipherData;
Aes aes = Aes.Create();
aes.Key = Encoding.UTF8.GetBytes(KeyString);
aes.GenerateIV();
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
ICryptoTransform cipher = aes.CreateEncryptor(aes.Key, aes.IV);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, cipher, CryptoStreamMode.Write))
{
using (StreamWriter sw = new StreamWriter(cs))
{
sw.Write(plainText);
}
}
cipherData = ms.ToArray();
}
byte[] combinedData = new byte[aes.IV.Length + cipherData.Length];
Array.Copy(aes.IV, 0, combinedData, 0, aes.IV.Length);
Array.Copy(cipherData, 0, combinedData, aes.IV.Length, cipherData.Length);
return combinedData;
}
public static string DecryptFromByte(byte[] combinedData)
{
string plainText;
Aes aes = Aes.Create();
aes.Key = Encoding.UTF8.GetBytes(KeyString);
byte[] iv = new byte[aes.BlockSize / 8];
byte[] cipherText = new byte[combinedData.Length - iv.Length];
Array.Copy(combinedData, iv, iv.Length);
Array.Copy(combinedData, iv.Length, cipherText, 0, cipherText.Length);
aes.IV = iv;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
ICryptoTransform decipher = aes.CreateDecryptor(aes.Key, aes.IV);
using (MemoryStream ms = new MemoryStream(cipherText))
{
using (CryptoStream cs = new CryptoStream(ms, decipher, CryptoStreamMode.Read))
{
using (StreamReader sr = new StreamReader(cs))
{
plainText = sr.ReadToEnd();
}
}
return plainText;
}
}