在我的应用程序中,我需要加密各种设置和密码。到目前为止,我一直在使用 RijndaelManaged 类等执行此操作,如下所示:
/// <summary>
/// Encrypts the string defined by parameter "data" and returns the encrypted data as string
/// </summary>
/// <param name="data">Data to be encrypted</param>
/// <returns>The encrypted data</returns>
public static string Encrypt(string data)
{
if (data == "")
return "";
byte[] bytes = Encoding.ASCII.GetBytes(initVector);
byte[] rgbSalt = Encoding.ASCII.GetBytes(saltValue);
byte[] buffer = Encoding.UTF8.GetBytes(data);
byte[] rgbKey = new PasswordDeriveBytes(passPhrase, rgbSalt, hashAlgorithm, passwordIterations).GetBytes(keySize / 8);
RijndaelManaged managed = new RijndaelManaged();
managed.Mode = CipherMode.CBC;
ICryptoTransform transform = managed.CreateEncryptor(rgbKey, bytes);
MemoryStream memStream = new MemoryStream();
CryptoStream cryStream = new CryptoStream(memStream, transform, CryptoStreamMode.Write);
cryStream.Write(buffer, 0, buffer.Length);
cryStream.FlushFinalBlock();
byte[] inArray = memStream.ToArray();
memStream.Close();
cryStream.Close();
return Convert.ToBase64String(inArray);
}
通常的问题是我需要将密码(和 saltValue)存储在某个地方。为了以 sequre 方式存储密码,我遇到了 DPAPI Protect() 和 Unprotect() 类,如下所示:
/// <summary>
/// Use Windows' "Data Protection API" to encrypt the string defined by parameter "clearText".
/// To decrypt, use the method "Unprotect"
/// http://www.thomaslevesque.com/2013/05/21/an-easy-and-secure-way-to-store-a-password-using-data-protection-api/
/// </summary>
/// <param name="clearText"></param>
/// <param name="optionalEntropy"></param>
/// <param name="scope"></param>
/// <returns></returns>
public static string Protect(string clearText, string optionalEntropy = null, DataProtectionScope scope = DataProtectionScope.CurrentUser)
{
if (clearText == null)
throw new ArgumentNullException("The parameter \"clearText\" was empty");
byte[] clearBytes = Encoding.UTF8.GetBytes(clearText);
byte[] entropyBytes = string.IsNullOrEmpty(optionalEntropy) ? null : Encoding.UTF8.GetBytes(optionalEntropy);
byte[] encryptedBytes = ProtectedData.Protect(clearBytes, entropyBytes, scope);
return Convert.ToBase64String(encryptedBytes);
}
我的问题如下: 使用 DPAPI,我现在可以以安全的方式存储我的加密方法的密码,但为什么我不应该简单地使用 DPAPI 直接加密我的所有设置?这是否会用大量数据填充 DPAPI,而这并不意味着它?
我的想法不是执行以下操作:
string setting1 = ”mySettingValue1”;
StoreSettingSomewhere(Encrypt(setting1));
我可以执行以下操作:
string setting1 = ”mySettingValue1”;
StoreSettingSomewhere(Protect(setting1, bla bla bla));
我知道在使用 DPAPI 时,我必须在同一台机器(或同一用户)上解密,但这对我来说不是问题。
任何帮助表示赞赏!