我的目标是编写一个可以加密密码并将其写入文件的简单控制台应用程序。然后读取文件(使用加密的密码)并解密文本以获得密码 我正在关注本文以及此处给出的C#示例: https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.protecteddata?view=netframework-4.8
我正在使用的代码:
using System;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;
namespace CreatePasswordFile
{
class CreatePasswordFile
{
static string PasswordFilePath;
static byte[] s_aditionalEntropy = { 1,2,3,4,5,6,7,8,9,10 };
static void Main(string[] args)
{
string plainPassword;
string PasswordFilePath = @"D:\PasswordFiles\Password.txt";
string PasswordFileEncryptedPath = @"D:\PasswordFiles\EncryptedPassword.txt";
using (StreamReader sr = new StreamReader(PasswordFilePath))
{
plainPassword = sr.ReadLine();
}
var passwordbytes = plainPassword.ToCharArray().Select(c => Convert.ToByte(c)).ToArray();
byte[] encryptedBytes1 = Protect(passwordbytes);
var encryptedString = Encoding.Unicode.GetString(encryptedBytes1);
WriteToFile(PasswordFileEncryptedPath, encryptedString);
string encryptedText = ReadEnryptedFile(PasswordFileEncryptedPath);
byte[] encryptedBytes2 = Encoding.Unicode.GetBytes(encryptedText);
byte[] originalPlainPassword = UnProtect(encryptedBytes2);
}
private static byte[] UnProtect(byte[] secret)
{
return ProtectedData.Unprotect(secret, s_aditionalEntropy, DataProtectionScope.CurrentUser);
}
private static string ReadEnryptedFile(string passwordFileEncryptedPath)
{
string returnValue = string.Empty;
using (StreamReader sr = new StreamReader(passwordFileEncryptedPath))
{
returnValue = sr.ReadLine();
}
return returnValue;
}
private static void WriteToFile(string passwordFileEncryptedPath, string encryptedSecret)
{
using (StreamWriter sw = new StreamWriter(passwordFileEncryptedPath))
{
sw.WriteLine(encryptedSecret);
}
}
private static byte[] Protect(byte[] passwordBytes)
{
return ProtectedData.Protect(passwordBytes, s_aditionalEntropy, DataProtectionScope.CurrentUser);
}
}
}
我得到这样的异常: System.Security.dll中发生了类型为'System.Security.Cryptography.CryptographicException'的未处理异常 消息:{“密钥在指定状态下无效。\ r \ n”}
此方法中发生异常:
private static byte[] UnProtect(byte[] secret)
{
return ProtectedData.Unprotect(secret, s_aditionalEntropy, DataProtectionScope.CurrentUser);
}
知道为什么会这样吗? 注意:我正在Visual Studio中运行此程序,因此DataProtectionScope.CurrentUser应该始终指向我的帐户(除非我在这里错了)。