我正在使用 Visual C# 内置功能设置 来保存我程序的一些选项。 我也想存储一个密码,但后来它公开了...是否可以使用此设置方法在保存密码之前加密密码,然后再将其解密?
最佳答案
为了简单的加密需求,我通过 ProtectedData 使用了 DPAPI类(class)。为了使生成的加密值可存储在文本文件或注册表中,我对生成的字节数组进行编码。
这是我写的用于总结的类:
namespace SomeNamespace
{
using System;
using System.Security.Cryptography;
using System.Text;
/// <summary>
/// used for encryption and decryption
/// </summary>
public static class DataProtector
{
private const string EntropyValue = "secret";
/// <summary>
/// Encrypts a string using the DPAPI.
/// </summary>
/// <param name="stringToEncrypt">The string to encrypt.</param>
/// <returns>The encrypted data.</returns>
public static string EncryptData(string stringToEncrypt)
{
byte[] encryptedData = ProtectedData.Protect(Encoding.Unicode.GetBytes(stringToEncrypt), Encoding.Unicode.GetBytes(EntropyValue), DataProtectionScope.LocalMachine);
return Convert.ToBase64String(encryptedData);
}
/// <summary>
/// Decrypts a string using the DPAPI.
/// </summary>
/// <param name="stringToDecrypt">The string to decrypt.</param>
/// <returns>The decrypted data.</returns>
public static string DecryptData(string stringToDecrypt)
{
byte[] decryptedData = ProtectedData.Unprotect(Convert.FromBase64String(stringToDecrypt), Encoding.Unicode.GetBytes(EntropyValue), DataProtectionScope.LocalMachine);
return Encoding.Unicode.GetString(decryptedData);
}
}
}
关于c# - 使用 C# 设置功能保存密码时的最佳做法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3937095/