aes.go 1.3 KB

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