go-crypt/crypt/hash.go
Claude 7407b89b8d
refactor(ax): AX RFC-025 compliance sweep pass 1
Remove banned imports (fmt, strings, os, errors, path/filepath) across all
production and test files, replace with core.* primitives, coreio.ReadStream,
and coreerr.E. Upgrade dappco.re/go/core v0.5.0 → v0.7.0 for core.PathBase
and core.Is. Fix isRepoScoped to exclude pr.* capabilities (enforcement is at
the forge layer, not the policy engine). Add Good/Bad/Ugly test coverage to
all packages missing the mandatory three-category naming convention.

Co-Authored-By: Virgil <virgil@lethean.io>
2026-03-31 08:48:56 +01:00

155 lines
4.8 KiB
Go

package crypt
import (
"crypto/subtle"
"encoding/base64"
core "dappco.re/go/core"
coreerr "dappco.re/go/core/log"
"golang.org/x/crypto/argon2"
"golang.org/x/crypto/bcrypt"
)
// HashPassword hashes a password using Argon2id with default parameters.
//
// hash, err := crypt.HashPassword("hunter2")
// // hash starts with "$argon2id$v=19$m=65536,t=3,p=4$..."
func HashPassword(password string) (string, error) {
salt, err := generateSalt(argon2SaltLen)
if err != nil {
return "", coreerr.E("crypt.HashPassword", "failed to generate salt", err)
}
hash := argon2.IDKey([]byte(password), salt, argon2Time, argon2Memory, argon2Parallelism, argon2KeyLen)
b64Salt := base64.RawStdEncoding.EncodeToString(salt)
b64Hash := base64.RawStdEncoding.EncodeToString(hash)
encoded := core.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
argon2.Version, argon2Memory, argon2Time, argon2Parallelism,
b64Salt, b64Hash)
return encoded, nil
}
// VerifyPassword verifies a password against an Argon2id hash string.
//
// ok, err := crypt.VerifyPassword("hunter2", storedHash)
// if !ok { return coreerr.E("auth.Login", "invalid password", nil) }
func VerifyPassword(password, hash string) (bool, error) {
parts := core.Split(hash, "$")
if len(parts) != 6 {
return false, coreerr.E("crypt.VerifyPassword", "invalid hash format", nil)
}
// Parse version field: "v=19" -> 19
var version uint32
if err := parseUint32Field(parts[2], "v=", &version); err != nil {
return false, coreerr.E("crypt.VerifyPassword", "failed to parse version", err)
}
// Parse parameter field: "m=65536,t=3,p=4"
var memory, timeParam uint32
var parallelism uint8
if err := parseArgon2Params(parts[3], &memory, &timeParam, &parallelism); err != nil {
return false, coreerr.E("crypt.VerifyPassword", "failed to parse parameters", err)
}
saltBytes, err := base64.RawStdEncoding.DecodeString(parts[4])
if err != nil {
return false, coreerr.E("crypt.VerifyPassword", "failed to decode salt", err)
}
expectedHash, err := base64.RawStdEncoding.DecodeString(parts[5])
if err != nil {
return false, coreerr.E("crypt.VerifyPassword", "failed to decode hash", err)
}
computedHash := argon2.IDKey([]byte(password), saltBytes, timeParam, memory, parallelism, uint32(len(expectedHash)))
return subtle.ConstantTimeCompare(computedHash, expectedHash) == 1, nil
}
// parseUint32Field parses a "prefix=N" string into a uint32.
// For example: parseUint32Field("v=19", "v=", &out) sets out to 19.
func parseUint32Field(s, prefix string, out *uint32) error {
value := core.TrimPrefix(s, prefix)
if value == s {
return coreerr.E("crypt.parseUint32Field", "missing prefix "+prefix, nil)
}
n, err := parseDecimalUint32(value)
if err != nil {
return err
}
*out = n
return nil
}
// parseArgon2Params parses "m=N,t=N,p=N" into memory, time, and parallelism.
//
// var m, t uint32; var p uint8
// parseArgon2Params("m=65536,t=3,p=4", &m, &t, &p)
func parseArgon2Params(s string, memory, timeParam *uint32, parallelism *uint8) error {
const op = "crypt.parseArgon2Params"
parts := core.Split(s, ",")
if len(parts) != 3 {
return coreerr.E(op, "expected 3 comma-separated fields", nil)
}
var m, t, p uint32
if err := parseUint32Field(parts[0], "m=", &m); err != nil {
return coreerr.E(op, "failed to parse memory", err)
}
if err := parseUint32Field(parts[1], "t=", &t); err != nil {
return coreerr.E(op, "failed to parse time", err)
}
if err := parseUint32Field(parts[2], "p=", &p); err != nil {
return coreerr.E(op, "failed to parse parallelism", err)
}
*memory = m
*timeParam = t
*parallelism = uint8(p)
return nil
}
// parseDecimalUint32 parses a decimal string into a uint32.
func parseDecimalUint32(s string) (uint32, error) {
if s == "" {
return 0, coreerr.E("crypt.parseDecimalUint32", "empty string", nil)
}
var result uint32
for _, ch := range s {
if ch < '0' || ch > '9' {
return 0, coreerr.E("crypt.parseDecimalUint32", "non-digit character in "+s, nil)
}
result = result*10 + uint32(ch-'0')
}
return result, nil
}
// HashBcrypt hashes a password using bcrypt with the given cost.
//
// hash, err := crypt.HashBcrypt("hunter2", bcrypt.DefaultCost)
func HashBcrypt(password string, cost int) (string, error) {
hash, err := bcrypt.GenerateFromPassword([]byte(password), cost)
if err != nil {
return "", coreerr.E("crypt.HashBcrypt", "failed to hash password", err)
}
return string(hash), nil
}
// VerifyBcrypt verifies a password against a bcrypt hash.
//
// ok, err := crypt.VerifyBcrypt("hunter2", storedHash)
func VerifyBcrypt(password, hash string) (bool, error) {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
if err == bcrypt.ErrMismatchedHashAndPassword {
return false, nil
}
if err != nil {
return false, coreerr.E("crypt.VerifyBcrypt", "failed to verify password", err)
}
return true, nil
}