'VB.NET Core 6, Hashing password in (Win form) using SHA512 - Visual Basic

I am trying to build an application where security and encryption are a high concern.

I am using Visual Studio 2022 and VB.NET 6.0 (I searched for 3 days now and couldn't find a suitable solution, all that I found is related to a different version of .NET and NOT Visual Studio 2022)

UPDATE: 16/5/2022

I updated my question to be more related to what I really need; which is hashing the password.

Thank you



Solution 1:[1]

This solution worked for me like charm:

Imports System.Security.Cryptography
Imports System.Text

Public Module hashing
    Public Function PWDhash(ByVal password As String)
        Using sha512Hash As SHA512 = SHA512.Create()
            Return GetHash(sha512Hash, password)
        End Using
    End Function

    Private Function GetHash(ByVal hashAlgorithm As HashAlgorithm, ByVal input As String) As String

        ' Convert the input string to a byte array and compute the hash.
        Dim data As Byte() = hashAlgorithm.ComputeHash(Encoding.UTF8.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.
        For i As Integer = 0 To data.Length - 1
            sBuilder.Append(data(i).ToString("x2"))
        Next
        ' Return the hexadecimal string.
        Return sBuilder.ToString()
    End Function

    ' Verify a hash against a string.
    Public Function VerifyHash(hashAlgorithm As HashAlgorithm, input As String, hash As String) As Boolean
        ' Hash the input.
        Dim hashOfInput As String = GetHash(hashAlgorithm, input)
        ' Create a StringComparer an compare the hashes.
        Dim comparer As StringComparer = StringComparer.OrdinalIgnoreCase
        Return comparer.Compare(hashOfInput, hash) = 0
    End Function
End Module

This is how to hash:

Dim HashedPWD As String = PWDhash("password here")

This is how to verify:

Dim IsPWDCorrect As Boolean = VerifyHash(sha512Hash, "password here", "password hash from DB")

I also created a function to force user to choose a complex password.

It works on VB.Net Core 6.0

The length of the hash is 128 Byte.

This is an example output:

708ed38ae70f96bc7dcb58515ab328614eaf3b41402de0c50e60ba0f56be5efc6f6daf0b226ec238c3dcaff182e466a1e12df1cadd4e62e6a8c197355b1edc4e

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1