aes.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package tyr
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. )
  7. var (
  8. key string
  9. )
  10. // AesCrypto define
  11. type AesCrypto struct {
  12. Key []byte
  13. }
  14. // SetAesCryptoKey set key,
  15. // key length:16, 24, 32 bytes to AES-128, AES-192, AES-256
  16. func SetAesCryptoKey(password string) {
  17. key = password
  18. }
  19. // GetAesCryptoKey get current key
  20. func GetAesCryptoKey() string {
  21. return key
  22. }
  23. // NewAesCrypto new AesCrypto
  24. func NewAesCrypto() *AesCrypto {
  25. return &AesCrypto{[]byte(key)}
  26. }
  27. // SetKey set key
  28. func (a *AesCrypto) SetKey(key string) {
  29. a.Key = []byte(key)
  30. }
  31. // Encrypt encrypt data
  32. func (a *AesCrypto) Encrypt(origData []byte) ([]byte, error) {
  33. block, err := aes.NewCipher(a.Key)
  34. if err != nil {
  35. return nil, err
  36. }
  37. blockSize := block.BlockSize()
  38. origData = pkcs5Padding(origData, blockSize)
  39. blockMode := cipher.NewCBCEncrypter(block, a.Key[:blockSize])
  40. crypted := make([]byte, len(origData))
  41. blockMode.CryptBlocks(crypted, origData)
  42. return crypted, nil
  43. }
  44. // Decrypt decrypt data
  45. func (a *AesCrypto) Decrypt(crypted []byte) ([]byte, error) {
  46. block, err := aes.NewCipher(a.Key)
  47. if err != nil {
  48. return nil, err
  49. }
  50. blockSize := block.BlockSize()
  51. blockMode := cipher.NewCBCDecrypter(block, a.Key[:blockSize])
  52. origData := make([]byte, len(crypted))
  53. blockMode.CryptBlocks(origData, crypted)
  54. origData = pkcs5UnPadding(origData)
  55. return origData, nil
  56. }
  57. func pkcs5Padding(ciphertext []byte, blockSize int) []byte {
  58. padding := blockSize - len(ciphertext)%blockSize
  59. padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  60. return append(ciphertext, padtext...)
  61. }
  62. func pkcs5UnPadding(data []byte) []byte {
  63. length := len(data)
  64. unpadding := int(data[length-1])
  65. if unpadding >= length {
  66. return []byte(``)
  67. }
  68. return data[:(length - unpadding)]
  69. }