aes_test.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package crypto
  2. import (
  3. "github.com/0xJacky/Nginx-UI/settings"
  4. "testing"
  5. "github.com/stretchr/testify/assert"
  6. "github.com/stretchr/testify/require"
  7. )
  8. func EncryptDecryptRoundTrip(text string) bool {
  9. encrypted, err := AesEncrypt([]byte(text))
  10. if err != nil {
  11. return false
  12. }
  13. decrypted, err := AesDecrypt(encrypted)
  14. if err != nil {
  15. return false
  16. }
  17. return text == string(decrypted)
  18. }
  19. func EncryptsNonEmptyStringWithoutError(text string) bool {
  20. _, err := AesEncrypt([]byte(text))
  21. return err == nil
  22. }
  23. func DecryptsToOriginalTextAfterEncryption(text string) bool {
  24. encrypted, _ := AesEncrypt([]byte(text))
  25. decrypted, err := AesDecrypt(encrypted)
  26. if err != nil {
  27. return false
  28. }
  29. return text == string(decrypted)
  30. }
  31. func FailsToDecryptWithModifiedCiphertext(text string) bool {
  32. encrypted, _ := AesEncrypt([]byte(text))
  33. // Modify the ciphertext
  34. encrypted[0] ^= 0xff
  35. _, err := AesDecrypt(encrypted)
  36. return err != nil
  37. }
  38. func FailsToDecryptShortCiphertext() bool {
  39. _, err := AesDecrypt([]byte("short"))
  40. return err != nil
  41. }
  42. func TestAesEncryptionDecryption(t *testing.T) {
  43. settings.CryptoSettings.Secret = "test"
  44. assert.True(t, EncryptDecryptRoundTrip("Hello, world!"), "should encrypt and decrypt to the original text")
  45. assert.True(t, EncryptsNonEmptyStringWithoutError("Test String"), "should encrypt a non-empty string without error")
  46. assert.True(t, DecryptsToOriginalTextAfterEncryption("Another Test String"), "should decrypt to the original text after encryption")
  47. assert.True(t, FailsToDecryptWithModifiedCiphertext("Sensitive Data"), "should fail to decrypt with modified ciphertext")
  48. assert.True(t, FailsToDecryptShortCiphertext(), "should fail to decrypt short ciphertext")
  49. }
  50. func TestAesEncrypt_WithEmptyString_ReturnsError(t *testing.T) {
  51. settings.CryptoSettings.Secret = "test"
  52. _, err := AesEncrypt([]byte(""))
  53. require.Error(t, err, "encrypting an empty string should return an error")
  54. }
  55. func TestAesDecrypt_WithInvalidBase64_ReturnsError(t *testing.T) {
  56. settings.CryptoSettings.Secret = "test"
  57. // Assuming the function is modified to handle this case explicitly
  58. encrypted, _ := AesEncrypt([]byte("valid text"))
  59. // Invalidate the base64 encoding
  60. encrypted[len(encrypted)-1] = '!'
  61. _, err := AesDecrypt(encrypted)
  62. require.Error(t, err, "decrypting an invalid base64 string should return an error")
  63. }