AesCryptoServiceProvider解密

时间:2014-12-13 14:39:08

标签: c# encryption aes aescryptoserviceprovider

我正在尝试使用此功能进行解密,但我不确定导致其失败的原因

  public string Decrypt(byte[] cipherText, byte[] IV, byte[] key)
    {

        using (AesCryptoServiceProvider AESDecrypt = new AesCryptoServiceProvider())
        {

            //here we set the key and IV instead having the class generate them.
            AESDecrypt.IV = IV;
            AESDecrypt.Key = key;

            ICryptoTransform decryptor = AESDecrypt.CreateDecryptor(AESDecrypt.Key, 
                                 AESDecrypt.IV);

            using (MemoryStream msDecrypt = new MemoryStream(cipherText))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, 
                     decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                    {
                        csDecrypt.Flush();
                        plainText = srDecrypt.ReadToEnd();
                        return plainText;
                    }
                }
            }
       }

    }

plainText返回一个空字符串。密钥和IV是在先前函数中生成的系统,并且正在正确传递。

1 个答案:

答案 0 :(得分:0)

我误读了第一个问题的答案并使用.flushfinalblock让它返回“密文”而没有真正解决根本问题。当我移动cipher = msEncrypt.ToArray();在加密流之外它完美地工作。并删除.flush()。 .FacePalm()