Добавить хеширование паролей Argon2id

This commit is contained in:
2026-10-06 14:47:47 +03:00
parent a552f15aa7
commit f42bf97b3a
3 changed files with 153 additions and 1 deletions
+1 -1
View File
@@ -11,6 +11,7 @@ require (
github.com/testcontainers/testcontainers-go v0.39.0
github.com/testcontainers/testcontainers-go/modules/postgres v0.39.0
github.com/testcontainers/testcontainers-go/modules/valkey v0.39.0
golang.org/x/crypto v0.57.0
)
require (
@@ -95,7 +96,6 @@ require (
go.uber.org/multierr v1.11.0 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect
golang.org/x/arch v0.22.0 // indirect
golang.org/x/crypto v0.57.0 // indirect
golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba // indirect
golang.org/x/net v0.59.0 // indirect
golang.org/x/sync v0.23.0 // indirect
+74
View File
@@ -0,0 +1,74 @@
// Package password hashes user passwords with Argon2id.
//
// A password has little entropy, so its hash must be slow and memory-hard to
// make offline guessing expensive. Session tokens are the opposite case: they
// are random 256-bit values, and a fast digest is enough for them.
package password
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"strings"
"golang.org/x/crypto/argon2"
)
// OWASP baseline for Argon2id. The parameters are written into every hash,
// so raising them later does not invalidate stored hashes.
const (
memoryKiB = 19 * 1024
iterations = 2
threads = 1
saltLen = 16
keyLen = 32
)
var ErrMalformed = errors.New("malformed password hash")
var b64 = base64.RawStdEncoding
// Hash returns the PHC string $argon2id$v=19$m=…,t=…,p=…$<salt>$<key>.
func Hash(plain string) string {
salt := make([]byte, saltLen)
// Since Go 1.24 crypto/rand.Read never returns an error.
_, _ = rand.Read(salt)
key := argon2.IDKey([]byte(plain), salt, iterations, memoryKiB, threads, keyLen)
return fmt.Sprintf("$argon2id$v=%d$%s$%s$%s",
argon2.Version, params(memoryKiB, iterations, threads), b64.EncodeToString(salt), b64.EncodeToString(key))
}
// Verify reports whether plain matches encoded. An error means the stored
// hash itself is unreadable, not that the password is wrong.
func Verify(encoded, plain string) (bool, error) {
parts := strings.Split(encoded, "$")
if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" {
return false, ErrMalformed
}
var version int
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil || version != argon2.Version {
return false, ErrMalformed
}
var memory, time uint32
var parallelism uint8
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &time, &parallelism); err != nil ||
memory == 0 || time == 0 || parallelism == 0 || params(memory, time, parallelism) != parts[3] {
return false, ErrMalformed
}
salt, err := b64.DecodeString(parts[4])
if err != nil || len(salt) == 0 {
return false, ErrMalformed
}
key, err := b64.DecodeString(parts[5])
if err != nil || len(key) == 0 {
return false, ErrMalformed
}
got := argon2.IDKey([]byte(plain), salt, time, memory, parallelism, uint32(len(key)))
return subtle.ConstantTimeCompare(got, key) == 1, nil
}
func params(memory, time uint32, parallelism uint8) string {
return fmt.Sprintf("m=%d,t=%d,p=%d", memory, time, parallelism)
}
@@ -0,0 +1,78 @@
package password_test
import (
"crypto/rand"
"encoding/base64"
"fmt"
"strings"
"testing"
"golang.org/x/crypto/argon2"
"messenger/internal/platform/password"
)
func TestHashVerifiesOnlyTheOriginalPassword(t *testing.T) {
for _, plain := range []string{
"correct horse battery staple",
"с:двоеточием:и кириллицей",
"emoji 👋👋👋 and : colon",
} {
encoded := password.Hash(plain)
ok, err := password.Verify(encoded, plain)
if err != nil || !ok {
t.Fatalf("Verify(%q) = %v, %v; want true", plain, ok, err)
}
ok, err = password.Verify(encoded, plain+"x")
if err != nil || ok {
t.Fatalf("Verify(wrong) = %v, %v; want false", ok, err)
}
}
}
func TestHashIsSaltedPHCString(t *testing.T) {
a, b := password.Hash("same password"), password.Hash("same password")
if a == b {
t.Fatal("two hashes of one password are equal: salt is missing")
}
if !strings.HasPrefix(a, "$argon2id$v=19$m=19456,t=2,p=1$") {
t.Fatalf("unexpected encoding %q", a)
}
if strings.Contains(a, "same password") {
t.Fatal("hash contains the plaintext")
}
}
// A hash made with other parameters must still verify: parameters travel in
// the encoded string, so they can be raised without invalidating old hashes.
func TestVerifyUsesParametersFromTheEncoding(t *testing.T) {
salt := make([]byte, 16)
_, _ = rand.Read(salt)
key := argon2.IDKey([]byte("legacy password"), salt, 1, 8*1024, 2, 32)
b64 := base64.RawStdEncoding
encoded := fmt.Sprintf("$argon2id$v=19$m=8192,t=1,p=2$%s$%s", b64.EncodeToString(salt), b64.EncodeToString(key))
ok, err := password.Verify(encoded, "legacy password")
if err != nil || !ok {
t.Fatalf("Verify = %v, %v; want true", ok, err)
}
}
func TestVerifyRejectsMalformedEncoding(t *testing.T) {
valid := password.Hash("whatever password")
parts := strings.Split(valid, "$")
for name, encoded := range map[string]string{
"empty": "",
"wrong algo": strings.Replace(valid, "argon2id", "argon2i", 1),
"wrong version": strings.Replace(valid, "v=19", "v=16", 1),
"bad params": strings.Replace(valid, "m=19456,t=2,p=1", "m=x,t=2,p=1", 1),
"zero params": strings.Replace(valid, "m=19456,t=2,p=1", "m=19456,t=0,p=1", 1),
"bad salt": strings.Join([]string{"", parts[1], parts[2], parts[3], "!!!", parts[5]}, "$"),
"bad key": strings.Join([]string{"", parts[1], parts[2], parts[3], parts[4], "!!!"}, "$"),
"missing fields": strings.Join(parts[:5], "$"),
} {
if _, err := password.Verify(encoded, "whatever password"); err == nil {
t.Errorf("%s: Verify accepted %q", name, encoded)
}
}
}