app.config文件是否是存储密码的安全位置?

时间:2012-04-10 11:30:57

标签: c# .net winforms passwords app-config

我需要在代码中存储机密密码。我不能使用哈希技术,因为密码本身是必需的。如何在app.config文件中安全地存储这些数据?

我还有其他方法可以安全地完成这项工作吗?

DPAPI和ProtectData Class不是一个选项,因为密钥是系统特定的,例如:连接字符串不能以这种方式存储给不同的最终用户系统。

1 个答案:

答案 0 :(得分:9)

您可以使用DPAPI(数据保护API)加密配置文件的某些部分。您的代码仍将使用ConfigurationManager,并且框架将对解密进行解密。有关相同的更多信息,请参阅此模式和实践文档How To: Encrypt Configuration Sections in ASP.NET 2.0 Using DPAPI

<强>更新

要加密或解密代码中的信息,您可以使用ProtectedData.Protect&amp; ProtectedData.Unprotect。这可以作为安装程序中自定义操作的一部分运行,也可以在用户使用应用程序时输入凭据时运行。

示例代码

class SecureStringManager
{
    readonly Encoding _encoding = Encoding.Unicode;

    public string Unprotect(string encryptedString)
    {
        byte[] protectedData = Convert.FromBase64String(encryptedString);
        byte[] unprotectedData = ProtectedData.Unprotect(protectedData,
            null, DataProtectionScope.CurrentUser);

        return _encoding.GetString(unprotectedData);
    }

    public string Protect(string unprotectedString)
    {
        byte[] unprotectedData = _encoding.GetBytes(unprotectedString);
        byte[] protectedData = ProtectedData.Protect(unprotectedData, 
            null, DataProtectionScope.CurrentUser);

        return Convert.ToBase64String(protectedData);
    }
}      
相关问题