我试图通过密码解密文件(使用相同的密码加密),但是它会抛出异常并且我不确定在哪里查看。
这就是我生成密码的方式
using (var rijndael = System.Security.Cryptography.Rijndael.Create())
{
rijndael.GenerateKey();
var key = Convert.ToBase64String(rijndael.Key);
MessageBox.Show(key, "Key created", MessageBoxButton.OK, MessageBoxImage.Information);
Account.CreateAccount(key);
Console.WriteLine(Account.Save(key));
Clipboard.SetText(key);
}
以及我如何保存帐户(返回true并创建加密文件)
private const int SaltSize = 8;
...
public static bool Save(string password)
{
try
{
var keyGenerator = new Rfc2898DeriveBytes(password, SaltSize);
var rijndael = Rijndael.Create();
rijndael.IV = keyGenerator.GetBytes(rijndael.BlockSize / 8);
rijndael.Key = keyGenerator.GetBytes(rijndael.KeySize / 8);
using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
fs.Write(keyGenerator.Salt, 0, SaltSize);
using (var cryptoStream = new CryptoStream(fs, rijndael.CreateEncryptor(), CryptoStreamMode.Write))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(cryptoStream, map);
}
fs.Close();
}
return true;
}
catch(ArgumentNullException e)
{
return false;
}
}
以及我如何加载该文件(返回-1并抛出异常)
public static int Load(String password)
{
Dictionary<string, Account> ret;
var salt = new byte[SaltSize];
var keyGenerator = new Rfc2898DeriveBytes(password, salt);
var rijndael = Rijndael.Create();
rijndael.IV = keyGenerator.GetBytes(rijndael.BlockSize / 8);
rijndael.Key = keyGenerator.GetBytes(rijndael.KeySize / 8);
try
{
using (Stream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
using (var cryptoStream = new CryptoStream(fs, rijndael.CreateDecryptor(), CryptoStreamMode.Read))
{
fs.Read(salt, 0, SaltSize);
if (fs.Length.Equals(0))
{
return 0;
}
BinaryFormatter binaryFormatter = new BinaryFormatter();
ret = (Dictionary<string, Account>)binaryFormatter.Deserialize(cryptoStream);
}
map = ret;
return 1;
}
catch(Exception e)
{
return -1;
}
}
在加载时输出
抛出异常:&#39; System.Runtime.Serialization.SerializationException&#39;在mscorlib.dll中 抛出异常:&#39; System.Security.Cryptography.CryptographicException&#39;在mscorlib.dll中 抛出异常:&#39; System.Runtime.Serialization.SerializationException&#39;在mscorlib.dll中 抛出异常:&#39; System.Security.Cryptography.CryptographicException&#39;在mscorlib.dll中 抛出异常:&#39; System.Runtime.Serialization.SerializationException&#39;在mscorlib.dll中 抛出异常:&#39; System.Security.Cryptography.CryptographicException&#39;在mscorlib.dll中 -1