Home About

December 9th, 2008

Creating salted hash passwords in C# - 3

Hash values have many uses in computing: for storing password tokens, securing that a file hasn’t been tampered with, or to create a short semi-unique signature for a larger data set. A hash algorithm takes a data set — such as a string — and turns it into a numeric value of a certain length.

This article will go into how to create a hash of your passwords and how salting them makes them more secure.

What is a hash?

A hash function turns “Hello World” into “3964322768″. And it does that every time you run that same string through the hash function. How it does that depends on the hash algorithm, and so does the “3964322768″ result.

Different hash function return different results, but given the same data the same function always returns the same result.

Now imagine transferring a block of 2Kb of data across the Internet — at the end of it you include an extra hash. The receiver can check if the data received was all transferred correctly, if a bit had fallen over the data block would have generated a different hash.

On collisions

In the “old days” CRC16 was used to ensure that data was being transmitted correctly over telephone and serial lines. As modems became faster and the data send increased collisions became more frequent, leading to corrupted transfers. The CRC-16 was a 16-bit value, so it could only generate 2^16 = 65535 unique values.

By making the hash longer the chance that two sets of data share the same hash value (a collision) decreases. It is important to realize that this chance will never reach zero! It is entirely (though often unlikely) possible that your program will have two strings that generate the same hash.

Using hashes to store passwords

Hashes are useful as a one-way method to store passwords. In a typical scenario a user types his password and the system generates the hash and compares this with a hash stored on file.

It is not possible to reverse the password from a hash. Thus if someone gets hold of the password file they cannot reverse the original passwords.

Salting the hash

Hashes however are still open to one of the oldest attacks: the dictionary attack. Your system will likely lock out a users after several failed password attempts. If however through a security breach an attacker obtains your hashed password file (or part thereof) it is possible to apply one of many standard dictionaries against the found hashes:

  1. Obtain hashed passwords (through online snooping, hacking)
  2. Use dictionary software which contains pre-computed hash values for common passwords
  3. See if the result matches , if so : password found
  4. The hacker can now login and impersonate the user

The dictionary attack can be blunted. By adding a unique salt to each hash the attacker needs to re-calculate the dictionary for each users password, greatly increasing the attack time.

A salt is a random set of bytes which are added to the data set before calculating the hash.

  1. User enters password for the first time
  2. The system adds a salt to the password (for example 4 bytes of random data)
  3. The system generates and stores the hash together with the salt

When the user returns for another login the system does the following:

  1. The users enters the password
  2. The system looks up the stored hash + salt
  3. The system tries if a new hash of the given password + salt matches the stored hash
  4. If they match the user can login

A Salted Hash implementation in C#

The following implementation demonstrates how you can implement a Salted Hash in C#. The class defaults to using SHA256Managed hash algorithm, and a salt size of 32 bits. You can however call the class with any other HashAlgorithm derived class (such as for example: SHA1Managed,SHA256Managed, SHA384Managed, SHA512Managed and MD5CryptoServiceProvider) and specify a salt size of any length.

The SaltedHash class provides two routines that do all the leg work:

void GetHashAndSalt(byte[] Data, out byte[] Hash, out byte[] Salt)

This routine generates the hash and a random salt for a given set of bytes.

bool VerifyHash(byte[] Data, byte[] Hash, byte[] Salt)

This routine checks if the data passed, together with the stored salt will generate the same hash as we had earlier calculated.

For convenience two more functions allow us to work with strings directly instead of byte arrays:

public void GetHashAndSaltString(string Data, out string Hash, out string Salt)

This routine takes a C# hash string and returns both the Hash and Salt as Base-64 encoded string.

public bool VerifyHashString(string Data, string Hash, string Salt)

The counterpart to the GetHashAndSaltString function, this routine allows us to use verify whether a string returns the same hash with the given salt.

using System;
using System.Security.Cryptography;
using System.Text;

