Skip to content
uencoder
TASK

Generate cryptographic nonces correctly

A nonce (number used once) must be unique per encryption under the same key. Learn when to use random vs counter nonces and the consequences of reuse.

  1. 1

    A nonce must never repeat under the same key. Two approaches: (1) random nonce — generate 96 bits from a CSPRNG, collision probability is negligible with a 96-bit space; (2) counter nonce — maintain a monotonic counter, guaranteed unique but requires persistent state. Random is simpler; counter is deterministic.

  2. 2
    Random Bytes Generator →

    Generate a 96-bit (12-byte) random nonce. This is the standard size for AES-GCM. With 96 bits, the probability of collision after 2^32 encryptions is less than 2^-32 (birthday bound) — safe for most applications.

  3. 3
    Hash Calculator →

    If you need a deterministic nonce from a message identifier, use a hash: nonce = H(message_id). This is useful when the same message must produce the same ciphertext (deterministic encryption), but be careful — it reveals if two messages are identical.

  4. 4

    Never use: timestamps (can repeat on fast machines), Math.random() (not cryptographic), a hardcoded constant, or a counter that wraps around. For AES-GCM specifically, 96-bit nonces are optimal — other sizes require additional processing and may weaken security.

Frequently asked questions

Random or counter nonce?
Random is simpler and stateless — use it for most applications. Counter is deterministic and avoids birthday-bound concerns, but requires persistent state and fails if the counter resets (e.g., server restart). For AES-GCM, NIST recommends 96-bit random nonces.
What if I accidentally reuse a nonce?
For GCM, nonce reuse is catastrophic — it leaks the authentication key and allows forgery. For CTR, it leaks the XOR of two plaintexts. If you suspect reuse, immediately rotate the encryption key and re-encrypt all data with new nonces.

Workflows that solve this

Learn more

Want to understand why?

Related tools