forked from mtusi2026/mtusi2026lab6
ЛР 6 — БПИ2302 — Нурлыгаянова — на 3
This commit is contained in:
@@ -0,0 +1,112 @@
|
||||
package password
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
type Params struct {
|
||||
MemoryKiB uint32
|
||||
Iterations uint32
|
||||
Parallelism uint8
|
||||
SaltLen uint32
|
||||
KeyLen uint32
|
||||
}
|
||||
|
||||
var Default = Params{
|
||||
MemoryKiB: 19 * 1024,
|
||||
Iterations: 2,
|
||||
Parallelism: 1,
|
||||
SaltLen: 16,
|
||||
KeyLen: 32,
|
||||
}
|
||||
|
||||
var ErrMalformedHash = errors.New("password: malformed hash")
|
||||
|
||||
var b64 = base64.RawStdEncoding
|
||||
|
||||
type Hasher struct {
|
||||
params Params
|
||||
slots chan struct{}
|
||||
}
|
||||
|
||||
func NewHasher(p Params, maxConcurrent int) *Hasher {
|
||||
if maxConcurrent <= 0 {
|
||||
maxConcurrent = 1
|
||||
}
|
||||
return &Hasher{params: p, slots: make(chan struct{}, maxConcurrent)}
|
||||
}
|
||||
|
||||
func (h *Hasher) acquire(ctx context.Context) error {
|
||||
select {
|
||||
case h.slots <- struct{}{}:
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hasher) release() { <-h.slots }
|
||||
|
||||
// Hash возвращает PHC-строку Argon2id со случайной солью.
|
||||
func (h *Hasher) Hash(ctx context.Context, plain string) (string, error) {
|
||||
salt := make([]byte, h.params.SaltLen)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", fmt.Errorf("password: rand: %w", err)
|
||||
}
|
||||
if err := h.acquire(ctx); err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer h.release()
|
||||
|
||||
p := h.params
|
||||
key := argon2.IDKey([]byte(plain), salt, p.Iterations, p.MemoryKiB, p.Parallelism, p.KeyLen)
|
||||
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version, p.MemoryKiB, p.Iterations, p.Parallelism,
|
||||
b64.EncodeToString(salt), b64.EncodeToString(key)), nil
|
||||
}
|
||||
|
||||
func (h *Hasher) Verify(ctx context.Context, plain, encoded string) (bool, error) {
|
||||
p, salt, want, err := decode(encoded)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if err := h.acquire(ctx); err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer h.release()
|
||||
|
||||
got := argon2.IDKey([]byte(plain), salt, p.Iterations, p.MemoryKiB, p.Parallelism, uint32(len(want)))
|
||||
return subtle.ConstantTimeCompare(got, want) == 1, nil
|
||||
}
|
||||
|
||||
func decode(encoded string) (Params, []byte, []byte, error) {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" {
|
||||
return Params{}, nil, nil, ErrMalformedHash
|
||||
}
|
||||
var version int
|
||||
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil || version != argon2.Version {
|
||||
return Params{}, nil, nil, ErrMalformedHash
|
||||
}
|
||||
var p Params
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &p.MemoryKiB, &p.Iterations, &p.Parallelism); err != nil {
|
||||
return Params{}, nil, nil, ErrMalformedHash
|
||||
}
|
||||
salt, err := b64.DecodeString(parts[4])
|
||||
if err != nil || len(salt) == 0 {
|
||||
return Params{}, nil, nil, ErrMalformedHash
|
||||
}
|
||||
key, err := b64.DecodeString(parts[5])
|
||||
if err != nil || len(key) == 0 {
|
||||
return Params{}, nil, nil, ErrMalformedHash
|
||||
}
|
||||
return p, salt, key, nil
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package password
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var testParams = Params{MemoryKiB: 64, Iterations: 1, Parallelism: 1, SaltLen: 16, KeyLen: 32}
|
||||
|
||||
func TestHashVerify(t *testing.T) {
|
||||
h := NewHasher(testParams, 2)
|
||||
ctx := context.Background()
|
||||
|
||||
pw := "пароль:с-двоеточием-и-юникодом"
|
||||
encoded, err := h.Hash(ctx, pw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.HasPrefix(encoded, "$argon2id$v=19$m=64,t=1,p=1$") {
|
||||
t.Errorf("unexpected format %q", encoded)
|
||||
}
|
||||
if strings.Contains(encoded, pw) {
|
||||
t.Error("hash contains plaintext")
|
||||
}
|
||||
|
||||
ok, err := h.Verify(ctx, pw, encoded)
|
||||
if err != nil || !ok {
|
||||
t.Errorf("Verify(correct) = %v, %v", ok, err)
|
||||
}
|
||||
ok, err = h.Verify(ctx, pw+"x", encoded)
|
||||
if err != nil || ok {
|
||||
t.Errorf("Verify(wrong) = %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHash_RandomSalt(t *testing.T) {
|
||||
h := NewHasher(testParams, 1)
|
||||
a, _ := h.Hash(context.Background(), "same-password-123")
|
||||
b, _ := h.Hash(context.Background(), "same-password-123")
|
||||
if a == b {
|
||||
t.Error("two hashes of the same password are equal: salt is not random")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerify_UsesParamsFromHash(t *testing.T) {
|
||||
old := NewHasher(testParams, 1)
|
||||
encoded, _ := old.Hash(context.Background(), "long-enough-password")
|
||||
|
||||
stronger := testParams
|
||||
stronger.Iterations = 3
|
||||
ok, err := NewHasher(stronger, 1).Verify(context.Background(), "long-enough-password", encoded)
|
||||
if err != nil || !ok {
|
||||
t.Errorf("old hash must verify after params change: %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerify_Malformed(t *testing.T) {
|
||||
h := NewHasher(testParams, 1)
|
||||
for _, s := range []string{"", "!", "$argon2i$v=19$m=64,t=1,p=1$AAAA$AAAA", "$argon2id$v=19$m=64$AAAA$AAAA"} {
|
||||
if _, err := h.Verify(context.Background(), "x", s); !errors.Is(err, ErrMalformedHash) {
|
||||
t.Errorf("Verify(%q) err = %v, want ErrMalformedHash", s, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHash_RespectsContextWhenBusy(t *testing.T) {
|
||||
h := NewHasher(testParams, 1)
|
||||
h.slots <- struct{}{} // единственный слот занят
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if _, err := h.Hash(ctx, "long-enough-password"); !errors.Is(err, context.Canceled) {
|
||||
t.Errorf("err = %v, want context.Canceled", err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user