我正在实现加密/解密方法,如本示例所示。问题是
EncryptString
方法中的字节数组为空;因此,结果字符串也是空的。怎么解决问题?
using System.Security.Cryptography;
using System.Text;
Crypto crypto = new();
string test = "test";
string encrypted = crypto.EncryptString(test);
string decrypted = crypto.DecryptString(encrypted);
Console.WriteLine($"{test}\n{encrypted}\n{decrypted}");
Console.ReadKey();
class Crypto
{
byte[] key = Encoding.UTF8.GetBytes("01234567890123456789012345678901");
byte[] iv = new byte[16];
public string EncryptString(string plainText)
{
using Aes aes = Aes.Create();
aes.Key = key;
aes.IV = iv;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using MemoryStream memoryStream = new();
using CryptoStream cryptoStream = new(memoryStream, encryptor, CryptoStreamMode.Write);
using StreamWriter streamWriter = new(cryptoStream);
streamWriter.Write(plainText);
// Array is empty here
byte[] array = memoryStream.ToArray();
return Encoding.UTF8.GetString(array);
}
public string DecryptString(string cipherText)
{
using Aes aes = Aes.Create();
aes.Key = key;
aes.IV = iv;
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
using MemoryStream memoryStream = new(Encoding.UTF8.GetBytes(cipherText));
using CryptoStream cryptoStream = new(memoryStream, decryptor, CryptoStreamMode.Read);
using StreamReader streamReader = new(cryptoStream);
string decrypted = streamReader.ReadToEnd();
return decrypted;
}
}
请注意,在您尝试复制的代码中,它们具有:
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
在调用 StreamWriter
之前,
msEncrypt.ToArray()
已关闭(处置)。在您的代码中,它是不一样的 - StreamWriter
直到作用域结束时才关闭(因为使用语句),因此当使用 memoryStream.ToArray()
时 - 尚未向该流写入任何内容。简单修复:
using MemoryStream memoryStream = new();
using CryptoStream cryptoStream = new(memoryStream, encryptor, CryptoStreamMode.Write);
using StreamWriter streamWriter = new(cryptoStream);
streamWriter.Write(plainText);
streamWriter.Close();
byte[] array = memoryStream.ToArray();
或者更好 - 只是在不必要的地方不要使用范围大小的
using
语句。
此外,加密结果请勿使用 UTF8 编码。加密的结果是二进制数据,而不是文本。如果您必须将其存储为字符串 - 使用诸如 Base64 编码之类的编码,而不是诸如 UTF8 之类的文本编码。