B4J Code Snippet Password SHA512 hash and salt


Active Member
Licensed User
'Generates a SHA512 hash of a string based on a given salt
Public Sub SHA512Hash(StringToHash As String, Salt() As Byte) As Byte()
    Dim bc As ByteConverter
    Dim md As MessageDigest
    Dim pHashedString() As Byte = md.GetMessageDigest(StringToHash.GetBytes("UTF8"), "SHA-512")
    Dim pHashAndSalt(pHashedString.Length + Salt.Length) As Byte
    bc.ArrayCopy(pHashedString , 0, pHashAndSalt, 0, pHashedString.Length)
    bc.ArrayCopy(Salt, 0, pHashAndSalt, pHashedString.Length, Salt.Length)
    Return md.GetMessageDigest(pHashAndSalt, "SHA-512")
End Sub

'Generates a random salt
Public Sub RandomSalt() As Byte()
    Dim salt(48) As Byte
    Dim sr As SecureRandom
    Return salt
End Sub

'Compares a given hash with a generated one based on the given string and salt
Public Sub SHA512VerifyHash(StringToVerify As String, Salt() As Byte, ComparableHash() As Byte) As Boolean
    Dim result As Boolean = False
    Dim hashToVerify() As Byte = SHA512Hash(StringToVerify, Salt)
    If hashToVerify.Length = ComparableHash.Length Then
        result = True
        For i = 0 To hashToVerify.Length - 1
            If hashToVerify(i) <> ComparableHash(i) Then
                result = False
            End If
    End If
    Return result
End Sub
*You need ByteConverter and Encryption library