75 lines
2.3 KiB
Go
75 lines
2.3 KiB
Go
// Package password hashes user passwords with Argon2id.
|
|
//
|
|
// A password has little entropy, so its hash must be slow and memory-hard to
|
|
// make offline guessing expensive. Session tokens are the opposite case: they
|
|
// are random 256-bit values, and a fast digest is enough for them.
|
|
package password
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"crypto/subtle"
|
|
"encoding/base64"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
|
|
"golang.org/x/crypto/argon2"
|
|
)
|
|
|
|
// OWASP baseline for Argon2id. The parameters are written into every hash,
|
|
// so raising them later does not invalidate stored hashes.
|
|
const (
|
|
memoryKiB = 19 * 1024
|
|
iterations = 2
|
|
threads = 1
|
|
saltLen = 16
|
|
keyLen = 32
|
|
)
|
|
|
|
var ErrMalformed = errors.New("malformed password hash")
|
|
|
|
var b64 = base64.RawStdEncoding
|
|
|
|
// Hash returns the PHC string $argon2id$v=19$m=…,t=…,p=…$<salt>$<key>.
|
|
func Hash(plain string) string {
|
|
salt := make([]byte, saltLen)
|
|
// Since Go 1.24 crypto/rand.Read never returns an error.
|
|
_, _ = rand.Read(salt)
|
|
key := argon2.IDKey([]byte(plain), salt, iterations, memoryKiB, threads, keyLen)
|
|
return fmt.Sprintf("$argon2id$v=%d$%s$%s$%s",
|
|
argon2.Version, params(memoryKiB, iterations, threads), b64.EncodeToString(salt), b64.EncodeToString(key))
|
|
}
|
|
|
|
// Verify reports whether plain matches encoded. An error means the stored
|
|
// hash itself is unreadable, not that the password is wrong.
|
|
func Verify(encoded, plain string) (bool, error) {
|
|
parts := strings.Split(encoded, "$")
|
|
if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" {
|
|
return false, ErrMalformed
|
|
}
|
|
var version int
|
|
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil || version != argon2.Version {
|
|
return false, ErrMalformed
|
|
}
|
|
var memory, time uint32
|
|
var parallelism uint8
|
|
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &time, ¶llelism); err != nil ||
|
|
memory == 0 || time == 0 || parallelism == 0 {
|
|
return false, ErrMalformed
|
|
}
|
|
salt, err := b64.DecodeString(parts[4])
|
|
if err != nil || len(salt) == 0 {
|
|
return false, ErrMalformed
|
|
}
|
|
key, err := b64.DecodeString(parts[5])
|
|
if err != nil || len(key) == 0 {
|
|
return false, ErrMalformed
|
|
}
|
|
got := argon2.IDKey([]byte(plain), salt, time, memory, parallelism, uint32(len(key)))
|
|
return subtle.ConstantTimeCompare(got, key) == 1, nil
|
|
}
|
|
|
|
func params(memory, time uint32, parallelism uint8) string {
|
|
return fmt.Sprintf("m=%d,t=%d,p=%d", memory, time, parallelism)
|
|
}
|