Use the golang.org/x/crypto/argon2 package to hash passwords by calling argon2.Key with your password, a random salt, and specific parameters like memory cost, iterations, and parallelism. Store the resulting hash alongside the salt in your database, then verify future logins by regenerating the hash with the stored salt and comparing it to the stored value using subtle.ConstantTimeCompare.
import (
"crypto/rand"
"encoding/hex"
"golang.org/x/crypto/argon2"
"golang.org/x/crypto/subtle"
)
func HashPassword(password []byte) (string, error) {
salt := make([]byte, 16)
if _, err := rand.Read(salt); err != nil {
return "", err
}
hash := argon2.Key(password, salt, 1, 64*1024, 4, 32)
return hex.EncodeToString(append(salt, hash...)), nil
}
func VerifyPassword(password []byte, storedHash string) bool {
parsed, err := hex.DecodeString(storedHash)
if err != nil || len(parsed) < 16 {
return false
}
salt, hash := parsed[:16], parsed[16:]
newHash := argon2.Key(password, salt, 1, 64*1024, 4, 32)
return subtle.ConstantTimeCompare(newHash, hash) == 1
}