aes.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package crypto
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "crypto/rand"
  6. "encoding/base64"
  7. "github.com/0xJacky/Nginx-UI/settings"
  8. "io"
  9. )
  10. // AesEncrypt encrypts text and given key with AES.
  11. func AesEncrypt(text []byte) ([]byte, error) {
  12. if len(text) == 0 {
  13. return nil, ErrPlainTextEmpty
  14. }
  15. block, err := aes.NewCipher(settings.CryptoSettings.GetSecretMd5())
  16. if err != nil {
  17. return nil, err
  18. }
  19. b := base64.StdEncoding.EncodeToString(text)
  20. ciphertext := make([]byte, aes.BlockSize+len(b))
  21. iv := ciphertext[:aes.BlockSize]
  22. if _, err = io.ReadFull(rand.Reader, iv); err != nil {
  23. return nil, err
  24. }
  25. cfb := cipher.NewCFBEncrypter(block, iv)
  26. cfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))
  27. return ciphertext, nil
  28. }
  29. // AesDecrypt decrypts text and given key with AES.
  30. func AesDecrypt(text []byte) ([]byte, error) {
  31. block, err := aes.NewCipher(settings.CryptoSettings.GetSecretMd5())
  32. if err != nil {
  33. return nil, err
  34. }
  35. if len(text) < aes.BlockSize {
  36. return nil, ErrCipherTextTooShort
  37. }
  38. iv := text[:aes.BlockSize]
  39. text = text[aes.BlockSize:]
  40. cfb := cipher.NewCFBDecrypter(block, iv)
  41. cfb.XORKeyStream(text, text)
  42. data, err := base64.StdEncoding.DecodeString(string(text))
  43. if err != nil {
  44. return nil, err
  45. }
  46. return data, nil
  47. }