CryptoStream错误填充无效,无法删除

时间:2015-10-16 07:57:48

标签: c# pkcs#7 rijndaelmanaged cryptostream

我的代码有问题。 问题在Decryptor中出现。

FlushFinalBlock throw “填充无效,无法删除”

在函数Decryptor中我得到长度为6048的myData, line cryptoStream.Write(myData,0,myData.Length);完成后我在memoryStream中得到长度6032 然后是行cryptoStream.FlushFinalBlock();抛出错误“填充无效,无法删除。”

如您所见,我正在使用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而不是解密数据。 代码适用于大多数数据包,并且可以说它可以工作几个小时,但之后我在Flushing上得到错误。

1 个答案:

答案 0 :(得分:0)

上层代码效果很好。 在我的情况下的问题是在用c ++输入的服务器上,我遇到了加密问题(接收和发送时的线程问题)