aes.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package utils
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "encoding/base64"
  7. "errors"
  8. )
  9. // pkcs7Padding 填充
  10. func pkcs7Padding(data []byte, blockSize int) []byte {
  11. //判断缺少几位长度。最少1,最多 blockSize
  12. padding := blockSize - len(data)%blockSize
  13. //补足位数。把切片[]byte{byte(padding)}复制padding个
  14. padText := bytes.Repeat([]byte{byte(padding)}, padding)
  15. return append(data, padText...)
  16. }
  17. // pkcs7UnPadding 填充的反向操作
  18. func pkcs7UnPadding(data []byte) ([]byte, error) {
  19. length := len(data)
  20. if length == 0 {
  21. return nil, errors.New("加密字符串错误!")
  22. }
  23. //获取填充的个数
  24. unPadding := int(data[length-1])
  25. return data[:(length - unPadding)], nil
  26. }
  27. // AesEncrypt 加密
  28. func AesEncrypt(cipherText string, sKey string) (string, error) {
  29. data := []byte(cipherText)
  30. key := []byte(sKey)
  31. //创建加密实例
  32. block, err := aes.NewCipher(key)
  33. if err != nil {
  34. return "", err
  35. }
  36. //判断加密块的大小
  37. blockSize := block.BlockSize()
  38. //填充
  39. encryptBytes := pkcs7Padding(data, blockSize)
  40. //初始化加密数据接收切片
  41. crypted := make([]byte, len(encryptBytes))
  42. //使用cbc加密模式
  43. blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
  44. //执行加密
  45. blockMode.CryptBlocks(crypted, encryptBytes)
  46. return base64.StdEncoding.EncodeToString(crypted), nil
  47. }
  48. // AesDecrypt 解密
  49. func AesDecrypt(encryptText string, sKey string) (string, error) {
  50. key := []byte(sKey)
  51. data, _ := base64.StdEncoding.DecodeString(encryptText)
  52. //创建实例
  53. block, err := aes.NewCipher(key)
  54. if err != nil {
  55. return "", err
  56. }
  57. //获取块的大小
  58. blockSize := block.BlockSize()
  59. //使用cbc
  60. blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
  61. //初始化解密数据接收切片
  62. crypted := make([]byte, len(data))
  63. //执行解密
  64. blockMode.CryptBlocks(crypted, data)
  65. //去除填充
  66. crypted, err = pkcs7UnPadding(crypted)
  67. if err != nil {
  68. return "", err
  69. }
  70. return string(crypted), nil
  71. }