Bad*_*ari 5 c# database security encryption
我使用Visual C#内置功能设置来保存我的一些程序选项.我还想存储一个密码,但随后公开...是否可以在使用此设置方法保存密码之前加密密码然后将其解密?
对于简单的加密需求,我通过ProtectedData类使用了 DPAPI 。为了使生成的加密值可存储在文本文件或注册表中,我对生成的字节数组进行编码。
这是我为总结这一点而编写的课程:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)