encryption.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package util
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "crypto/rand"
  6. "io"
  7. "github.com/grafana/grafana/pkg/log"
  8. )
  9. func Decrypt(payload []byte, secret string) []byte {
  10. key := encryptionKeyToBytes(secret)
  11. block, err := aes.NewCipher(key)
  12. if err != nil {
  13. log.Fatal(4, err.Error())
  14. }
  15. // The IV needs to be unique, but not secure. Therefore it's common to
  16. // include it at the beginning of the ciphertext.
  17. if len(payload) < aes.BlockSize {
  18. log.Fatal(4, "payload too short")
  19. }
  20. iv := payload[:aes.BlockSize]
  21. payload = payload[aes.BlockSize:]
  22. stream := cipher.NewCFBDecrypter(block, iv)
  23. // XORKeyStream can work in-place if the two arguments are the same.
  24. stream.XORKeyStream(payload, payload)
  25. return payload
  26. }
  27. func Encrypt(payload []byte, secret string) []byte {
  28. key := encryptionKeyToBytes(secret)
  29. block, err := aes.NewCipher(key)
  30. if err != nil {
  31. log.Fatal(4, err.Error())
  32. }
  33. // The IV needs to be unique, but not secure. Therefore it's common to
  34. // include it at the beginning of the ciphertext.
  35. ciphertext := make([]byte, aes.BlockSize+len(payload))
  36. iv := ciphertext[:aes.BlockSize]
  37. if _, err := io.ReadFull(rand.Reader, iv); err != nil {
  38. log.Fatal(4, err.Error())
  39. }
  40. stream := cipher.NewCFBEncrypter(block, iv)
  41. stream.XORKeyStream(ciphertext[aes.BlockSize:], payload)
  42. return ciphertext
  43. }
  44. // Key needs to be 32bytes
  45. func encryptionKeyToBytes(secret string) []byte {
  46. key := make([]byte, 32, 32)
  47. keyBytes := []byte(secret)
  48. secretLength := len(keyBytes)
  49. for i := 0; i < 32; i++ {
  50. key[i] = keyBytes[i%secretLength]
  51. }
  52. return key
  53. }