Tools - Password Utility Class
cPassword - Password Hash Tool
Overview
Provides password hash generation and verification functionality, supporting MD5, SHA1, SHA256 algorithms, and custom salt values.
Dependencies
cCryptoHash(src/Crypt/Hash)
Properties
| Property | Type | Description |
|---|---|---|
Algorithm | CryptoHashAlgorithm | Hash algorithm (default MD5) |
Salt | String | Salt value (default empty) |
Encoding | CryptoStringEncoding | String encoding (default UTF8) |
LastError | String | Last error message (read-only) |
Enumeration Values
CryptoHashAlgorithm
vb
HASH_ALG_MD5 = 0
HASH_ALG_SHA1 = 1
HASH_ALG_SHA256 = 2Methods
Create
Creates password hash.
vb
Public Function Create( _
ByVal Password As String, _
Optional ByRef Salt As Variant _
) As StringParameters:
| Parameter | Type | Description |
|---|---|---|
Password | String | Plain text password |
Salt | Variant | Optional, salt value (if not passed, uses property Salt) |
Returns:
Returns hash string in hexadecimal format.
Example:
vb
Dim Pwd As New cPassword
' Using default MD5
Dim Hash1 As String
Hash1 = Pwd.Create("myPassword")
Debug.Print Hash1 ' Output: 34819d7beeabb9260a5c854bc85b3e44
' Using SHA256
Pwd.Algorithm = HASH_ALG_SHA256
Dim Hash2 As String
Hash2 = Pwd.Create("myPassword")
Debug.Print Hash2
' Using random salt
Dim Salt As String
Salt = VBMAN.CryptoRandom.GetString(16) ' Generate 16-char random salt
Pwd.Salt = Salt
Dim Hash3 As String
Hash3 = Pwd.Create("myPassword")Verify
Verifies if password matches.
vb
Public Function Verify( _
ByVal Password As String, _
ByVal Hash As String, _
Optional ByRef Salt As Variant _
) As BooleanParameters:
| Parameter | Type | Description |
|---|---|---|
Password | String | Plain text password |
Hash | String | Stored hash value |
Salt | Variant | Optional, salt value |
Returns:
True- Password matchesFalse- Password does not match
Example:
vb
Dim Pwd As New cPassword
Pwd.Salt = "mysalt"
' Create hash
Dim StoredHash As String
StoredHash = Pwd.Create("myPassword")
' Verify password
If Pwd.Verify("myPassword", StoredHash) Then
Debug.Print "Password correct"
Else
Debug.Print "Password incorrect"
End IfComplete Example
vb
Private Sub TestPassword()
Dim Pwd As New cPassword
' Configuration
Pwd.Algorithm = HASH_ALG_SHA256
Pwd.Salt = "AppSpecificSalt"
Pwd.Encoding = ENCODING_UTF8
' Store hash when user registers
Dim UserHash As String
UserHash = Pwd.Create(txtPassword.Text)
SaveToDatabase txtUserName.Text, UserHash
' Verify when user logs in
Dim StoredHash As String
StoredHash = GetHashFromDatabase(txtUserName.Text)
If Pwd.Verify(txtPassword.Text, StoredHash) Then
MsgBox "Login successful"
Else
MsgBox "Password incorrect"
End If
End SubSecurity Recommendations
- Use strong hash algorithm - Prefer SHA256
- Add random salt - Prevents rainbow table attacks
- Salt uniqueness - Each user should use a different salt
- Salt storage - Salt should be stored together with the hash