MYSQL5 Hash

Description: This shared function hashes a string and returns the MYSQL5 hash for the given text. If text is null, empty or cannot encode the string, returns an empty string. Note: Since MYSQL5 uses a double SHA-1 hash function, it is not 100% secure. Take appropriate precautions to ensure passwords are fully secure before using in production code.
Tested Platform: .NET 4.0, Visual Studio 2010, Windows 7
Language: VB.NET
Public Shared Function MYSQL5(ByVal Text As String) As String
        If Not String.IsNullOrEmpty(Text) Then
            ' Setup a SHA1 Crypto Provider
            Dim sha1crypto As New System.Security.Cryptography.SHA1CryptoServiceProvider
            Dim encoding As New System.Text.UTF8Encoding()

            Try
                ' Get the bytes of our string and comput the hash, twice!
                Dim byteHash() As Byte = sha1crypto.ComputeHash(encoding.GetBytes(Text))
                byteHash = sha1crypto.ComputeHash(byteHash)

                ' Spit out the hash appended with the asterisk
                Return "*" & BitConverter.ToString(byteHash).Replace("-", "")
            Catch e As System.Text.EncoderFallbackException
                Return ""
            End Try
        End If

        Return ""
End Function

Submitted: October 28, 2012

Return to the snippets listing