// Package password implements a bounded Argon2id password KDF. package password import ( "crypto/rand" "crypto/subtle" "encoding/base64" "strings" "golang.org/x/crypto/argon2" ) const ( memoryKiB = 19 * 1024 iterations = 2 parallelism = 1 saltBytes = 16 hashBytes = 32 prefix = "$argon2id$v=19$m=19456,t=2,p=1$" ) // Hasher implements password hashing without transport or storage dependencies. type Hasher struct{} // Hash generates a salted Argon2id encoding using fixed resource bounds. func (Hasher) Hash(password string) (string, error) { salt := make([]byte, saltBytes) if _, err := rand.Read(salt); err != nil { return "", err } hash := argon2.IDKey([]byte(password), salt, iterations, memoryKiB, parallelism, hashBytes) return prefix + base64.RawStdEncoding.EncodeToString(salt) + "$" + base64.RawStdEncoding.EncodeToString(hash), nil } // Verify accepts only this application's bounded KDF encoding and compares in constant time. func (Hasher) Verify(encoded, password string) bool { if !strings.HasPrefix(encoded, prefix) { return false } parts := strings.Split(strings.TrimPrefix(encoded, prefix), "$") if len(parts) != 2 { return false } salt, err := base64.RawStdEncoding.DecodeString(parts[0]) if err != nil || len(salt) != saltBytes { return false } expected, err := base64.RawStdEncoding.DecodeString(parts[1]) if err != nil || len(expected) != hashBytes { return false } actual := argon2.IDKey([]byte(password), salt, iterations, memoryKiB, parallelism, hashBytes) return subtle.ConstantTimeCompare(actual, expected) == 1 }