102 lines
2.4 KiB
Go
102 lines
2.4 KiB
Go
package db
|
|
|
|
import (
|
|
"testing"
|
|
)
|
|
|
|
func TestHashSHA256(t *testing.T) {
|
|
h1 := HashSHA256("hello")
|
|
h2 := HashSHA256("hello")
|
|
if h1 != h2 {
|
|
t.Fatal("same input should produce same hash")
|
|
}
|
|
if h1 == HashSHA256("world") {
|
|
t.Fatal("different input should produce different hash")
|
|
}
|
|
if len(h1) != 64 {
|
|
t.Fatalf("SHA-256 hex should be 64 chars, got %d", len(h1))
|
|
}
|
|
}
|
|
|
|
func TestEncryptDecryptWithoutKey(t *testing.T) {
|
|
old := encryptionKey
|
|
encryptionKey = nil
|
|
defer func() { encryptionKey = old }()
|
|
|
|
enc, err := Encrypt("plain")
|
|
if err != nil {
|
|
t.Fatalf("encrypt without key: %v", err)
|
|
}
|
|
if enc != "plain" {
|
|
t.Fatal("without key, Encrypt should return plaintext")
|
|
}
|
|
dec, err := Decrypt("plain")
|
|
if err != nil {
|
|
t.Fatalf("decrypt without key: %v", err)
|
|
}
|
|
if dec != "plain" {
|
|
t.Fatal("without key, Decrypt should return input as-is")
|
|
}
|
|
}
|
|
|
|
func TestEncryptDecryptWithKey(t *testing.T) {
|
|
if err := SetEncryptionKey("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"); err != nil {
|
|
t.Fatalf("set key: %v", err)
|
|
}
|
|
defer func() { encryptionKey = nil }()
|
|
|
|
original := "4242424242424242"
|
|
enc, err := Encrypt(original)
|
|
if err != nil {
|
|
t.Fatalf("encrypt: %v", err)
|
|
}
|
|
if enc == original {
|
|
t.Fatal("encrypted text should differ from plaintext")
|
|
}
|
|
|
|
dec, err := Decrypt(enc)
|
|
if err != nil {
|
|
t.Fatalf("decrypt: %v", err)
|
|
}
|
|
if dec != original {
|
|
t.Fatalf("decrypted = %q, want %q", dec, original)
|
|
}
|
|
}
|
|
|
|
func TestEncryptNondeterministic(t *testing.T) {
|
|
if err := SetEncryptionKey("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"); err != nil {
|
|
t.Fatalf("set key: %v", err)
|
|
}
|
|
defer func() { encryptionKey = nil }()
|
|
|
|
e1, _ := Encrypt("same")
|
|
e2, _ := Encrypt("same")
|
|
if e1 == e2 {
|
|
t.Fatal("GCM encryption should produce different ciphertext each time (random nonce)")
|
|
}
|
|
}
|
|
|
|
func TestSetEncryptionKeyInvalidLength(t *testing.T) {
|
|
if err := SetEncryptionKey("abcd"); err == nil {
|
|
t.Fatal("expected error for short key")
|
|
}
|
|
}
|
|
|
|
func TestSetEncryptionKeyInvalidHex(t *testing.T) {
|
|
if err := SetEncryptionKey("zzzz"); err == nil {
|
|
t.Fatal("expected error for non-hex key")
|
|
}
|
|
}
|
|
|
|
func TestDecryptInvalidCiphertext(t *testing.T) {
|
|
if err := SetEncryptionKey("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"); err != nil {
|
|
t.Fatalf("set key: %v", err)
|
|
}
|
|
defer func() { encryptionKey = nil }()
|
|
|
|
_, err := Decrypt("00")
|
|
if err == nil {
|
|
t.Fatal("expected error for short ciphertext")
|
|
}
|
|
}
|