namespace SaltedHash
    class SaltedHash
        HashAlgorithm HashProvider;
        int SalthLength;

        /// <summary>
        /// The constructor takes a HashAlgorithm as a parameter. 
        /// </summary>
        /// <param name="HashAlgorithm">
        /// A <see cref="HashAlgorithm"/> HashAlgorihm which is derived from HashAlgorithm. C# provides
        /// the following classes: SHA1Managed,SHA256Managed, SHA384Managed, SHA512Managed and MD5CryptoServiceProvider
        /// </param>

        public SaltedHash(HashAlgorithm HashAlgorithm, int theSaltLength)
            HashProvider = HashAlgorithm;
            SalthLength = theSaltLength;

        /// <summary>
        /// Default constructor which initialises the SaltedHash with the SHA256Managed algorithm
        /// and a Salt of 4 bytes ( or 4*8 = 32 bits)
        /// </summary>

        public SaltedHash() : this(new SHA256Managed(), 4)

        /// <summary>
        /// The actual hash calculation is shared by both GetHashAndSalt and the VerifyHash functions
        /// </summary>
        /// <param name="Data">A byte array of the Data to Hash</param>
        /// <param name="Salt">A byte array of the Salt to add to the Hash</param>
        /// <returns>A byte array with the calculated hash</returns>

        private byte[] ComputeHash(byte[] Data, byte[] Salt)
            // Allocate memory to store both the Data and Salt together
            byte[] DataAndSalt = new byte[Data.Length + SalthLength];

            // Copy both the data and salt into the new array
            Array.Copy(Data, DataAndSalt, Data.Length);
            Array.Copy(Salt, 0, DataAndSalt, Data.Length, SalthLength);

            // Calculate the hash
            // Compute hash value of our plain text with appended salt.
            return HashProvider.ComputeHash(DataAndSalt);

        /// <summary>
        /// Given a data block this routine returns both a Hash and a Salt
        /// </summary>
        /// <param name="Data">
        /// A <see cref="System.Byte"/>byte array containing the data from which to derive the salt
        /// </param>
        /// <param name="Hash">
        /// A <see cref="System.Byte"/>byte array which will contain the hash calculated
        /// </param>
        /// <param name="Salt">
        /// A <see cref="System.Byte"/>byte array which will contain the salt generated
        /// </param>

        public void GetHashAndSalt(byte[] Data, out byte[] Hash, out byte[] Salt)
            // Allocate memory for the salt 
            Salt = new byte[SalthLength];

            // Strong runtime pseudo-random number generator, on Windows uses CryptAPI
            // on Unix /dev/urandom
            RNGCryptoServiceProvider random = new RNGCryptoServiceProvider();

            // Create a random salt

            // Compute hash value of our data with the salt.
            Hash = ComputeHash(Data, Salt);

        /// <summary>
        /// The routine provides a wrapper around the GetHashAndSalt function providing conversion
        /// from the required byte arrays to strings. Both the Hash and Salt are returned as Base-64 encoded strings.
        /// </summary>
        /// <param name="Data">
        /// A <see cref="System.String"/> string containing the data to hash
        /// </param>
        /// <param name="Hash">
        /// A <see cref="System.String"/> base64 encoded string containing the generated hash
        /// </param>
        /// <param name="Salt">
        /// A <see cref="System.String"/> base64 encoded string containing the generated salt
        /// </param>

        public void GetHashAndSaltString(string Data, out string Hash, out string Salt)
            byte[] HashOut;
            byte[] SaltOut;

            // Obtain the Hash and Salt for the given string
            GetHashAndSalt(Encoding.UTF8.GetBytes(Data), out HashOut, out SaltOut);

            // Transform the byte[] to Base-64 encoded strings
            Hash = Convert.ToBase64String(HashOut);
            Salt = Convert.ToBase64String(SaltOut);

        /// <summary>
        /// This routine verifies whether the data generates the same hash as we had stored previously
        /// </summary>
        /// <param name="Data">The data to verify </param>
        /// <param name="Hash">The hash we had stored previously</param>
        /// <param name="Salt">The salt we had stored previously</param>
        /// <returns>True on a succesfull match</returns>

        public bool VerifyHash(byte[] Data, byte[] Hash, byte[] Salt)
            byte[] NewHash = ComputeHash(Data, Salt);

            //  No easy array comparison in C# -- we do the legwork
            if (NewHash.Length != Hash.Length) return false;

            for (int Lp = 0; Lp < Hash.Length; Lp++ )
                if (!Hash[Lp].Equals(NewHash[Lp]))
                    return false;

            return true;

        /// <summary>
        /// This routine provides a wrapper around VerifyHash converting the strings containing the
        /// data, hash and salt into byte arrays before calling VerifyHash.
        /// </summary>
        /// <param name="Data">A UTF-8 encoded string containing the data to verify</param>
        /// <param name="Hash">A base-64 encoded string containing the previously stored hash</param>
        /// <param name="Salt">A base-64 encoded string containing the previously stored salt</param>
        /// <returns></returns>

        public bool VerifyHashString(string Data, string Hash, string Salt)
            byte[] HashToVerify = Convert.FromBase64String(Hash);
            byte[] SaltToVerify = Convert.FromBase64String(Salt);
            byte[] DataToVerify = Encoding.UTF8.GetBytes(Data);
            return VerifyHash(DataToVerify, HashToVerify, SaltToVerify);


    /// <summary>
    /// This little demo code shows how to encode a users password.
    /// </summary>

    class SaltedHashDemo
        public static void Main(string[] args)
            // We use the default SHA-256 & 4 byte length
            SaltedHash demo = new SaltedHash();

            // We have a password, which will generate a Hash and Salt
            string Password = "MyGlook234";
            string Hash;
            string Salt;

            demo.GetHashAndSaltString(Password, out Hash, out Salt);
            Console.WriteLine("Password = {0} , Hash = {1} , Salt = {2}", Password, Hash, Salt);

            // Password validation
            // We need to pass both the earlier calculated Hash and Salt (we need to store this somewhere safe between sessions)

            // First check if a wrong password passes
            string WrongPassword = "OopsOops";
            Console.WriteLine("Verifying {0} = {1}", WrongPassword, demo.VerifyHashString(WrongPassword, Hash, Salt));

            // Check if the correct password passes
            Console.WriteLine("Verifying {0} = {1}", Password, demo.VerifyHashString(Password, Hash, Salt));



