Documentation
¶
Overview ¶
Package hash provides password hashing and verification using industry-standard algorithms: Argon2id, bcrypt, and SHA-256 (with optional HMAC key).
For password storage, prefer Argon2id (NewArgon2/CompareArgon2) or bcrypt (CreateBcrypt/CompareBcrypt). SHA-256 is provided for non-password hashing use cases such as data integrity checks.
All hashing functions use crypto/rand for salt generation and constant-time comparison to prevent timing attacks.
Index ¶
- func CompareArgon2(password, encodedHash string) (bool, error)
- func CompareBcrypt(hashedText string, plainText string) error
- func CreateBcrypt(plainText string, cost int) (string, error)
- func NewArgon2(password []byte) (string, error)
- func NewSHA256(text string) string
- func NewSHA256WithKey(text, key string) string
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CompareArgon2 ¶
CompareArgon2 compares a plaintext password against an argon2id encoded hash. Returns true if the password matches, false otherwise.
Example ¶
package main
import (
"fmt"
"github.com/alpardfm/go-toolkit/hash"
)
func main() {
// First, hash a password
password := "my-secret-password"
hashed, err := hash.NewArgon2([]byte(password))
if err != nil {
fmt.Println("error:", err)
return
}
// Compare with the correct password
match, err := hash.CompareArgon2(password, hashed)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println("correct password:", match)
// Compare with a wrong password
match, err = hash.CompareArgon2("wrong-password", hashed)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println("wrong password:", match)
}
Output: correct password: true wrong password: false
func CompareBcrypt ¶
CompareBcrypt compares a bcrypt hashed string with a plaintext string. Returns nil if they match, or an error if they do not.
func CreateBcrypt ¶
CreateBcrypt hashes a plaintext string using bcrypt with the specified cost factor.
func NewArgon2 ¶
NewArgon2 hashes a password using the Argon2id algorithm and returns the hash in the standard argon2id encoded format: $argon2id$v=<version>$m=<memory>,t=<iterations>,p=<parallelism>$<salt>$<hash>.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/alpardfm/go-toolkit/hash"
)
func main() {
// Hash a password using Argon2id
hashed, err := hash.NewArgon2([]byte("my-secret-password"))
if err != nil {
fmt.Println("error:", err)
return
}
// The hash follows the standard argon2id format
fmt.Println(strings.HasPrefix(hashed, "$argon2id$"))
}
Output: true
func NewSHA256WithKey ¶
NewSHA256WithKey generates a HMAC SHA256 hash with a given key.
Types ¶
This section is empty.