WPF-本地保存登录账号密码
时间: 2023-07-27 20:31:35 浏览: 98
您可以使用.NET Framework中的System.Security命名空间提供的ProtectedData类来保护您的敏感信息,例如登录凭据。ProtectedData类使用当前用户的登录凭据,以及可选的数据保护范围,对数据进行加密和解密。
以下是一个使用ProtectedData类保存和读取登录凭据的示例:
```csharp
using System.Security.Cryptography;
// 保存登录凭据
public void SaveCredentials(string username, string password)
{
byte[] usernameBytes = Encoding.UTF8.GetBytes(username);
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
byte[] protectedUsername = ProtectedData.Protect(usernameBytes, null, DataProtectionScope.CurrentUser);
byte[] protectedPassword = ProtectedData.Protect(passwordBytes, null, DataProtectionScope.CurrentUser);
File.WriteAllBytes("credentials.dat", protectedUsername.Concat(protectedPassword).ToArray());
}
// 读取登录凭据
public (string, string) LoadCredentials()
{
byte[] protectedData = File.ReadAllBytes("credentials.dat");
byte[] protectedUsername = protectedData.Take(protectedData.Length / 2).ToArray();
byte[] protectedPassword = protectedData.Skip(protectedData.Length / 2).ToArray();
byte[] usernameBytes = ProtectedData.Unprotect(protectedUsername, null, DataProtectionScope.CurrentUser);
byte[] passwordBytes = ProtectedData.Unprotect(protectedPassword, null, DataProtectionScope.CurrentUser);
string username = Encoding.UTF8.GetString(usernameBytes);
string password = Encoding.UTF8.GetString(passwordBytes);
return (username, password);
}
```
请注意,此示例仅适用于本地保存登录凭据。如果您需要在多个设备之间同步凭据,则需要使用不同的方法。