Comparing Password SHA1 Hash

J.C. SolvoTerra 0 Tallied Votes 867 Views Share

Using .Net's SHA1 Crypto Service to compare hashes between a user's password and their stored hashed password.

Simplez =0)

Imports System.Security.Cryptography

Public Class Form1

	'Holds Hash Bytes Returned From Database
    Dim StoredHash As Byte() = Nothing
	
	'Holds Hash Bytes From Current User Password Attempt
    Dim UserHash As Byte() = Nothing

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load

        'Mimic Returned Hash From Users Database
        StoredHash = GetSHA1PasswordHash("ThisIsMyPassword")

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        'Convert Current Users Password To Hash
        UserHash = GetSHA1PasswordHash(TextBox1.Text)

        'Compare The User Hash With The Stored Hash
        Select Case UserHash.SequenceEqual(StoredHash)
            Case False
                MsgBox("Incorrect Password")
            Case True
                MsgBox("Access Granted")
        End Select

    End Sub

    Public Function GetSHA1PasswordHash(Password As String) As Byte()

        'Self Explanitory
        Dim SHA1_CSP As New SHA1CryptoServiceProvider()
        Return SHA1_CSP.ComputeHash(System.Text.Encoding.UTF8.GetBytes(Password))

    End Function

End Class