crypt-aes.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. copy(ciphertext, ori)
  37. block, err := aes.NewCipher(key)
  38. if err != nil {
  39. panic(fmt.Errorf("Error creating new block cipher\n%v\n", err))
  40. }
  41. if len(ciphertext) < aes.BlockSize {
  42. panic(fmt.Errorf("ciphertext too short"))
  43. }
  44. iv := ciphertext[:aes.BlockSize]
  45. ciphertext = ciphertext[aes.BlockSize:]
  46. stream := cipher.NewCFBDecrypter(block, iv)
  47. // XORKeyStream can work in-place if the two arguments are the same.
  48. stream.XORKeyStream(ciphertext, ciphertext)
  49. return ciphertext
  50. }