aes.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package service
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. )
  7. // Encrypt aes encrypt
  8. func Encrypt(origData []byte, key []byte) ([]byte, error) {
  9. block, err := aes.NewCipher(key)
  10. if err != nil {
  11. return nil, err
  12. }
  13. blockSize := block.BlockSize()
  14. origData = PKCS5Padding(origData, blockSize)
  15. blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
  16. crypted := make([]byte, len(origData))
  17. blockMode.CryptBlocks(crypted, origData)
  18. return crypted, nil
  19. }
  20. // Decrypt aes encrypt
  21. func Decrypt(crypted []byte, key []byte) ([]byte, error) {
  22. block, err := aes.NewCipher(key)
  23. if err != nil {
  24. return nil, err
  25. }
  26. blockSize := block.BlockSize()
  27. blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
  28. origData := make([]byte, len(crypted))
  29. blockMode.CryptBlocks(origData, crypted)
  30. origData = PKCS5UnPadding(origData)
  31. return origData, nil
  32. }
  33. // PKCS5Padding padding
  34. func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
  35. padding := blockSize - len(ciphertext)%blockSize
  36. padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  37. return append(ciphertext, padtext...)
  38. }
  39. // PKCS5UnPadding unpadding
  40. func PKCS5UnPadding(origData []byte) []byte {
  41. length := len(origData)
  42. unpadding := int(origData[length-1])
  43. return origData[:(length - unpadding)]
  44. }