Asp.net MVC - How to hash password

前端 未结 3 636
时光说笑
时光说笑 2020-12-16 06:00

How do I hash an users input(password) to database and then later read the hashed password during login?

I believe the solution is to hash the password upon registe

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-16 06:46

    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:

    using System.Security.Cryptography;
    using System.Text;
    
    //--------------------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(hmac2));
    

    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. Please don't post same question twice. Duplicate from here.

提交回复
热议问题