forked from mtusi2026/mtusi2026lab7
60 lines
2.1 KiB
Go
60 lines
2.1 KiB
Go
package services
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"crypto/subtle"
|
|
"encoding/base64"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
|
|
"golang.org/x/crypto/argon2"
|
|
)
|
|
|
|
const (
|
|
argonMemory uint32 = 64 * 1024
|
|
argonIterations uint32 = 3
|
|
argonParallelism uint8 = 2
|
|
passwordSaltSize = 16
|
|
passwordHashSize = 32
|
|
)
|
|
|
|
// HashPassword stores the salt and Argon2id parameters in one PHC-encoded value.
|
|
func HashPassword(password string) ([]byte, error) {
|
|
salt := make([]byte, passwordSaltSize)
|
|
if _, err := rand.Read(salt); err != nil {
|
|
return nil, err
|
|
}
|
|
hash := argon2.IDKey([]byte(password), salt, argonIterations, argonMemory, argonParallelism, passwordHashSize)
|
|
encoded := fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
|
argon2.Version, argonMemory, argonIterations, argonParallelism,
|
|
base64.RawStdEncoding.EncodeToString(salt),
|
|
base64.RawStdEncoding.EncodeToString(hash),
|
|
)
|
|
return []byte(encoded), nil
|
|
}
|
|
|
|
func VerifyPassword(password string, encoded []byte) (bool, error) {
|
|
parts := strings.Split(string(encoded), "$")
|
|
if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" || parts[2] != fmt.Sprintf("v=%d", argon2.Version) {
|
|
return false, errors.New("invalid password hash format")
|
|
}
|
|
var memory, iterations uint32
|
|
var parallelism uint8
|
|
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &iterations, ¶llelism); err != nil ||
|
|
fmt.Sprintf("m=%d,t=%d,p=%d", memory, iterations, parallelism) != parts[3] ||
|
|
memory < 8*1024 || memory > 128*1024 || iterations < 1 || iterations > 10 || parallelism < 1 || parallelism > 8 {
|
|
return false, errors.New("invalid password hash parameters")
|
|
}
|
|
salt, err := base64.RawStdEncoding.Strict().DecodeString(parts[4])
|
|
if err != nil || len(salt) != passwordSaltSize {
|
|
return false, errors.New("invalid password salt")
|
|
}
|
|
expected, err := base64.RawStdEncoding.Strict().DecodeString(parts[5])
|
|
if err != nil || len(expected) != passwordHashSize {
|
|
return false, errors.New("invalid password hash")
|
|
}
|
|
actual := argon2.IDKey([]byte(password), salt, iterations, memory, parallelism, passwordHashSize)
|
|
return subtle.ConstantTimeCompare(expected, actual) == 1, nil
|
|
}
|