Csharp 在本地记住密码并加密和删除密码的方法
时间: 2024-05-11 12:14:01 浏览: 89
在 C# 中,可以使用 System.Security.Cryptography 命名空间来实现对密码的加密和解密。以下是一个示例代码,演示了如何在本地记住密码并对其进行加密和删除:
```csharp
using System;
using System.IO;
using System.Security.Cryptography;
public class PasswordManager
{
// 密码文件路径
private static string passwordFilePath = "password.bin";
// 加密密钥
private static byte[] key = { 1, 2, 3, 4, 5, 6, 7, 8 };
// 加密向量
private static byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 };
// 加密密码并保存到本地文件
public static void SavePassword(string password)
{
// 创建加密器
var aes = Aes.Create();
aes.Key = key;
aes.IV = iv;
// 加密密码
byte[] encryptedPassword;
using (var encryptor = aes.CreateEncryptor())
using (var ms = new MemoryStream())
using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
using (var sw = new StreamWriter(cs))
{
sw.Write(password);
cs.FlushFinalBlock();
encryptedPassword = ms.ToArray();
}
// 保存加密后的密码到本地文件
File.WriteAllBytes(passwordFilePath, encryptedPassword);
}
// 从本地文件中读取加密的密码并解密
public static string GetPassword()
{
// 如果密码文件不存在,则返回空字符串
if (!File.Exists(passwordFilePath))
{
return "";
}
// 读取加密后的密码
var encryptedPassword = File.ReadAllBytes(passwordFilePath);
// 创建解密器
var aes = Aes.Create();
aes.Key = key;
aes.IV = iv;
// 解密密码
string password;
using (var decryptor = aes.CreateDecryptor())
using (var ms = new MemoryStream(encryptedPassword))
using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
using (var sr = new StreamReader(cs))
{
password = sr.ReadToEnd();
}
return password;
}
// 删除保存在本地文件中的密码
public static void DeletePassword()
{
if (File.Exists(passwordFilePath))
{
File.Delete(passwordFilePath);
}
}
}
```
在这个示例代码中,我们使用了 AES 对密码进行加密和解密。在加密时,将密码写入一个 MemoryStream 中,并通过 CryptoStream 将其加密。在解密时,读取加密后的密码到一个 MemoryStream 中,并通过 CryptoStream 将其解密。加密后的密码保存在本地文件中,可以随时从本地文件中读取并解密。如果需要删除保存在本地文件中的密码,可以使用 DeletePassword 方法。