encryption.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. if secretLength > i {
  51. key[i] = keyBytes[i]
  52. } else {
  53. key[i] = 0
  54. }
  55. }
  56. return key
  57. }