AESCBC.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package util
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "encoding/hex"
  7. "errors"
  8. "strings"
  9. )
  10. var PwdKey = "4MTGXKRGWVHCVC7C"
  11. //PKCS7 填充模式
  12. func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
  13. padding := blockSize - len(ciphertext)%blockSize
  14. //Repeat()函数的功能是把切片[]byte{byte(padding)}复制padding个,然后合并成新的字节切片返回
  15. padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  16. return append(ciphertext, padtext...)
  17. }
  18. //填充的反向操作,删除填充字符串
  19. func PKCS7UnPadding1(origData []byte) ([]byte, error) {
  20. //获取数据长度
  21. length := len(origData)
  22. if length == 0 {
  23. return nil, errors.New("加密字符串错误!")
  24. } else {
  25. //获取填充字符串长度
  26. unpadding := int(origData[length-1])
  27. //截取切片,删除填充字节,并且返回明文
  28. return origData[:(length - unpadding)], nil
  29. }
  30. }
  31. //实现加密
  32. func AesEcrypt(origData []byte, key []byte) ([]byte, error) {
  33. //创建加密算法实例
  34. block, err := aes.NewCipher(key)
  35. if err != nil {
  36. return nil, err
  37. }
  38. //获取块的大小
  39. blockSize := block.BlockSize()
  40. //对数据进行填充,让数据长度满足需求
  41. origData = PKCS7Padding(origData, blockSize)
  42. //采用AES加密方法中CBC加密模式
  43. blocMode := cipher.NewCBCEncrypter(block, key[:blockSize])
  44. crypted := make([]byte, len(origData))
  45. //执行加密
  46. blocMode.CryptBlocks(crypted, origData)
  47. return crypted, nil
  48. }
  49. //实现解密
  50. func AesDeCrypt(cypted []byte, key []byte) (string, error) {
  51. //创建加密算法实例
  52. block, err := aes.NewCipher(key)
  53. if err != nil {
  54. return "", err
  55. }
  56. //获取块大小
  57. blockSize := block.BlockSize()
  58. //创建加密客户端实例
  59. blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
  60. origData := make([]byte, len(cypted))
  61. //这个函数也可以用来解密
  62. blockMode.CryptBlocks(origData, cypted)
  63. //去除填充字符串
  64. origData, err = PKCS7UnPadding1(origData)
  65. if err != nil {
  66. return "", err
  67. }
  68. return string(origData), err
  69. }
  70. //加密base64
  71. func EnPwdCode(pwdStr,PwdKey string) string {
  72. pwd := []byte(pwdStr)
  73. result, err := AesEcrypt(pwd, []byte(PwdKey))
  74. if err != nil {
  75. return ""
  76. }
  77. return hex.EncodeToString(result)
  78. }
  79. //解密
  80. func dePwdCode(pwd,PwdKey string) string {
  81. temp, _ := hex.DecodeString(pwd)
  82. //执行AES解密
  83. res, _:=AesDeCrypt(temp, []byte(PwdKey))
  84. return res
  85. }
  86. func GetPri(pwd,PwdKey string)string {
  87. result :=dePwdCode(pwd,strings.ToUpper(PwdKey))
  88. return result
  89. }
  90. func EnPriCode(pwdStr,PwdKey string)string{
  91. result :=EnPwdCode(pwdStr,strings.ToUpper(PwdKey))
  92. return result
  93. }