Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

passwords

hash

Hai guys,

I came to know that storing hash value of a password is a safe one from Preferred Method of Storing Passwords In Database...

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

  • How to compare both the values stored in DB and the one given by the user?

like image 439
ACP Avatar asked Jan 05 '10 09:01

ACP


2 Answers

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.

like image 140
Daniel May Avatar answered Oct 04 '22 19:10

Daniel May


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);
        }
like image 27
magnus Avatar answered Oct 04 '22 19:10

magnus