Copied from internal/domain/identity, internal/domain/org, internal/domain/access, internal/infrastructure/access and internal/infrastructure/postgres.
48 lines
1.6 KiB
Go
48 lines
1.6 KiB
Go
package governance
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"crypto/subtle"
|
|
"encoding/base64"
|
|
"fmt"
|
|
"strings"
|
|
"unicode/utf8"
|
|
|
|
"golang.org/x/crypto/argon2"
|
|
)
|
|
|
|
// HashPassword uses the OWASP Argon2id minimum with a fresh salt.
|
|
func HashPassword(password string) (string, error) {
|
|
if utf8.RuneCountInString(password) < 15 || len(password) > 1024 {
|
|
return "", fmt.Errorf("%w: password must have at least 15 characters and at most 1024 bytes", ErrInvalidIdentity)
|
|
}
|
|
if strings.Contains(commonPasswords, "\n"+strings.ToLower(password)+"\n") {
|
|
return "", fmt.Errorf("%w: choose a password that is not commonly used", ErrInvalidIdentity)
|
|
}
|
|
var salt [16]byte
|
|
if _, err := rand.Read(salt[:]); err != nil {
|
|
return "", err
|
|
}
|
|
key := argon2.IDKey([]byte(password), salt[:], 2, 19*1024, 1, 32)
|
|
return "$argon2id$v=19$m=19456,t=2,p=1$" + base64.RawStdEncoding.EncodeToString(salt[:]) + "$" + base64.RawStdEncoding.EncodeToString(key), nil
|
|
}
|
|
|
|
// VerifyPassword accepts only parameters this application produces, bounding
|
|
// the work even if a stored hash is corrupted.
|
|
func VerifyPassword(password, hash string) bool {
|
|
parts := strings.Split(hash, "$")
|
|
if len(parts) != 6 || parts[1] != "argon2id" || parts[2] != "v=19" || parts[3] != "m=19456,t=2,p=1" || len(password) > 1024 {
|
|
return false
|
|
}
|
|
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
|
if err != nil || len(salt) != 16 {
|
|
return false
|
|
}
|
|
expected, err := base64.RawStdEncoding.DecodeString(parts[5])
|
|
if err != nil || len(expected) != 32 {
|
|
return false
|
|
}
|
|
key := argon2.IDKey([]byte(password), salt, 2, 19*1024, 1, 32)
|
|
return subtle.ConstantTimeCompare(key, expected) == 1
|
|
}
|