cipher.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package util
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "crypto/rand"
  6. "errors"
  7. "io"
  8. "github.com/seaweedfs/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. }