Salted Hashed Passwords

Saving passwords for your application must be done with caution. Especialy when securing websites. Leaked databases have been exposed all over the internet.
In the event your database is exposed you want to make it as hard as possible to crack the passwords, so you have enought time to inform your users and let them change their passwords. Maybe event disable the users that haven’t changed their passwords.
I’ve written a util class that generates a salt and hashes strings (like passwords) with a salt. Using a salt to encrypt the password makes it hard to crack it. The salt is attached to the password and than the complete string is encrypted with the key. See below:

public static class SaltUtil
{
    public static string GenerateRandomSalt()
    {
        // use Random Number Generator
        RNGCryptoServiceProvider algoritm = new RNGCryptoServiceProvider();    
        // request a byte array with random numbers of length 16
        byte[] buff = new byte[16];
        algoritm.GetBytes(buff);    
        // return the string respresentation
        return Convert.ToBase64String(buff);
    }
    public static string GenerateSaltedHash(string password, string salt) 
    {
        System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
        // use SHA256 bit
        byte[] key = encoding.GetBytes("Your key here");
        HashAlgorithm algorithm = new HMACSHA256(key);
        // combine password and salt
        byte[] combinedPasswordAndSalt = encoding.GetBytes(string.Concat(password, salt));
        // compute the hash from password with salt
        byte[] hash = algorithm.ComputeHash(combinedPasswordAndSalt);
        // return the string representation
        return Convert.ToBase64String(hash);
    }
}

On creation of a user you can generate a salt and hash the password. ! Make sure to save the salt as the code will generate a new salt every time !
Feel free to use this code and to comment on this below.

About erictummers

Working in a DevOps team is the best thing that happened to me. I like challenges and sharing the solutions with others. On my blog I’ll mostly post about my work, but expect an occasional home project, productivity tip and tooling review.
This entry was posted in Security and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.