forked from mtusi2026/mtusi2026lab3
work 3
This commit is contained in:
@@ -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