Files
mtusi2026lab7/internal/pkg/password/password.go
T
2026-11-29 21:59:16 +03:00

95 lines
3.0 KiB
Go

package password
import (
"context"
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"strings"
"golang.org/x/crypto/argon2"
"golang.org/x/crypto/bcrypt"
)
// Bound simultaneous KDF work to 4 * 32 MiB worst case, 4 * 19 MiB for current hashes, including concurrent registrations.
var slots = make(chan struct{}, 4)
const prefix = "$argon2id$v=19$m=19456,t=2,p=1$"
func bounded(ctx context.Context, fn func() ([]byte, error)) ([]byte, error) {
select {
case slots <- struct{}{}:
case <-ctx.Done():
return nil, ctx.Err()
}
defer func() { <-slots }()
if err := ctx.Err(); err != nil {
return nil, err
}
return fn()
}
func Hash(ctx context.Context, password string) (string, error) {
salt := make([]byte, 16)
if _, err := rand.Read(salt); err != nil {
return "", err
}
key, err := derive(ctx, password, salt, 19456, 2, 1)
if err != nil {
return "", err
}
return prefix + base64.RawStdEncoding.EncodeToString(salt) + "$" + base64.RawStdEncoding.EncodeToString(key), nil
}
func derive(ctx context.Context, password string, salt []byte, memory, rounds uint32, threads uint8) ([]byte, error) {
return bounded(ctx, func() ([]byte, error) {
return argon2.IDKey([]byte(password), salt, rounds, memory, threads, 32), nil
})
}
func Verify(ctx context.Context, password, encoded string) (bool, error) {
if strings.HasPrefix(encoded, "$2") {
cost, err := bcrypt.Cost([]byte(encoded))
if err != nil || cost > 12 {
return false, errors.New("invalid legacy password hash")
}
_, err = bounded(ctx, func() ([]byte, error) {
return nil, bcrypt.CompareHashAndPassword([]byte(encoded), []byte(password))
})
if errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) {
return false, nil
}
return err == nil, err
}
parts := strings.Split(encoded, "$")
if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" || parts[2] != "v=19" {
return false, errors.New("unsupported password hash")
}
var memory, rounds uint32
var threads uint8
count, _ := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &rounds, &threads)
if count != 3 || parts[3] != fmt.Sprintf("m=%d,t=%d,p=%d", memory, rounds, threads) ||
threads < 1 || threads > 4 || memory < 8*uint32(threads) || memory > 32768 || rounds < 1 || rounds > 4 {
return false, errors.New("invalid password parameters")
}
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
if err != nil || len(salt) < 8 || len(salt) > 32 {
return false, errors.New("invalid salt")
}
expected, err := base64.RawStdEncoding.DecodeString(parts[5])
if err != nil || len(expected) != 32 {
return false, errors.New("invalid hash")
}
actual, err := derive(ctx, password, salt, memory, rounds, threads)
return subtle.ConstantTimeCompare(actual, expected) == 1, err
}
func NeedsRehash(encoded string) bool {
return !strings.HasPrefix(encoded, prefix) || strings.LastIndexByte(encoded, '$') != len(prefix)+22
}
// A valid fixed encoding for equal-cost verification when username does not exist.
const DummyHash = prefix + "AAAAAAAAAAAAAAAAAAAAAA$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"