我正在使用Visual C#内置功能设置来保存我的程序选项。我还想存储一个密码,但这使得它变成公共的...是否可以在使用此设置方法保存之前对密码进行加密,然后再解密回来?
我正在使用Visual C#内置功能设置来保存我的程序选项。我还想存储一个密码,但这使得它变成公共的...是否可以在使用此设置方法保存之前对密码进行加密,然后再解密回来?
对于简单的加密需求,我使用DPAPI通过ProtectedData类。为了使结果加密值可以存储在文本文件或注册表中,我对结果字节数组进行编码。
这是我编写的包装类:
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);
}
}
}