Hash with MD5 in VB.NET

51,260

Solution 1

It is important to note that MD5 is no longer considered a good way to hash data you wish to protect. See wikipedia for a discussion of the vulnerabilities.

See this answer for hashing using SHA.


For passwords, you'd save the hash of the user's PW to the DB. Because it is one-way (you cannot easily get the original value back from the hash), this prevents someone like a janitor or customer service rep from being able to see the actual passwords in the database.

Imports System.Security.Cryptography
Imports System.Text

Shared Function GetHash(theInput As String) As String

    Using hasher As MD5 = MD5.Create()    ' create hash object

        ' Convert to byte array and get hash
        Dim dbytes As Byte() = 
             hasher.ComputeHash(Encoding.UTF8.GetBytes(theInput))

        ' sb to create string from bytes
        Dim sBuilder As New StringBuilder()

        ' convert byte data to hex string
        For n As Integer = 0 To dbytes.Length - 1
            sBuilder.Append(dbytes(n).ToString("X2"))
        Next n

        Return sBuilder.ToString()
    End Using

End Function

Depending on how you want to save it, rather than a using StringBuilder to create a hex string, you can use Convert.ToBase64String():

Return Convert.ToBase64String(dbytes)
' MyWeakPassword hashed:
'     to hex: DB28F1BE20A407398171295DD0D191E2
'  to Base64: 2yjxviCkBzmBcSld0NGR4g==

Hashing should be done with salt. This is data added to the hash to make the result less predictable (there are dictionaries of the hashed results of common PW such as "password"; salt changes the outcome):

Shared Function GetHash(theInput As String, theSalt As String) As String
...
      hasher.ComputeHash(Encoding.UTF8.GetBytes(theInput & theSalt))

Salt should be created using the Cryptographic random number generator as shown in the SHA Version. Convert the salt to text (hex or Base64) then combine with the PW to get the PW hash.


To check/compare a user's entry, simply hash the input and compare it to the hash stored in the database, using the same Salt (which means the Salt needs to be saved):

 Shared Function CheckHash(hashedStr As String, newInput As String) As Boolean
    ' get the hash value of user input: 
    Dim newHash  As String = GetHash(newInput & dbSalt) 

    ' return comparison
    Return String.Compare(newHash, hashedStr, InvariantCultureIgnoreCase)
 End Function

As written, the GetHash function is intended to be used from something like a CryptoTools Class. Since it is Shared/Static the class need not be instanced:

  thisHash = CryptoTools.GetHash(strToHash) 

Note: Hashing is case sensitive, so foobar will result in a different hash than FooBar or FOOBAR. To create a case insensitive system, convert the original string (such as a password) to lowercase before you compute the MD5 hash value to be saved, and do the same for the value they later enter:

' ToLowerInvariant allows for foreign char sets
Dim str As String = PWTextBox.Text.ToLowerInvariant

If CheckHash(dbHashedValue, str) Then
    ' okie dokie
Else
    ' failed
End If

Solution 2

  1. MD5 Convertion
Dim [source] As String = password_text_box.text 
Using md5Hash As MD5 = MD5.Create()
Dim hash As String = GetMd5Hash(md5Hash, source)

2, Insert Name and hash into database

3, Validation

During login take MD5 of password again run sql query

Select name,password from table where Login ='" & username & "' and Password ='" & md5(user input pass) & "'

if dreader returns value , then valid login else invalid login

Share:
51,260
Koinzell
Author by

Koinzell

Updated on July 21, 2022

Comments

  • Koinzell
    Koinzell almost 2 years

    So, I got a bit of a problem here, I got a database, a login and a registration, all in different classes, now I need to hash the password in the database and read it out again when logging in, but I don't know how to handle this, I already searched a lot but couldn't find anything useful.

    Here is my login class

    Imports System.Data
    
    Imports System.Data.SqlClient
    
    Imports System.Data.SqlServerCe
    
    Public Class Login
    
        Inherits System.Web.UI.Page
    
    
        Private Sub LSend_Click(sender As Object, e As System.EventArgs) Handles LSend.Click
    
            If Bibliothek.EntryExists(LNAME.Text, "Username") = False Then
                LNAMELBL.Text = "Name oder Passwort Falsch."
                Exit Sub
            End If
    
            If Bibliothek.EntryExists(LPW.Text, "Passwort") = False Then
                LNAMELBL.Text = "Name oder Passwort Falsch."
                Exit Sub
            End If
            Dim UserN As String = LNAME.Text
            Session("Admin") = Bibliothek.GetValueBool(UserN, "IsAdmin")
            Session("USERNA") = Bibliothek.GetValueBool(UserN, "Username")
    
            Response.Redirect("/TSL/Home.aspx")
        End Sub
        Private Sub REG_Click(sender As Object, e As System.EventArgs) Handles REG.Click
            Response.Redirect("/TSL/Registrierung.aspx")
        End Sub
    
    End Class