How to salt and hash a password value using c#?

The most popular way to do this is using a hashing algorithm. There's an excellent blog post here about how to use the MD5 algorithm to hash a string, but there are many other examples in the System.Cryptography namespace.

As for #2, the general step-by-step guide to how this would work would be the following:

On registration:

  1. Hash a user's password using your specified algorithm and store it in the database
  2. Salt this hash (optional, but preferred)

On login / user & password check:

  1. Look up in the database for the username
  2. If it exists, retrieve the hashed password
  3. Hash and salt the entered password and compare it to the retrieved password

It's all relatively long-winded, but it's very secure.

There's another extremely in-depth guide on hashing and salting here.


Simple hash:

public string GetSHA256Hash(string s)
        {
            if (string.IsNullOrEmpty(s))
            {
                throw new ArgumentException("An empty string value cannot be hashed.");
            }

            Byte[] data = System.Text.Encoding.UTF8.GetBytes(s);
            Byte[] hash = new SHA256CryptoServiceProvider().ComputeHash(data);
            return Convert.ToBase64String(hash);
        }

Tags:

C#

Passwords

Hash