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. // Encrypt aes encrypt
  9. func Encrypt(origData []byte) ([]byte, error) {
  10. block, err := aes.NewCipher(key)
  11. if err != nil {
  12. return nil, err
  13. }
  14. blockSize := block.BlockSize()
  15. origData = PKCS5Padding(origData, blockSize)
  16. blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
  17. crypted := make([]byte, len(origData))
  18. blockMode.CryptBlocks(crypted, origData)
  19. return crypted, nil
  20. }
  21. // Decrypt aes encrypt
  22. func Decrypt(crypted []byte) ([]byte, error) {
  23. block, err := aes.NewCipher(key)
  24. if err != nil {
  25. return nil, err
  26. }
  27. blockSize := block.BlockSize()
  28. blockMode := cipher.NewCBCDecrypter(block, key[: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. }