crypto.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package myth
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. )
  7. var (
  8. aesKey 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. aesKey = password
  18. }
  19. // GetAesCryptoKey get current key
  20. func GetAesCryptoKey() string {
  21. return aesKey
  22. }
  23. // NewAesCrypto new AesCrypto
  24. func NewAesCrypto() *AesCrypto {
  25. return &AesCrypto{[]byte(aesKey)}
  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(data []byte) ([]byte, error) {
  33. block, err := aes.NewCipher(a.Key)
  34. if err != nil {
  35. return nil, err
  36. }
  37. blockSize := block.BlockSize()
  38. data = pkcs5Padding(data, blockSize)
  39. blockMode := cipher.NewCBCEncrypter(block, a.Key[:blockSize])
  40. crypted := make([]byte, len(data))
  41. blockMode.CryptBlocks(crypted, data)
  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. }