CryptoStream 报错 Padding is invalid and cannot be removed

CryptoStream error Padding is invalid and cannot be removed

我的代码有问题。 函数 Decryptor 出现问题。

FlushFinalBlock 抛出 "Padding is invalid and cannot be removed"

在函数 Decryptor 中,我得到长度为 6048 的 myData, 当行 cryptoStream.Write(myData, 0, myData.Length);完成后我在 memoryStream 中得到长度 6032 然后是行 cryptoStream.FlushFinalBlock();抛出错误 "Padding is invalid and cannot be removed."

如您所见,我正在使用 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();
            }
        }
    }
}

服务器使用加密器,数据通过UDP发送。 客户端使用 Decryptor 而不是解密数据。 代码适用于大多数数据包,可以说它可以工作几个小时,但之后我在法拉盛上遇到了那个错误。

上面的代码效果很好。 在我的案例中,问题出在用 C++ 键入的服务器上,我在加密方面遇到了问题(接收和发送时的线程问题)