A nonce (number used once) is a unique value that is generated for a single use in a cryptographic or security context. Nonces ensure that previous communications cannot be replayed, that requests are fresh, and that specific operations can only be performed once.
How It Works
Nonces serve different purposes depending on where they are applied. In cryptographic protocols, a nonce is combined with a key during encryption to ensure that encrypting the same plaintext twice produces different ciphertext. Without a nonce, identical messages encrypted with the same key would produce identical output, leaking information about the plaintext.
In web security, nonces appear most prominently in Content Security Policy (CSP). A CSP nonce is a randomly generated value included in both the CSP header and the nonce attribute of allowed <script> tags. The browser only executes scripts whose nonce matches the one declared in the policy. Since the nonce changes with every page load, an attacker who injects a script tag cannot predict the required nonce value, preventing cross-site scripting even when inline scripts are necessary.
Anti-CSRF tokens function as nonces. The server generates a unique token for each form or session, embeds it in the page, and validates it when the form is submitted. Since an attacker on a different origin cannot read the token, they cannot forge a valid request. Each token is used once or bound to a specific session, preventing replay.
Authentication protocols use nonces to prevent replay attacks. The server sends a challenge nonce, and the client must include it in their authentication response. Since each nonce is unique and time-limited, an intercepted response cannot be replayed in a future authentication attempt.
Requirements
Nonces must be generated using cryptographically secure random number generators. Predictable nonces undermine every security mechanism that depends on them. They must also be validated server-side and rejected if reused, expired, or malformed.
Why It Matters
Nonces are a deceptively simple concept that underpins the security of encryption, authentication, and cross-site request protection. When nonce generation is weak or validation is missing, the mechanisms they protect become vulnerable to replay, injection, and forgery attacks.
Need your application tested? Get in touch.