How to hash a string in VB.NET

1 Answer

0 votes
Imports System

Module Program

    '''
    ''' Computes a hash value for a string.
    '''
    ''' <param name="text">
    ''' The input string to hash.
    ''' </param>
    ''' <returns>
    ''' A 32-bit integer hash value.
    ''' </returns>
    '''
    ''' Notes:
    ''' - String.GetHashCode() is the built-in hashing mechanism
    '''   provided by .NET.
    ''' - It is commonly used by collections such as Dictionary(Of TKey, TValue)
    '''   and HashSet(Of T).
    ''' - Different strings can produce the same hash value
    '''   (known as a collision).
    ''' - Hashes are intended for fast lookups, not security.
    '''
    Private Function HashString(text As String) As Integer
        Return text.GetHashCode()
    End Function

    Sub Main()

        ' Example input string.
        Dim text As String = "Hello, World!"

        ' Compute the hash value.
        Dim hashValue As Integer = HashString(text)

        Console.WriteLine($"Original string: {text}")
        Console.WriteLine($"Hash value     : {hashValue}")

        Console.WriteLine()

        ' Demonstrate hash comparison.
        Dim anotherText As String = "Hello, World!"

        If HashString(text) = HashString(anotherText) Then

            Console.WriteLine("Hashes match.")

            '
            ' IMPORTANT:
            '
            ' Matching hashes do not guarantee that two strings
            ' are identical because collisions are possible.
            '
            ' Therefore, compare the original strings when
            ' an exact match is required.
            '
            If text.Equals(anotherText, StringComparison.Ordinal) Then
                Console.WriteLine("Strings are identical.")
            End If
        End If

        '
        ' Professional Guidance
        '
        ' Use string hashes for:
        '   - Dictionary lookups
        '   - HashSet collections
        '   - Caching
        '   - Fast comparisons
        '
        ' Do NOT use String.GetHashCode() for:
        '   - Password storage
        '   - Encryption
        '   - Digital signatures
        '   - Security-sensitive verification
        '
		' Hashes are not encryption and cannot be reversed to recover the original string.
		'
        ' For security-related hashing, use cryptographic
        ' algorithms such as SHA-256 from System.Security.Cryptography.
        '

    End Sub

End Module



' run:
' 
' Original string: Hello, World!
' Hash value     : 1184037675
'
' Hashes match.
' Strings are identical.
'
'

 



answered Oct 4 by avibootz
...