crypto.go 1.8 KB

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