87 lines
1.9 KiB
Go
87 lines
1.9 KiB
Go
package crypto
|
|
|
|
import (
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
func testKey(t *testing.T) []byte {
|
|
t.Helper()
|
|
k, err := DeriveKey([]byte("0123456789abcdef0123456789abcdef-aaa"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return k
|
|
}
|
|
|
|
func TestRoundTrip(t *testing.T) {
|
|
k := testKey(t)
|
|
cases := []string{
|
|
"hello",
|
|
"",
|
|
"ツインビー グラディウス パロディウス",
|
|
strings.Repeat("a", 4096),
|
|
"line1\nline2\ttab",
|
|
}
|
|
for _, pt := range cases {
|
|
ct, err := Encrypt(k, pt)
|
|
if err != nil {
|
|
t.Fatalf("encrypt %q: %v", pt, err)
|
|
}
|
|
if pt != "" && !IsEncrypted(ct) {
|
|
t.Errorf("expected enc: prefix on %q", ct)
|
|
}
|
|
got, err := Decrypt(k, ct)
|
|
if err != nil {
|
|
t.Fatalf("decrypt: %v", err)
|
|
}
|
|
if got != pt {
|
|
t.Errorf("round-trip mismatch: got %q want %q", got, pt)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestNonceUnique(t *testing.T) {
|
|
k := testKey(t)
|
|
a, _ := Encrypt(k, "same plaintext")
|
|
b, _ := Encrypt(k, "same plaintext")
|
|
if a == b {
|
|
t.Error("two encryptions of the same plaintext produced identical ciphertext (nonce not random)")
|
|
}
|
|
}
|
|
|
|
func TestTamperRejected(t *testing.T) {
|
|
k := testKey(t)
|
|
ct, _ := Encrypt(k, "secret")
|
|
tampered := ct[:len(ct)-2] + "AA"
|
|
if _, err := Decrypt(k, tampered); err == nil {
|
|
t.Error("expected tampered ciphertext to fail decryption")
|
|
}
|
|
}
|
|
|
|
func TestWrongKeyRejected(t *testing.T) {
|
|
k1 := testKey(t)
|
|
k2, _ := DeriveKey([]byte("a-different-32-byte-key-aaaaaaaaaaaa"))
|
|
ct, _ := Encrypt(k1, "secret")
|
|
if _, err := Decrypt(k2, ct); err == nil {
|
|
t.Error("expected decryption with wrong key to fail")
|
|
}
|
|
}
|
|
|
|
func TestPlaintextPassthrough(t *testing.T) {
|
|
k := testKey(t)
|
|
got, err := Decrypt(k, "not-encrypted")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got != "not-encrypted" {
|
|
t.Errorf("plaintext passthrough failed: %q", got)
|
|
}
|
|
}
|
|
|
|
func TestDeriveKeyRequiresMinLength(t *testing.T) {
|
|
if _, err := DeriveKey([]byte("too short")); err == nil {
|
|
t.Error("expected error on short key material")
|
|
}
|
|
}
|