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...
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:
- Hash a user's password using your specified algorithm and store it in the database
- Salt this hash (optional, but preferred)
On login / user & password check:
- Look up in the database for the username
- If it exists, retrieve the hashed password
- 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);
}
Strictly speaking, you should salt the password then hash it, to avoid a dictionary attack. You can use any of the implementations of the HashAlgorithm
abstract class in the System.Cryptography
namespace to calculate the hash - current best choice would probably be one of the SHA-2 algorithms.
You store the hash not the password, and compare the hash values to authenticate the user.
Like the others have said, there are many options.
Here is some sample code (using MD5 instead of SHA) from Microsoft that might help get you get started
using System;
using System.Security.Cryptography;
using System.Text;
string sSourceData;
byte[] tmpSource;
byte[] tmpHash;
sSourceData = "MySourceData";
//Create a byte array from source data.
tmpSource = ASCIIEncoding.ASCII.GetBytes(sSourceData);
//Compute hash based on source data.
tmpHash = new MD5CryptoServiceProvider().ComputeHash(tmpSource);
For hashing you have several supported algorithms in System.Security.Cryptography, for your usecase you probably want to choose an SHA based hash or something similar.
Regarding the comparison: You don't compare the DB value and the one the user gave to you. You use the same encryption/hashing function that you used to store the password in the DB in the first place, this time with the user input. If the result is equal to the hash in the DB the password was (probably) correct.
The intention is that no one that has access to the DB can retrieve the passwords in clear text and not even your program needs to know about it (only the part that accepts the user input will have it for a short time).
Links (maybe even duplicates):
- Secure Password Hashing
- https://stackoverflow.com/questions/1841595/secure-password-hashing
System.Security.Cryptography.MD5