crypto.go 1.9 KB

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