Search code examples
c#pkcs#7rijndaelmanagedcryptostream

CryptoStream error Padding is invalid and cannot be removed


i have problem with my code. Problem occures in function Decryptor.

FlushFinalBlock throw "Padding is invalid and cannot be removed"

In function Decryptor i get myData of length 6048, when line cryptoStream.Write(myData, 0, myData.Length); is done i get length 6032 in memoryStream and then the line cryptoStream.FlushFinalBlock(); throws an error "Padding is invalid and cannot be removed."

As you can see i am using Padding = PaddingMode.PKCS7;

static RijndaelManaged rmCrypto;
static object lockCryptoStream = new object();

public static void SetrmCrypto()
{
    rmCrypto = new RijndaelManaged();
    rmCrypto.Padding = PaddingMode.PKCS7;
    rmCrypto.KeySize = 128;
    rmCrypto.Key = new ASCIIEncoding().GetBytes("xxxxxxxxxxxxxxxx");
    rmCrypto.IV = new ASCIIEncoding().GetBytes("yyyyyyyyyyyyyyyy");
}

public static byte[] Encryptor(byte[] myData)
{
    lock (lockCryptoStream)
    {
        using (var memoryStream = new MemoryStream())
        {
            using (var cryptoStream = new CryptoStream(memoryStream, rmCrypto.CreateEncryptor(rmCrypto.Key, rmCrypto.IV), CryptoStreamMode.Write))
            {
                cryptoStream.Write(myData, 0, myData.Length);
                cryptoStream.FlushFinalBlock();
                cryptoStream.Close();
                return memoryStream.ToArray();
            }
        }
    }
}

public static byte[] Decryptor(byte[] myData)
{
    lock (lockCryptoStream)
    {
        using (var memoryStream = new MemoryStream())
        {
            using (var cryptoStream = new CryptoStream(memoryStream, rmCrypto.CreateDecryptor(rmCrypto.Key, rmCrypto.IV), CryptoStreamMode.Write))
            {
                cryptoStream.Write(myData, 0, myData.Length);
                cryptoStream.FlushFinalBlock();
                cryptoStream.Close();
                return memoryStream.ToArray();
            }
        }
    }
}

Encryptor is used on server, and data are sent through UDP. Client using Decryptor than decrypt the data. Code works for most of the packets and lets say it works for some hours but then after while i get that error on Flushing.


Solution

  • upper code works great. problem in my case was on server which was typed in c++ and i had problems with that encryption (thread problems on receiving and sending)