0

我最近一直在尝试“CryptoStream”,并遇到了通过加密和解密文本的想法。Aes 类。'命名空间:System.Security.Cryptography'

在使用两个输入参数创建成功加密文本的函数后:文本、密码

static byte[] Salt = { 18,39,27,48,82,32,12,92 };
        public static string EncryptAES(string txt, string Password) {
            Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(Password, Salt);
            RijndaelManaged RJM = new RijndaelManaged();
            RJM.Key = rfc.GetBytes(RJM.KeySize / 8);
            ICryptoTransform ICT = Aes.Create().CreateEncryptor(RJM.Key, RJM.IV);

            using (MemoryStream MS = new MemoryStream()) {
                using (CryptoStream CS = new CryptoStream(MS, ICT, CryptoStreamMode.Write)) {
                    using (StreamWriter SW = new StreamWriter(CS)) {
                        SW.Write(txt);
                    }
                }

                return Convert.ToBase64String(MS.ToArray());
            }
        }

解密文本的问题发生了。

我解密文本的尝试如下:

public static string DecryptAES(string EncryptedTxt, string Password) {
            Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(EncryptedTxt, Salt);
            RijndaelManaged RJM = new RijndaelManaged();
            RJM.Key = rfc.GetBytes(RJM.KeySize / 8);
            ICryptoTransform ICT = Aes.Create().CreateDecryptor(RJM.Key, RJM.IV);
            using (MemoryStream MS = new MemoryStream(Convert.FromBase64String(EncryptedTxt))) {
                using (CryptoStream CS = new CryptoStream(MS, ICT, CryptoStreamMode.Read)) {
                    using (StreamReader SR = new StreamReader(CS)) {
                        return SR.ReadToEnd();
                    }
                }
            }

然而; 看来我将内存流转换为字符串然后返回的方式无效,因为我收到以下错误:错误:值不能为空\n参数名称:inputBuffer

错误发生在使用 (MemoryStream MS = new MemoryStream(Convert.FromBase64String(EncryptedTxt)))

如何将 MemoryStream 转换为字符串并返回?

提前致谢 :-)

4

0 回答 0