crypto.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. n := len(crypted)
  56. blockSize := block.BlockSize()
  57. if n%blockSize != 0 {
  58. return nil, errors.New(`crypto/cipher: input not full blocks`)
  59. }
  60. blockMode := cipher.NewCBCDecrypter(block, a.IV[:blockSize])
  61. origData := make([]byte, n)
  62. blockMode.CryptBlocks(origData, crypted)
  63. origData = pkcs7UnPadding(origData)
  64. return origData, nil
  65. }
  66. func pkcs7Padding(cipherText []byte, blockSize int) []byte {
  67. padding := blockSize - len(cipherText)%blockSize
  68. padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  69. return append(cipherText, padtext...)
  70. }
  71. func pkcs7UnPadding(data []byte) []byte {
  72. length := len(data)
  73. unpadding := int(data[length-1])
  74. if unpadding >= length {
  75. return []byte(``)
  76. }
  77. return data[:(length - unpadding)]
  78. }