You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
1.1 KiB

  1. package util
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "crypto/rand"
  6. "errors"
  7. "io"
  8. "github.com/chrislusf/seaweedfs/weed/glog"
  9. )
  10. type CipherKey []byte
  11. func GenCipherKey() CipherKey {
  12. key := make([]byte, 32)
  13. if _, err := io.ReadFull(rand.Reader, key); err != nil {
  14. glog.Fatalf("random key gen: %v", err)
  15. }
  16. return CipherKey(key)
  17. }
  18. func Encrypt(plaintext []byte, key CipherKey) ([]byte, error) {
  19. c, err := aes.NewCipher(key)
  20. if err != nil {
  21. return nil, err
  22. }
  23. gcm, err := cipher.NewGCM(c)
  24. if err != nil {
  25. return nil, err
  26. }
  27. nonce := make([]byte, gcm.NonceSize())
  28. if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
  29. return nil, err
  30. }
  31. return gcm.Seal(nonce, nonce, plaintext, nil), nil
  32. }
  33. func Decrypt(ciphertext []byte, key CipherKey) ([]byte, error) {
  34. c, err := aes.NewCipher(key)
  35. if err != nil {
  36. return nil, err
  37. }
  38. gcm, err := cipher.NewGCM(c)
  39. if err != nil {
  40. return nil, err
  41. }
  42. nonceSize := gcm.NonceSize()
  43. if len(ciphertext) < nonceSize {
  44. return nil, errors.New("ciphertext too short")
  45. }
  46. nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
  47. return gcm.Open(nil, nonce, ciphertext, nil)
  48. }