66 lines
1.8 KiB
Go
66 lines
1.8 KiB
Go
package password
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"crypto/subtle"
|
|
"encoding/base64"
|
|
"errors"
|
|
"strings"
|
|
|
|
"golang.org/x/crypto/argon2"
|
|
)
|
|
|
|
// Bound simultaneous KDF work to 4 * 19 MiB, including concurrent registrations.
|
|
var slots = make(chan struct{}, 4)
|
|
|
|
const prefix = "$argon2id$v=19$m=19456,t=2,p=1$"
|
|
|
|
func derive(ctx context.Context, password string, salt []byte) ([]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 argon2.IDKey([]byte(password), salt, 2, 19456, 1, 32), nil
|
|
}
|
|
|
|
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)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return prefix + base64.RawStdEncoding.EncodeToString(salt) + "$" + base64.RawStdEncoding.EncodeToString(key), nil
|
|
}
|
|
|
|
func Verify(ctx context.Context, password, encoded string) (bool, error) {
|
|
if !strings.HasPrefix(encoded, prefix) {
|
|
return false, errors.New("unsupported password hash")
|
|
}
|
|
parts := strings.Split(strings.TrimPrefix(encoded, prefix), "$")
|
|
if len(parts) != 2 {
|
|
return false, errors.New("invalid password hash")
|
|
}
|
|
salt, err := base64.RawStdEncoding.DecodeString(parts[0])
|
|
if err != nil || len(salt) != 16 {
|
|
return false, errors.New("invalid salt")
|
|
}
|
|
expected, err := base64.RawStdEncoding.DecodeString(parts[1])
|
|
if err != nil || len(expected) != 32 {
|
|
return false, errors.New("invalid hash")
|
|
}
|
|
actual, err := derive(ctx, password, salt)
|
|
return subtle.ConstantTimeCompare(actual, expected) == 1, err
|
|
}
|
|
|
|
// A valid fixed encoding for equal-cost verification when username does not exist.
|
|
const DummyHash = prefix + "AAAAAAAAAAAAAAAAAAAAAA$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
|