crypto_test.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package telegram
  2. import (
  3. "encoding/base64"
  4. "testing"
  5. )
  6. func mustKey(t *testing.T) string {
  7. t.Helper()
  8. // 32 zero-bytes → stable base64 for test determinism.
  9. return base64.StdEncoding.EncodeToString(make([]byte, 32))
  10. }
  11. func TestCryptoRoundTrip(t *testing.T) {
  12. c, err := NewCrypto(mustKey(t))
  13. if err != nil {
  14. t.Fatal(err)
  15. }
  16. ct, err := c.Encrypt("xing")
  17. if err != nil {
  18. t.Fatal(err)
  19. }
  20. pt, err := c.Decrypt(ct)
  21. if err != nil {
  22. t.Fatal(err)
  23. }
  24. if pt != "xing" {
  25. t.Errorf("roundtrip got %q want %q", pt, "xing")
  26. }
  27. }
  28. func TestCryptoRejectsShortKey(t *testing.T) {
  29. short := base64.StdEncoding.EncodeToString(make([]byte, 16))
  30. if _, err := NewCrypto(short); err == nil {
  31. t.Error("expected err for 16-byte key")
  32. }
  33. }
  34. func TestCryptoRejectsTamperedCiphertext(t *testing.T) {
  35. c, _ := NewCrypto(mustKey(t))
  36. ct, _ := c.Encrypt("secret")
  37. ct[len(ct)-1] ^= 0xFF
  38. if _, err := c.Decrypt(ct); err == nil {
  39. t.Error("expected tamper detection")
  40. }
  41. }
  42. func TestCryptoNonceRandomness(t *testing.T) {
  43. c, _ := NewCrypto(mustKey(t))
  44. a, _ := c.Encrypt("same")
  45. b, _ := c.Encrypt("same")
  46. if string(a) == string(b) {
  47. t.Error("identical ciphertexts imply nonce reuse")
  48. }
  49. }