gcm.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // Copyright (c) 2022 Tulir Asokan
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this
  5. // file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6. package gcmutil
  7. import (
  8. "crypto/aes"
  9. "crypto/cipher"
  10. "fmt"
  11. )
  12. func Prepare(secretKey []byte) (gcm cipher.AEAD, err error) {
  13. var block cipher.Block
  14. if block, err = aes.NewCipher(secretKey); err != nil {
  15. err = fmt.Errorf("failed to initialize AES cipher: %w", err)
  16. } else if gcm, err = cipher.NewGCM(block); err != nil {
  17. err = fmt.Errorf("failed to initialize GCM: %w", err)
  18. }
  19. return
  20. }
  21. func Decrypt(secretKey, iv, ciphertext, additionalData []byte) ([]byte, error) {
  22. if gcm, err := Prepare(secretKey); err != nil {
  23. return nil, err
  24. } else if plaintext, decryptErr := gcm.Open(nil, iv, ciphertext, additionalData); decryptErr != nil {
  25. return nil, decryptErr
  26. } else {
  27. return plaintext, nil
  28. }
  29. }
  30. func Encrypt(secretKey, iv, plaintext, additionalData []byte) ([]byte, error) {
  31. if gcm, err := Prepare(secretKey); err != nil {
  32. return nil, err
  33. } else {
  34. return gcm.Seal(nil, iv, plaintext, additionalData), nil
  35. }
  36. }