encoding.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package encoding
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "encoding/base64"
  7. "encoding/json"
  8. "errors"
  9. )
  10. //EncryptConfig 加密配置
  11. type EncryptConfig struct {
  12. Key string
  13. IV string
  14. }
  15. //JSON JSON格式化增加对[]byte的支持
  16. func JSON(o interface{}) string {
  17. var v []byte
  18. switch o1 := o.(type) {
  19. case [][]byte:
  20. o2 := make([]interface{}, len(o1))
  21. for i := 0; i < len(o1); i++ {
  22. o2[i] = string(o1[i])
  23. }
  24. v, _ = json.Marshal(o2)
  25. case []interface{}:
  26. for i := 0; i < len(o1); i++ {
  27. if b, ok := o1[i].([]byte); ok {
  28. o1[i] = string(b)
  29. }
  30. }
  31. v, _ = json.Marshal(o1)
  32. default:
  33. v, _ = json.Marshal(o)
  34. }
  35. if len(v) > 0 {
  36. return string(v)
  37. }
  38. return ""
  39. }
  40. //填充到BlockSize整数倍长度,如果正好就是对的长度,再多填充一个BlockSize长度
  41. func pad(src []byte) []byte {
  42. padding := aes.BlockSize - len(src)%aes.BlockSize
  43. padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  44. return append(src, padtext...)
  45. }
  46. //去除填充的字节
  47. func unpad(src []byte) ([]byte, error) {
  48. length := len(src)
  49. if length == 0 {
  50. return []byte{0}, nil
  51. }
  52. unpadding := int(src[length-1])
  53. if unpadding > length {
  54. return nil, errors.New("unpad error. This could happen when incorrect encryption key is used")
  55. }
  56. return src[:(length - unpadding)], nil
  57. }
  58. //Encrypt 加密
  59. func Encrypt(text string, c *EncryptConfig) (string, error) {
  60. if "" == text {
  61. return "", nil
  62. }
  63. block, err := aes.NewCipher([]byte(c.Key))
  64. if err != nil {
  65. return "", err
  66. }
  67. msg := pad([]byte(text))
  68. ciphertext := make([]byte, len(msg))
  69. mode := cipher.NewCBCEncrypter(block, []byte(c.IV))
  70. mode.CryptBlocks(ciphertext, msg)
  71. finalMsg := base64.StdEncoding.EncodeToString(ciphertext)
  72. return finalMsg, nil
  73. }
  74. //Decrypt 解密
  75. func Decrypt(text string, c *EncryptConfig) (string, error) {
  76. if "" == text {
  77. return "", nil
  78. }
  79. block, err := aes.NewCipher([]byte(c.Key))
  80. if err != nil {
  81. return "", err
  82. }
  83. decodedMsg, err := base64.StdEncoding.DecodeString(text)
  84. if err != nil {
  85. return "", err
  86. }
  87. if (len(decodedMsg) % aes.BlockSize) != 0 {
  88. return "", errors.New("blocksize must be multipe of decoded message length")
  89. }
  90. msg := decodedMsg
  91. mode := cipher.NewCBCDecrypter(block, []byte(c.IV))
  92. mode.CryptBlocks(msg, msg)
  93. unpadMsg, err := unpad(msg)
  94. if err != nil {
  95. return "", err
  96. }
  97. return string(unpadMsg), nil
  98. }