1
0

aes.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package cryptoutil
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "crypto/rand"
  6. "github.com/cockroachdb/errors"
  7. )
  8. // AESGCMEncrypt encrypts plaintext with the given key using AES in GCM mode.
  9. func AESGCMEncrypt(key, plaintext []byte) ([]byte, error) {
  10. block, err := aes.NewCipher(key)
  11. if err != nil {
  12. return nil, err
  13. }
  14. gcm, err := cipher.NewGCM(block)
  15. if err != nil {
  16. return nil, err
  17. }
  18. nonce := make([]byte, gcm.NonceSize())
  19. if _, err := rand.Read(nonce); err != nil {
  20. return nil, err
  21. }
  22. ciphertext := gcm.Seal(nil, nonce, plaintext, nil)
  23. return append(nonce, ciphertext...), nil
  24. }
  25. // AESGCMDecrypt decrypts ciphertext with the given key using AES in GCM mode.
  26. func AESGCMDecrypt(key, ciphertext []byte) ([]byte, error) {
  27. block, err := aes.NewCipher(key)
  28. if err != nil {
  29. return nil, err
  30. }
  31. gcm, err := cipher.NewGCM(block)
  32. if err != nil {
  33. return nil, err
  34. }
  35. size := gcm.NonceSize()
  36. if len(ciphertext)-size <= 0 {
  37. return nil, errors.New("ciphertext is empty")
  38. }
  39. nonce := ciphertext[:size]
  40. ciphertext = ciphertext[size:]
  41. return gcm.Open(nil, nonce, ciphertext, nil)
  42. }