54 lines
1.6 KiB
Go
54 lines
1.6 KiB
Go
package protocol
|
|||
|
|
|
||
|
|
import (
|
||
|
|
"crypto/rand"
|
||
|
|
"crypto/subtle"
|
||
|
|
"encoding/base64"
|
||
|
|
"fmt"
|
||
|
|
"strings"
|
||
|
|
|
||
|
|
"golang.org/x/crypto/argon2"
|
||
|
|
)
|
||
|
|
|
||
|
|
// Argon2id parameters. These are deliberately generous since password
|
||
|
|
// verification happens rarely (once per connection attempt), not in a hot
|
||
|
|
// path, so we can afford to make offline brute-forcing of a stolen hash slow.
|
||
|
|
const (
|
||
|
|
argonTime = 3
|
||
|
|
argonMemory = 64 * 1024 // 64 MiB
|
||
|
|
argonThreads = 2
|
||
|
|
argonKeyLen = 32
|
||
|
|
saltLen = 16
|
||
|
|
)
|
||
|
|
|
||
|
|
// HashPassword derives an encoded Argon2id hash string suitable for storing
|
||
|
|
// in the host's config file. Format: argon2id$<b64 salt>$<b64 hash>
|
||
|
|
func HashPassword(password string) (string, error) {
|
||
|
|
salt := make([]byte, saltLen)
|
||
|
|
if _, err := rand.Read(salt); err != nil {
|
||
|
|
return "", err
|
||
|
|
}
|
||
|
|
hash := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
|
||
|
|
return fmt.Sprintf("argon2id$%s$%s",
|
||
|
|
base64.RawStdEncoding.EncodeToString(salt),
|
||
|
|
base64.RawStdEncoding.EncodeToString(hash)), nil
|
||
|
|
}
|
||
|
|
|
||
|
|
// VerifyPassword checks password against an encoded hash produced by
|
||
|
|
// HashPassword, using a constant-time comparison of the derived key.
|
||
|
|
func VerifyPassword(password, encoded string) bool {
|
||
|
|
parts := strings.Split(encoded, "$")
|
||
|
|
if len(parts) != 3 || parts[0] != "argon2id" {
|
||
|
|
return false
|
||
|
|
}
|
||
|
|
salt, err := base64.RawStdEncoding.DecodeString(parts[1])
|
||
|
|
if err != nil {
|
||
|
|
return false
|
||
|
|
}
|
||
|
|
want, err := base64.RawStdEncoding.DecodeString(parts[2])
|
||
|
|
if err != nil {
|
||
|
|
return false
|
||
|
|
}
|
||
|
|
got := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, uint32(len(want)))
|
||
|
|
return subtle.ConstantTimeCompare(got, want) == 1
|
||
|
|
}
|