|
| 1 | +package crypto_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "testing" |
| 6 | + |
| 7 | + "github.com/weprodev/go-pkg/crypto" |
| 8 | +) |
| 9 | + |
| 10 | +func TestAESService_Validation(t *testing.T) { |
| 11 | + shortKey := []byte("short_key") |
| 12 | + if _, err := crypto.NewAESService(shortKey); err == nil { |
| 13 | + t.Fatal("expected error for non-32-byte key") |
| 14 | + } |
| 15 | + |
| 16 | + validKey := make([]byte, 32) |
| 17 | + if _, err := crypto.NewAESService(validKey); err != nil { |
| 18 | + t.Fatalf("unexpected error for 32-byte key: %v", err) |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +func TestAESService_EncryptDecrypt(t *testing.T) { |
| 23 | + key := []byte("0123456789abcdef0123456789abcdef") // 32 bytes |
| 24 | + svc, err := crypto.NewAESService(key) |
| 25 | + if err != nil { |
| 26 | + t.Fatalf("failed to create AES service: %v", err) |
| 27 | + } |
| 28 | + |
| 29 | + plaintext := []byte("hello world this is a secret") |
| 30 | + ciphertext, err := svc.Encrypt(plaintext) |
| 31 | + if err != nil { |
| 32 | + t.Fatalf("encryption failed: %v", err) |
| 33 | + } |
| 34 | + |
| 35 | + if bytes.Equal(plaintext, ciphertext) { |
| 36 | + t.Fatal("ciphertext should not match plaintext") |
| 37 | + } |
| 38 | + |
| 39 | + decrypted, err := svc.Decrypt(ciphertext) |
| 40 | + if err != nil { |
| 41 | + t.Fatalf("decryption failed: %v", err) |
| 42 | + } |
| 43 | + |
| 44 | + if !bytes.Equal(plaintext, decrypted) { |
| 45 | + t.Errorf("expected %s, got %s", plaintext, decrypted) |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +func TestAESService_DecryptShortCiphertext(t *testing.T) { |
| 50 | + key := []byte("0123456789abcdef0123456789abcdef") |
| 51 | + svc, _ := crypto.NewAESService(key) |
| 52 | + |
| 53 | + // Minimal GCM nonce size is 12. Providing less than that should error out safely. |
| 54 | + shortData := []byte("too_short") |
| 55 | + _, err := svc.Decrypt(shortData) |
| 56 | + if err == nil { |
| 57 | + t.Fatal("expected error decoding short ciphertext") |
| 58 | + } |
| 59 | +} |
0 commit comments