aesecb_test.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package codec
  2. import (
  3. "encoding/base64"
  4. "testing"
  5. "github.com/stretchr/testify/assert"
  6. )
  7. func TestAesEcb(t *testing.T) {
  8. var (
  9. key = []byte("q4t7w!z%C*F-JaNdRgUjXn2r5u8x/A?D")
  10. val = []byte("hello")
  11. badKey1 = []byte("aaaaaaaaa")
  12. // more than 32 chars
  13. badKey2 = []byte("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
  14. )
  15. _, err := EcbEncrypt(badKey1, val)
  16. assert.NotNil(t, err)
  17. _, err = EcbEncrypt(badKey2, val)
  18. assert.NotNil(t, err)
  19. dst, err := EcbEncrypt(key, val)
  20. assert.Nil(t, err)
  21. _, err = EcbDecrypt(badKey1, dst)
  22. assert.NotNil(t, err)
  23. _, err = EcbDecrypt(badKey2, dst)
  24. assert.NotNil(t, err)
  25. _, err = EcbDecrypt(key, val)
  26. // not enough block, just nil
  27. assert.Nil(t, err)
  28. src, err := EcbDecrypt(key, dst)
  29. assert.Nil(t, err)
  30. assert.Equal(t, val, src)
  31. }
  32. func TestAesEcbBase64(t *testing.T) {
  33. const (
  34. val = "hello"
  35. badKey1 = "aaaaaaaaa"
  36. // more than 32 chars
  37. badKey2 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
  38. )
  39. key := []byte("q4t7w!z%C*F-JaNdRgUjXn2r5u8x/A?D")
  40. b64Key := base64.StdEncoding.EncodeToString(key)
  41. b64Val := base64.StdEncoding.EncodeToString([]byte(val))
  42. _, err := EcbEncryptBase64(badKey1, val)
  43. assert.NotNil(t, err)
  44. _, err = EcbEncryptBase64(badKey2, val)
  45. assert.NotNil(t, err)
  46. _, err = EcbEncryptBase64(b64Key, val)
  47. assert.NotNil(t, err)
  48. dst, err := EcbEncryptBase64(b64Key, b64Val)
  49. assert.Nil(t, err)
  50. _, err = EcbDecryptBase64(badKey1, dst)
  51. assert.NotNil(t, err)
  52. _, err = EcbDecryptBase64(badKey2, dst)
  53. assert.NotNil(t, err)
  54. _, err = EcbDecryptBase64(b64Key, val)
  55. assert.NotNil(t, err)
  56. src, err := EcbDecryptBase64(b64Key, dst)
  57. assert.Nil(t, err)
  58. b, err := base64.StdEncoding.DecodeString(src)
  59. assert.Nil(t, err)
  60. assert.Equal(t, val, string(b))
  61. }