简体   繁体   English

MVC-如何哈希和加盐

[英]MVC - How to hash and salt

I managed to get hash working, but the salt-part is still an issue.. I've been searching and testing examples without success. 我设法使哈希工作,但盐的部分仍然是一个问题。.我一直在搜索和测试示例,但未成功。 This is my code with hash: 这是我的哈希代码:

        [Required]
        [StringLength(MAX, MinimumLength = 3, ErrorMessage = "min 3, max 50 letters")]
        public string Password { get; set; }
        public string Salt { get; set; }

Hash password function(without salt): 哈希密码功能(无盐):

 public string HashPass(string password) { 

       byte[] encodedPassword = new UTF8Encoding().GetBytes(password);
       byte[] hash = ((HashAlgorithm) CryptoConfig.CreateFromName("MD5")).ComputeHash(encodedPassword);
       string encoded = BitConverter.ToString(hash).Replace("-", string.Empty).ToLower();

          return encoded;//returns hashed version of password
      }

Register: 寄存器:

        [HttpPost]
        public ActionResult Register(User user) {
            if (ModelState.IsValid) {

                        var u = new User {
                            UserName = user.UserName,                               
                            Password = HashPass(user.Password)//calling hash-method
                        };

                        db.Users.Add(u);
                        db.SaveChanges();

                    return RedirectToAction("Login");
                }
            }return View();    
        }

Login: 登录:

     public ActionResult Login() {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(User u) {
            if (ModelState.IsValid) 
            {
                using (UserEntities db = new UserEntities()) {

                    string readHash = HashPass(u.Password);

                    var v = db.Users.Where(a => a.UserName.Equals(u.UserName) &&
                                              a.Password.Equals(readHash)).FirstOrDefault();
                    if (v != null) {

                        return RedirectToAction("Index", "Home"); //after login
                    }
                }
            }return View(u);
        }

So far hash work.. But how do I make salt work here? 到目前为止,哈希工作..但是我如何使盐在这里工作?

I would prefer a demonstrate on my code as I find it very hard to understand by words. 我希望在我的代码上进行演示,因为我很难用文字来理解。

I'm using database first. 我先使用数据库。

When it comes to security don't try to reinvent the wheel. 当涉及到安全性时,请勿尝试重新发明轮子。 Use Claims based authentication. 使用基于声明的身份验证。

If you still must manage usernames and passwords use Hash-based message authentication code ( HMAC ) 如果仍然必须管理用户名和密码,请使用基于哈希的消息身份验证代码( HMAC

I would also recommend investing sometime and reading Enterprise Security Best Practices . 我还建议您花一些时间阅读《 企业安全最佳实践》 There are already smarter people who solved this problems why reinvent the wheel. 已经有更聪明的人解决了这个问题,为什么需要重新发明轮子。 And .NET has all the goodies there. .NET在那里具有所有优势。

Example below: 下面的例子:

//--------------------MyHmac.cs-------------------
public static class MyHmac
{
    private const int SaltSize = 32;

    public static byte[] GenerateSalt()
    {
        using (var rng = new RNGCryptoServiceProvider())
        {
            var randomNumber = new byte[SaltSize];

            rng.GetBytes(randomNumber);

            return randomNumber;

        }
    }

    public static byte[] ComputeHMAC_SHA256(byte[] data, byte[] salt)
    {
        using (var hmac = new HMACSHA256(salt))
        {
            return hmac.ComputeHash(data);
        }
    }
}



//-------------------Program.cs---------------------------
string orgMsg = "Original Message";
        string otherMsg = "Other Message";


        Console.WriteLine("HMAC SHA256 Demo in .NET");

        Console.WriteLine("----------------------");
        Console.WriteLine();

        var salt = MyHmac.GenerateSalt();

        var hmac1 = MyHmac.ComputeHMAC_SHA256(Encoding.UTF8.GetBytes(orgMsg), salt);
        var hmac2 = MyHmac.ComputeHMAC_SHA256(Encoding.UTF8.GetBytes(otherMsg), salt);


        Console.WriteLine("Original Message Hash:{0}", Convert.ToBase64String(hmac1));
        Console.WriteLine("Other Message Hash:{0}", Convert.ToBase64String(hmac1));

NOTE: Salts do not have to be kept secret and can be stored alongside the hash itself. 注意:盐不必保密,可以与哈希值本身一起存储。 It's to increase security from rainbow table attack. 这是为了提高彩虹表攻击的安全性。

Use the System.Web.Helpers.Crypto NuGet package from Microsoft. 使用Microsoft的System.Web.Helpers.Crypto NuGet程序包。 It takes care of the salt for you. 它为您照顾盐。

You hash a password like this: var hash = Crypto.HashPassword("foo"); 您可以像这样对密码进行哈希处理: var hash = Crypto.HashPassword("foo");

You verify a password like this: var verified = Crypto.VerifyHashedPassword(hash, "foo"); 您可以像这样验证密码: var verified = Crypto.VerifyHashedPassword(hash, "foo");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM