crypt-aes.go 1.2 KB

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