加密和解密MemoryStream

时间:2016-11-17 09:16:56

标签: c# encryption

我需要加密并稍后解密MemoryStream(原始的大型PDF文件)。我尝试了以下代码:

    public static string GenerateKey()
    {
        var desCrypto = (DESCryptoServiceProvider)DES.Create();

        return Encoding.ASCII.GetString(desCrypto.Key);
    }

    public static MemoryStream Encrypt(Stream fsInput,string sKey)
    {
        var fsEncrypted=new MemoryStream();

        var des = new DESCryptoServiceProvider
        {
            Key = Encoding.ASCII.GetBytes(sKey),
            IV = Encoding.ASCII.GetBytes(sKey)
        };
        var desencrypt = des.CreateEncryptor();
        var cryptostream = new CryptoStream(fsEncrypted,desencrypt,CryptoStreamMode.Write);

        var bytearrayinput = new byte[fsInput.Length];
        fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
        cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
        fsInput.Close();

        fsEncrypted.Flush();
        fsEncrypted.Position = 0;
        return fsEncrypted;
    }

    public static MemoryStream Decrypt(Stream fsread,string sKey)
    {
        var des = new DESCryptoServiceProvider
        {
            Key = Encoding.ASCII.GetBytes(sKey),
            IV = Encoding.ASCII.GetBytes(sKey)
        };

        var sOutputFilename = new MemoryStream();
        var desdecrypt = des.CreateDecryptor();
        var cryptostreamDecr = new CryptoStream(fsread,desdecrypt,CryptoStreamMode.Read);

        var fsDecrypted = new StreamWriter(sOutputFilename);
        fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
        fsDecrypted.Flush();
        fsDecrypted.Close();
        sOutputFilename.Position = 0;

        return sOutputFilename;
    }

致电示例:

    var sSecretKey = FileHelper.GenerateKey();
    var encyptedPdfContent = FileHelper.Encrypt(httpPostedFile.InputStream, sSecretKey);

    var decryptedPdfContent = FileHelper.Decrypt(encyptedPdfContent, sSecretKey);

加密似乎按预期工作,但是当我尝试解密时

fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());

返回Bad Data例外。

我的代码出了什么问题?

我看到其他帖子,所有帖子都与字符串编码(Encoding.Unicode)有关。我没有字符串。我有一个根本没有编码的内存流!

2 个答案:

答案 0 :(得分:2)

请在解密方法

中添加以下代码
des.Padding = PaddingMode.Zeros;

答案 1 :(得分:1)

您需要在致电cryptoStream之后刷新Write这可以使用FluchFinalBlock来完成:

cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.FlushFinalBlock();

同样在您的Decrypt方法中,您通过关闭StreamWriter来处理退货流,所以只需删除此行:

fsDecrypted.Close();