简体   繁体   中英

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 )

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.

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. It takes care of the salt for you.

You hash a password like this: var hash = Crypto.HashPassword("foo");

You verify a password like this: var verified = Crypto.VerifyHashedPassword(hash, "foo");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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