尽我最大的努力,我无法纠正我的 Decrypt 方法引发的异常。在将数据转换为字节缓冲区数组的那一行,将引发 ArgumentNullException。首先我添加了一个:
if (String.IsNullOrEmpty(data))
{
throw new ArgumentNullException ("Null data");
}
同样对于密码,我做了同样的代码。然后,在 if 语句中弹出相同的异常后,我将其更改为下面的 try-catch 语句。现在异常不会出现在 try-catch 行上,而是出现在 Decrypt 的缓冲区转换行上。我不太确定程序想要什么,因为我认为 try-catch 可以解决问题,但我对 C# 也很陌生,所以我可能会遗漏一些明显的东西。
public static string Encrypt (string data, string password)
{
if (String.IsNullOrEmpty(data as string))
{
throw new ArgumentException("Null data.");
}
if (String.IsNullOrEmpty(password as string))
{
throw new ArgumentException("Null password.");
}
using (SymmetricAlgorithm alg = GetAlgorithm(password))
using (MemoryStream ms = new MemoryStream())
using (CryptoStream cs = new CryptoStream (ms, alg.CreateEncryptor(), CryptoStreamMode.Write))
{
byte[] buffer = Encoding.UTF8.GetBytes(data);
cs.Write(buffer, 0, buffer.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
}
public static string Decrypt (string data, string password)
{
try
{
String.IsNullOrEmpty(data);
}
catch
{
throw new ArgumentException("Null data.");
}
try
{
String.IsNullOrEmpty(password);
}
catch
{
throw new ArgumentException("Null password.");
}
using (SymmetricAlgorithm alg = GetAlgorithm(password))
using (MemoryStream ms = new MemoryStream())
using (CryptoStream cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write))
{
byte[] buffer = Convert.FromBase64String(data);//This is where the exception occurs
cs.Write(buffer, 0, buffer.Length);
cs.FlushFinalBlock();
buffer = ms.ToArray();
return Convert.ToBase64String(buffer);
}
}