encrypt

encrypt encrypts and decrypts data for transport and storage using AES-GCM authenticated encryption.

Part of nurago, a collection of independent Go packages for backend services.

import "github.com/tecnickcom/nurago/pkg/encrypt"

Package encrypt encrypts and decrypts data for transport and storage using AES-GCM authenticated encryption.

It protects application payloads moving between systems such as databases, queues, caches, or external services.

This package uses AES-GCM authenticated encryption with a random nonce prefixed to the ciphertext. It provides both raw byte-level APIs and convenience helpers that serialize arbitrary values with gob or JSON before encryption.

Security and caveats

  • Random-nonce message limit: each call generates a fresh 96-bit random nonce. With random nonces the number of messages that may safely be encrypted under a single key is bounded by the birthday paradox (see NIST SP 800-38D). Rotate keys well before ~2^32 messages per key to keep the nonce-collision probability negligible. A nonce collision under the same key breaks both confidentiality and authentication.
  • Nonce uniqueness depends entirely on the randomness source. Encrypt uses crypto/rand.Reader. Override it (via EncryptWith and WithRandReader) only in tests; a non-cryptographic or repeating reader causes nonce reuse.
  • The gob helpers (ByteEncryptAny/ByteDecryptAny and their string wrappers) decode with encoding/gob, which is not designed for adversarial input. Because the payload is authenticated before decoding, only data produced by a holder of the key ever reaches the decoder; even so, prefer the JSON family (the *SerializeAny helpers) for cross-language or lower-trust payloads.
  • The Base64 output uses standard encoding (RFC 4648 with ‘+’ and ‘/’), which is not URL- or filename-safe. Re-encode at the call site if you need to embed the payload in a URL or path.
  • All exported functions are stateless and safe for concurrent use.

When To Use

  • A field must be encrypted before it reaches the database or a queue.
  • You want authenticated encryption without assembling the pieces yourself.

Example

key := []byte("abcdefghijklmnopqrstuvwxyz012345") // 32 bytes: AES-256

enc, err := encrypt.Encrypt(key, []byte("secret message"))
if err != nil {
	log.Fatal(err)
}

dec, err := encrypt.Decrypt(key, enc)
if err != nil {
	log.Fatal(err)
}

fmt.Println(string(dec))

// Output:
// secret message

Full source is in example_encrypt_test.go. More runnable examples are on pkg.go.dev.

Dependencies

This package reaches no external module: it uses only the Go standard library.