aes.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package base
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "encoding/base64"
  7. "errors"
  8. "fmt"
  9. )
  10. // AES CBC 加密
  11. func aesEncryptCBC(origData, key []byte) (crypted []byte, err error) {
  12. defer func() {
  13. if r := recover(); r != nil {
  14. crypted = nil
  15. err = errors.New(fmt.Sprintf("%v", r))
  16. }
  17. }()
  18. block, err := aes.NewCipher(key)
  19. if err != nil {
  20. return
  21. }
  22. blockSize := block.BlockSize()
  23. origData = zeroPadding(origData, blockSize)
  24. blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
  25. crypted = make([]byte, len(origData))
  26. blockMode.CryptBlocks(crypted, origData)
  27. return
  28. }
  29. // AES CBC 加密后做一次Base64加密
  30. func aesEncryptCBCWithBase64(origData, key []byte) (string, error) {
  31. cbc, err := aesEncryptCBC(origData, key)
  32. if err != nil {
  33. return "", err
  34. }
  35. return base64.StdEncoding.EncodeToString(cbc), nil
  36. }
  37. func zeroPadding(ciphertext []byte, blockSize int) []byte {
  38. padding := blockSize - len(ciphertext)%blockSize
  39. if padding == 0 {
  40. return ciphertext
  41. }
  42. padtext := bytes.Repeat([]byte{byte(0)}, padding)
  43. return append(ciphertext, padtext...)
  44. }