DEV Community

vblover programmer
vblover programmer

Posted on

VB .Net: Secure Password

SecurePassword Class:

Imports System.Text
Imports System.Security.Cryptography
Public Class SecurePassword
    Protected Friend Shared Function GetMd5Hash(ByVal input As String) As String
        ' Create a new instance of the MD5 object.
        Dim md5Hasher As MD5 = MD5.Create()
        ' Convert the input string to a byte array and compute the hash.
        Dim data As Byte() = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input))
        ' Create a new Stringbuilder to collect the bytes
        ' and create a string.
        Dim sBuilder As New StringBuilder()
        ' Loop through each byte of the hashed data 
        ' and format each one as a hexadecimal string.
        Dim i As Integer
        For i = 0 To data.Length - 1
            sBuilder.Append(data(i).ToString("x2"))
        Next i
        ' Return the hexadecimal string.
        Return sBuilder.ToString()
    End Function
    ' Verify a hash against a string.
    Protected Friend Shared Function verifyMd5Hash(ByVal input As String, ByVal hash As String) As Boolean
        ' Hash the input.
        Dim hashOfInput As String = getMd5Hash(input)
        ' Create a StringComparer an compare the hashes.
        Dim comparer As StringComparer = StringComparer.OrdinalIgnoreCase
        If comparer.Compare(hashOfInput, hash) = 0 Then Return True
            Return False
     End Function
End Class

Enter fullscreen mode Exit fullscreen mode

Using for password property to save:

   Public ReadOnly Property Password() As String
        Get
            Return SecurePassword.GetMd5Hash(ConfirmPasswordBox.Text)
        End Get
    End Property

Enter fullscreen mode Exit fullscreen mode

Check for password correction:

If SecurePassword.verifyMd5Hash(Me.PasswordBox.Text,
UserAccount(Me.ID).Password) = False Then
                        Me.PasswordBox.Text = ""
                        .SetError(Me.PasswordBox, "Wrong Password!")
                        Me.PasswordBox.Focus()
                        Me.PasswordBox.Select()
                        Exit Sub
                    End If

Enter fullscreen mode Exit fullscreen mode

Top comments (0)