aes.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package tools
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "encoding/base64"
  7. "errors"
  8. )
  9. // AES 加密
  10. func AesEncrypt(orig string, _Aeskey string) (string, error) {
  11. origData := []byte(orig)
  12. key := []byte(_Aeskey)
  13. block, err := aes.NewCipher(key)
  14. if err != nil {
  15. return "", err
  16. }
  17. blockSize := block.BlockSize()
  18. origData = func(ciphertext []byte, blockSize int) []byte {
  19. padding := blockSize - len(ciphertext)%blockSize
  20. padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  21. return append(ciphertext, padtext...)
  22. }(origData, blockSize)
  23. blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
  24. crypted := make([]byte, len(origData))
  25. blockMode.CryptBlocks(crypted, origData)
  26. return base64.StdEncoding.EncodeToString(crypted), nil
  27. }
  28. // AES 解密
  29. func AesDecrypt(cryted string, _Aeskey string) (string, error) {
  30. if cryted == "" {
  31. return "", errors.New("错误的数据")
  32. }
  33. crypted, err := base64.StdEncoding.DecodeString(cryted)
  34. if err != nil {
  35. return "", err
  36. }
  37. key := []byte(_Aeskey)
  38. block, err := aes.NewCipher(key)
  39. if err != nil {
  40. return "", err
  41. }
  42. blockSize := block.BlockSize()
  43. blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
  44. origData := make([]byte, len(crypted))
  45. blockMode.CryptBlocks(origData, crypted)
  46. origData = func(origData []byte) []byte {
  47. length := len(origData)
  48. unpadding := int(origData[length-1])
  49. return origData[:(length - unpadding)]
  50. }(origData)
  51. return string(origData[:]), nil
  52. }