存储web api凭据的安全方法?

时间:2013-07-15 15:06:02

标签: c# asp.net sql-server security cryptography

我的网络应用程序登录到web api。这需要一个电子邮件和密码。我不能在我的数据库中哈希这些,因为api需要明文密码。

如何以比纯文本,xor或base64更安全的方式存储我的web api凭据?对于这种事情,有没有“适当的”解决方案?

1 个答案:

答案 0 :(得分:2)

是的,ProtectedData类,它允许您加密绑定到Windows用户帐户的对象,因此如果将user.config文件复制到另一个用户/计算机,它将无法正常工作

在您的设置文件中,创建两个名为ApiUsernameApiPassword的字符串属性,然后点击顶部的“查看代码”并添加以下功能

internal sealed partial class Settings {

    private MD5 md5 = MD5.Create();
    public global::System.Net.NetworkCredential ApiLogin
    {
        get
        {
            global::System.Net.NetworkCredential tmp = null;
            if (ApiPassword != "")
            {
                tmp = new System.Net.NetworkCredential();
                tmp.UserName = ApiUsername;
                try
                {
                    tmp.Password = System.Text.Encoding.UTF8.GetString(ProtectedData.Unprotect(Convert.FromBase64String(ApiPassword), md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(ApiUsername.ToUpper())), DataProtectionScope.CurrentUser));
                }
                catch
                {
                    tmp.Password = "";
                }
            }
            return tmp;
        }
        set
        {
            global::System.Net.NetworkCredential tmp2 = value;
            ApiUsername = tmp2.UserName;
            ApiPassword = Convert.ToBase64String(ProtectedData.Protect(System.Text.Encoding.UTF8.GetBytes(tmp2.Password), md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(tmp2.UserName.ToUpper())), DataProtectionScope.CurrentUser));

        }
    }
}

这将添加一个名为ApiLogin的可访问属性,该属性将包含带有解密密码的NetworkCredential,当您将凭据保存到磁盘时,它将其存储在无法复制到其他用户的受保护的受保护表单中

如果解密失败,则会在返回的凭据中将密码设置为空白。如果您希望decrption在该单个计算机上的任何useraccount上工作,请将ProtectionScope更改为DataProtectionScope.LocalMachine