aes.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package aes
  2. import (
  3. "bytes"
  4. cryptoAes "crypto/aes"
  5. "crypto/cipher"
  6. "encoding/base64"
  7. )
  8. var _ Aes = (*aes)(nil)
  9. type Aes interface {
  10. i()
  11. // Encrypt 加密
  12. Encrypt(encryptStr string) (string, error)
  13. // Decrypt 解密
  14. Decrypt(decryptStr string) (string, error)
  15. }
  16. type aes struct {
  17. key string
  18. iv string
  19. }
  20. func New(key, iv string) Aes {
  21. return &aes{
  22. key: key,
  23. iv: iv,
  24. }
  25. }
  26. func (a *aes) i() {}
  27. func (a *aes) Encrypt(encryptStr string) (string, error) {
  28. encryptBytes := []byte(encryptStr)
  29. block, err := cryptoAes.NewCipher([]byte(a.key))
  30. if err != nil {
  31. return "", err
  32. }
  33. blockSize := block.BlockSize()
  34. encryptBytes = pkcs5Padding(encryptBytes, blockSize)
  35. blockMode := cipher.NewCBCEncrypter(block, []byte(a.iv))
  36. encrypted := make([]byte, len(encryptBytes))
  37. blockMode.CryptBlocks(encrypted, encryptBytes)
  38. return base64.URLEncoding.EncodeToString(encrypted), nil
  39. }
  40. func (a *aes) Decrypt(decryptStr string) (string, error) {
  41. decryptBytes, err := base64.URLEncoding.DecodeString(decryptStr)
  42. if err != nil {
  43. return "", err
  44. }
  45. block, err := cryptoAes.NewCipher([]byte(a.key))
  46. if err != nil {
  47. return "", err
  48. }
  49. blockMode := cipher.NewCBCDecrypter(block, []byte(a.iv))
  50. decrypted := make([]byte, len(decryptBytes))
  51. blockMode.CryptBlocks(decrypted, decryptBytes)
  52. decrypted = pkcs5UnPadding(decrypted)
  53. return string(decrypted), nil
  54. }
  55. func pkcs5Padding(cipherText []byte, blockSize int) []byte {
  56. padding := blockSize - len(cipherText)%blockSize
  57. padText := bytes.Repeat([]byte{byte(padding)}, padding)
  58. return append(cipherText, padText...)
  59. }
  60. func pkcs5UnPadding(decrypted []byte) []byte {
  61. length := len(decrypted)
  62. unPadding := int(decrypted[length-1])
  63. return decrypted[:(length - unPadding)]
  64. }