SPB Git

Repository Public

crypt_test.go 2.7 KB 101 lines go

1package backup23import (4	"bytes"5	"crypto/rand"6	"errors"7	"io"8	"testing"9)1011func roundTrip(t *testing.T, key, plain []byte) []byte {12	t.Helper()13	var enc bytes.Buffer14	w, err := NewEncrypter(&enc, key)15	if err != nil {16		t.Fatal(err)17	}18	// Write in awkward pieces to cross chunk boundaries.19	for i := 0; i < len(plain); i += 7919 {20		end := min(i+7919, len(plain))21		if _, err := w.Write(plain[i:end]); err != nil {22			t.Fatal(err)23		}24	}25	if err := w.Close(); err != nil {26		t.Fatal(err)27	}28	r, err := NewDecrypter(bytes.NewReader(enc.Bytes()), key)29	if err != nil {30		t.Fatal(err)31	}32	got, err := io.ReadAll(r)33	if err != nil {34		t.Fatalf("decrypt: %v", err)35	}36	if !bytes.Equal(got, plain) {37		t.Fatalf("round trip mismatch: %d vs %d bytes", len(got), len(plain))38	}39	return enc.Bytes()40}4142func TestEncryptDecryptSizes(t *testing.T) {43	key := make([]byte, 32)44	rand.Read(key)45	for _, n := range []int{0, 1, chunkSize - 1, chunkSize, chunkSize + 1, 3*chunkSize + 123} {46		plain := make([]byte, n)47		rand.Read(plain)48		roundTrip(t, key, plain)49	}50}5152func TestTamperTruncateWrongKey(t *testing.T) {53	key := make([]byte, 32)54	rand.Read(key)55	plain := make([]byte, 3*chunkSize+500)56	rand.Read(plain)57	enc := roundTrip(t, key, plain)58	read := func(b, k []byte) error {59		r, err := NewDecrypter(bytes.NewReader(b), k)60		if err != nil {61			return err62		}63		_, err = io.ReadAll(r)64		return err65	}66	other := make([]byte, 32)67	rand.Read(other)68	if err := read(enc, other); !errors.Is(err, ErrCorrupt) {69		t.Fatalf("wrong key: %v", err)70	}71	for _, pos := range []int{len(magic) + 1, len(enc) / 2, len(enc) - 1} {72		bad := bytes.Clone(enc)73		bad[pos] ^= 0x0174		if err := read(bad, key); err == nil {75			t.Fatalf("bit flip at %d not detected", pos)76		}77	}78	// Truncation at every structural boundary and in the middle of a chunk.79	chunk := 4 + chunkSize + 1680	head := len(magic) + 481	for _, cut := range []int{head, head + chunk, head + 2*chunk, head + chunk + 100, len(enc) - 1, len(enc) - 20} {82		if err := read(enc[:cut], key); err == nil {83			t.Fatalf("truncation at %d not detected", cut)84		}85	}86	// Dropping the final (short) chunk leaves only "more" chunks: must be reported as truncated.87	if err := read(enc[:head+3*chunk], key); !errors.Is(err, ErrTruncated) {88		t.Fatalf("missing last chunk: %v", err)89	}90	// Swapping two chunks is detected (nonce counter).91	swapped := bytes.Clone(enc)92	copy(swapped[head:head+chunk], enc[head+chunk:head+2*chunk])93	copy(swapped[head+chunk:head+2*chunk], enc[head:head+chunk])94	if err := read(swapped, key); !errors.Is(err, ErrCorrupt) {95		t.Fatalf("reordered chunks: %v", err)96	}97	if err := read([]byte("plain sql dump"), key); !errors.Is(err, ErrFormat) {98		t.Fatalf("foreign file: %v", err)99	}100}101
Files main
Menu

Theme