Image credit: Looking Glass

Be Sociable, Share!

Tags: , , , , , ,

3 Responses to “Creating salted hash passwords in C#”

  1. Pepe Sasia Says:

    Hi!, i’m using your great implementation of salted hash passwords, It’s nice, but what I really need now is to retrieve a password from a given hash and salt. How can I do that? Have you got this issue resolved? Thank you very much.

  2. Jeff Mu Says:

    The whole point of using a hash and salt is so that you cannot recover the password. You can only compare if the hashs match. Reverisble encryption on passwords isn’t much better than storing password in plain text, if you get the encryption key (for a symetrical encryption) then you have everyone’s password.

    It’s not an issue, is a feature by design…


  3. Haddicus Says:

    In implementation, Pepe, you shouldn’t be able to do this! Salted hashes only allow further authentication by comparing the hash, not by returning the right password. Basic hash theory.

Most popular

    Sorry. No data so far.

Recent Comments
  • Juan Romero: Hi there, it’s a neat little class, but I believe you could do the same thing with the WebClient...
  • anthosh: Hey, THank you very much for your tutorial. It was awesome. But i have a problem that i am not able to...
  • bian: how to get passphase if i have encrypt and decrypt string?? Thanks alot
  • Michael: Hi, I really like your post, thanks a lot, it really helped clear up a few things I could not remember how...
  • Bharat Prajapati: i was trying to import keyword dictionary to this plugin which is in csv format, but i get an error...