Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to verify password which is store in database as a hash value?

Tags:

c#

asp.net

I want to store password in an encrypted form. I have used sha256. My code is as below

public static string ComputeHash(string plainText)
    {
        int minSaltSize = 4;
        int maxSaltSize = 8;

        Random random = new Random();
        int saltSize = random.Next(minSaltSize, maxSaltSize);

        byte[] saltBytes = new byte[saltSize];
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        rng.GetNonZeroBytes(saltBytes);

        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
        byte[] plainTextWithSaltBytes = new byte[plainTextBytes.Length + saltBytes.Length];

        for (int i = 0; i < plainTextBytes.Length; i++)
            plainTextWithSaltBytes[i] = plainTextBytes[i];

        for (int i = 0; i < saltBytes.Length; i++)
            plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];


        HashAlgorithm hash = new SHA256Managed();
        byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);
        byte[] hashWithSaltBytes = new byte[hashBytes.Length + saltBytes.Length];

        for (int i = 0; i < hashBytes.Length; i++)
            hashWithSaltBytes[i] = hashBytes[i];

        for (int i = 0; i < saltBytes.Length; i++)
            hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];

        string hashValue = Convert.ToBase64String(hashWithSaltBytes);
        return hashValue;
    }

Now when user login i want to verify this password How can i do that??

like image 511
vaishali Avatar asked Dec 12 '22 18:12

vaishali


1 Answers

Take the plain text password from the user, hash it with the same algorithm and compare the freshly generated hash with the hash stored within the database. If both hashes are the same, the user entered the correct password.

Update

You use everytime a freshly random salt, thous leading to the different hashes. Simply make a new column within your database containing the salt used and take this one.

It is not a security problem to save the salt together with the hash. The salt will only prohibit the simple usage of pre-calculated rainbow-tables for a single hash-algorithm if it would be used directly. It doesn't give any clue about the real password that was used and also not about how the salt is combined with the plain-text password (prepend, append, inter-weaved, ...), so it can safely be stored next to the generated hash.

like image 89
Oliver Avatar answered Mar 23 '23 00:03

Oliver