crypt-aes.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package util
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "crypto/rand"
  6. "fmt"
  7. "io"
  8. )
  9. // KeyAES func
  10. func KeyAES() []byte {
  11. var err error
  12. var key = make([]byte, 32)
  13. if _, err = rand.Read(key); err != nil {
  14. panic(fmt.Errorf("Error generate aes key\n\n%+v", err))
  15. }
  16. return key
  17. }
  18. // EncryptAES func
  19. func EncryptAES(key, data []byte) []byte {
  20. block, err := aes.NewCipher(key)
  21. if err != nil {
  22. panic(err)
  23. }
  24. ciphertext := make([]byte, aes.BlockSize+len(data))
  25. iv := ciphertext[:aes.BlockSize]
  26. if _, err := io.ReadFull(rand.Reader, iv); err != nil {
  27. panic(err)
  28. }
  29. stream := cipher.NewCFBEncrypter(block, iv)
  30. stream.XORKeyStream(ciphertext[aes.BlockSize:], data)
  31. return ciphertext
  32. }
  33. // DecryptAES func
  34. func DecryptAES(key, ori []byte) []byte {
  35. ciphertext := make([]byte, len(ori))
  36. block, err := aes.NewCipher(key)
  37. if err != nil {
  38. panic(fmt.Errorf("Error creating new block cipher\n%v\n", err))
  39. }
  40. if len(ciphertext) < aes.BlockSize {
  41. panic(fmt.Errorf("ciphertext too short"))
  42. }
  43. iv := ciphertext[:aes.BlockSize]
  44. ciphertext = ciphertext[aes.BlockSize:]
  45. stream := cipher.NewCFBDecrypter(block, iv)
  46. // XORKeyStream can work in-place if the two arguments are the same.
  47. stream.XORKeyStream(ciphertext, ciphertext)
  48. return ciphertext
  49. }