How to hash a password

后端 未结 9 787
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 14:49

I\'d like to store the hash of a password on the phone, but I\'m not sure how to do it. I can only seem to find encryption methods. How should the password be hashed properl

9条回答
  •  长发绾君心
    2020-11-22 15:38

    Use the below class to Generate a Salt first. Each user needs to have a different salt, we can save it in the database along with the other user properties. The rounds value decides the number of times the password will be hashed.

    For more details: https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.rfc2898derivebytes.-ctor?view=netcore-3.1#System_Security_Cryptography_Rfc2898DeriveBytes__ctor_System_Byte___System_Byte___System_Int32_

    public class HashSaltWithRounds
    {
        int saltLength = 32;
        public byte[] GenerateSalt()
        {
            using (var randomNumberGenerator = new RNGCryptoServiceProvider())
            {
                var randomNumber = new byte[saltLength];
                randomNumberGenerator.GetBytes(randomNumber);
                return randomNumber;
            }
        }
    
        public string HashDataWithRounds(byte[] password, byte[] salt, int rounds)
        {
            using(var rfc2898= new Rfc2898DeriveBytes(password, salt, rounds))
            {
                return Convert.ToBase64String(rfc2898.GetBytes(32));
            }
        }
    }
    

    We can call it from a console application as follows. I have hashed the password twice using the same salt.

    public class Program
    {
        public static void Main(string[] args)
        {
            int numberOfIterations = 99;
            var hashFunction = new HashSaltWithRounds();
    
            string password = "Your Password Here";
            byte[] salt = hashFunction.GenerateSalt();
    
            var hashedPassword1 = hashFunction.HashDataWithRounds(Encoding.UTF8.GetBytes(password), salt, numberOfIterations);
            var hashedPassword2 = hashFunction.HashDataWithRounds(Encoding.UTF8.GetBytes(password), salt, numberOfIterations);
    
            Console.WriteLine($"hashedPassword1 :{hashedPassword1}");
            Console.WriteLine($"hashedPassword2 :{hashedPassword2}");
            Console.WriteLine(hashedPassword1.Equals(hashedPassword2));
    
            Console.ReadLine();
    
        }
    }
    

提交回复
热议问题