B4J Question Password Hashing

Squiffy

Active Member
Licensed User
Longtime User
Are there any examples on this?
As I'm typing this, the server example comes to mind...
Is this the recommended way on how to handle username/password storage & authentication?

B4X:
Public Sub CheckCredentials(User As String, Password As String) As Boolean
    Dim sq As SQL = pool.GetConnection
    Dim rs As ResultSet = sq.ExecQuery2("SELECT hash, salt FROM b4j_users WHERE name = ? COLLATE utf8_unicode_ci", _
        Array As Object(User))
    Dim res As Boolean = False
    If rs.NextRow Then
        Dim hash() As Byte = CalcHash(Password, rs.GetBlob("salt"))
        Dim storedHash() As Byte = rs.GetBlob("hash")
        If hash.Length = storedHash.Length Then
            res = True
            For i = 0 To hash.Length - 1
                If hash(i) <> storedHash(i) Then
                    res = False
                    Exit
                End If
            Next
        End If
    End If
    rs.Close
    sq.Close
    Return res
End Sub

Public Sub AddUser(User As String, Password As String)
    Dim salt(48) As Byte
    Dim sr As SecureRandom
    sr.GetRandomBytes(salt)
    Dim hash() As Byte = CalcHash(Password, salt)
    Dim sq As SQL = pool.GetConnection
    sq.ExecNonQuery2("INSERT INTO b4j_users VALUES (?, ?, ?)", _
        Array As Object(User, hash, salt))
    sq.Close
End Sub

Public Sub CalcHash(Password As String, salt() As Byte) As Byte()
    Dim md As MessageDigest
    Dim spassword() As Byte = md.GetMessageDigest(Password.GetBytes("UTF8"), "SHA-512")
    Dim pbAndSalt(spassword.Length + salt.Length) As Byte
    Dim bc As ByteConverter
    bc.ArrayCopy(spassword, 0, pbAndSalt, 0, spassword.Length)
    bc.ArrayCopy(salt, 0, pbAndSalt, spassword.Length, salt.Length)
    Return md.GetMessageDigest(pbAndSalt, "SHA-512")
End Sub
 

mindful

Active Member
Licensed User
That is a good way .. I use it too ! But if you want to add an extra security (i am not says that this isn't enough) you can keep that salt in another database (eg. sql lite) like keyvaluestore 2 .. and encrypt it again ... this is usefull if your app is a server app and maybe an attacker gets hold of your database ...

Or you can use google firebase authentication i think it has user and pass besides oauth ...
 
Upvote 0
Top