Files
mtusi2026lab4/internal/password/password.go
T

64 lines
2.0 KiB
Go

// Package password хеширует пароли Argon2id.
package password
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"fmt"
"strings"
"golang.org/x/crypto/argon2"
)
// Params — стоимость KDF. Значения пишутся в саму строку хеша,
// поэтому старые пароли проверяются даже после смены настроек.
type Params struct {
Time uint32
Memory uint32
Threads uint8
}
// Hash возвращает PHC-строку.
func (p Params) Hash(plain string) (string, error) {
if p.Time < 1 || p.Threads < 1 || p.Memory < 8*uint32(p.Threads) {
return "", fmt.Errorf("argon2 params are too small")
}
salt := make([]byte, 16)
if _, err := rand.Read(salt); err != nil {
return "", err
}
sum := argon2.IDKey([]byte(plain), salt, p.Time, p.Memory, p.Threads, 32)
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
argon2.Version,
p.Memory, p.Time, p.Threads,
base64.RawStdEncoding.EncodeToString(salt),
base64.RawStdEncoding.EncodeToString(sum),
), nil
}
// Verify сравнивает пароль с PHC-строкой. Параметры берутся из строки, не из текущего конфига.
func Verify(plain, encoded string) bool {
parts := strings.Split(encoded, "$")
if len(parts) != 6 || parts[1] != "argon2id" || !strings.HasPrefix(parts[2], "v=") {
return false
}
var memory, timeCost, threads int
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &timeCost, &threads); err != nil {
return false
}
if memory < 8 || timeCost < 1 || threads < 1 || threads > 255 {
return false
}
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
if err != nil || len(salt) == 0 {
return false
}
want, err := base64.RawStdEncoding.DecodeString(parts[5])
if err != nil || len(want) == 0 {
return false
}
got := argon2.IDKey([]byte(plain), salt, uint32(timeCost), uint32(memory), uint8(threads), uint32(len(want)))
return subtle.ConstantTimeCompare(got, want) == 1
}