在web.config文件中以不可逆加密格式存储密码

时间:2015-04-17 11:10:30

标签: asp.net-mvc-4 c#-4.0 web-config configuration-files password-encryption

我有一个需要验证活动目录帐户的MVC应用程序。我想将帐户名和密码存储在web.config文件中。

我正在寻找的是在web.config文件中以不可逆转的加密格式存储此帐户密码的最佳防弹方式的建议。

然而,我也欢迎另一种接近这一要求的方式,因为我第一次做这种事情,所以我不确定其他人如何在网络上安全地存储密码.config文件,然后从应用程序中读取它。

1 个答案:

答案 0 :(得分:2)

您可以执行以下操作:

https://msdn.microsoft.com/en-us/library/zhhddkxy%28v=vs.140%29.aspx https://msdn.microsoft.com/en-us/library/dtkwfdky(v=vs.140).aspx

那是加密/谴责,但我认为你要求的是单向哈希。如果你想要哈希相当容易,但这需要你在web.config中存储哈希。然后,当登录尝试发生时,您使用预定义的算法对提交的密码进行散列并比较匹配。

如何进行散列: http://www.codeproject.com/Articles/704865/Salted-Password-Hashing-Doing-it-Right

使用已知盐在c#中进行散列的代码。这很久以前从其他地方解除了。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;

namespace Helpers
{
public class SaltedHashPassword
{
    /// <summary>
    /// Hashed password to save.
    /// </summary>
    public string Hash { get; private set; }

    /// <summary>
    /// Salt used to generate the hased password. Save with the password as well.
    /// </summary>
    public string Salt { get; private set; }

    public SaltedHashPassword(string password)
    {
        var saltBytes = new byte[32];
        using (var provider = RandomNumberGenerator.Create())
        {
            provider.GetNonZeroBytes(saltBytes);
        }
        Salt = Convert.ToBase64String(saltBytes);
        var passwordAndSaltBytes = Concat(password, saltBytes);
        Hash = ComputeHash(passwordAndSaltBytes);
    }

    public static bool Verify(string salt, string hash, string password)
    {
        var saltBytes = Convert.FromBase64String(salt);
        var passwordAndSaltBytes = Concat(password, saltBytes);
        var hashAttempt = ComputeHash(passwordAndSaltBytes);
        return hash == hashAttempt;
    }

    static private string ComputeHash(byte[] bytes)
    {
        using (var sha512 = SHA512.Create())
        {
            return Convert.ToBase64String(sha512.ComputeHash(bytes));
        }
    }

    static private byte[] Concat(string password, byte[] saltBytes)
    {
        var passwordBytes = Encoding.UTF8.GetBytes(password);
        return passwordBytes.Concat(saltBytes).ToArray();
    }
}

}

相关问题