Salted Hash
With hashing, you simply store the hash value of a user's password in the database. However, if two users have the same password, then the hash values for these two passwords would be identical. Imagine the hacker seeing that the two hash values are identical; it would not be hard for him to guess that the two passwords must be the same. For example, users often like to use their own names (or birth dates, or common words found in the dictionary) as passwords. Hence, hackers often like to use dictionary attacks to correctly guess users' passwords. To reduce the chance of dictionary attacks, you can add a "salt" to the hashing process so that no two identical passwords can generate the same hash values. For example, instead of hashing a user's password, you can hash his password together with his other information, such as email address, birth date, last name, first name, etc. The idea is to ensure that each user will have a unique password hash value. While this idea of using the user's information as a salt for the hashing process sounds good, it is quite easy for hackers to guess. A better approach would be to randomly generate a number to be used as the salt and then hash it together with the user's password.
The following subroutine,
Salted_Hashing_SHA1(), generates a random number using the
RNGCryptoServiceProvider class, which returns a list of randomly generated bytes (the salt). It then combines the salt with the original password and performs a hash on it.
Code:
Private Sub Salted_Hashing_SHA1()
'---Random Number Generator---
Dim salt(8) As Byte
Dim rng As New RNGCryptoServiceProvider
rng.GetBytes(salt)
'---ask the user to enter a password---
Console.Write("Please enter a password: ")
Dim password As String = Console.ReadLine()
'---add the salt to the password---
password &= ASCII.GetString(salt)
'---hash the password---
Dim data() As Byte = ASCII.GetBytes(password)
Dim passwordHash() As Byte
Dim sha As New SHA1CryptoServiceProvider()
passwordHash = sha.ComputeHash(data)
'---ask the user to enter the same password again---
Console.Write("Please enter password again: ")
password = Console.ReadLine()
Console.WriteLine(ASCII.GetString(salt))
'---adding the salt to the second password---
password &= ASCII.GetString(salt)
'---hash the second password and compare it with the first---
data = ASCII.GetBytes(password)
If ASCII.GetString(passwordHash) = _
ASCII.GetString(sha.ComputeHash(data)) Then
Console.WriteLine("Same password")
Else
Console.WriteLine("Incorrect password")
End If
End Sub Note that if you use salted hashing for storing passwords, the "salt" used for each password must be stored separately from the main hash database so that hackers do not have a chance to obtain it easily.