What is a Nonce

A nonce (number used once) is a value that must never be reused with the same key in a cryptographic operation. In symmetric encryption, the nonce ensures that encrypting the same plaintext twice with the same key produces different ciphertexts. In authentication protocols, nonces prevent replay attacks -- where an attacker records a valid message and retransmits it.

How it works

In AES-GCM, the most widely used authenticated encryption mode, the nonce is 96 bits (12 bytes). The sender generates a unique nonce for each message, encrypts the plaintext with the key and nonce, and transmits the nonce alongside the ciphertext. The receiver uses the same key and nonce to decrypt.

The critical rule: never reuse a nonce with the same key. In AES-GCM, nonce reuse is catastrophic. An attacker who observes two ciphertexts encrypted with the same key and nonce can XOR them together to cancel out the keystream, revealing the XOR of the two plaintexts. From there, recovering both plaintexts is often straightforward, and the authentication tag can be forged.

Nonces can be generated in two ways:

  • Counter-based -- start at 0 and increment for each message. Simple and guaranteed unique as long as the counter is never reset. This is the recommended approach for AES-GCM when a single sender controls the counter.
  • Random -- generate a random value for each message. Easier in distributed systems where coordinating a counter is impractical, but requires a large nonce space to avoid birthday collisions. With a 96-bit nonce, the collision probability becomes dangerous after roughly 2^32 messages under the same key.

ChaCha20-Poly1305, another common authenticated cipher, uses a 96-bit nonce with the same uniqueness requirement. XChaCha20 extends the nonce to 192 bits, making random nonce generation safe for virtually unlimited messages.

Why it matters

Nonce misuse is one of the most common and devastating implementation mistakes in cryptography. A single nonce reuse can compromise the confidentiality and integrity of all messages encrypted under that key. Understanding nonce management is essential for anyone implementing or configuring encryption.

See How Symmetric Encryption Works for the full walkthrough of block ciphers, modes of operation, and nonce management.