Difficulty: Intermediate
What is a nonce, where is it used, and how is it different from a salt and an IV?
A nonce is a 'number used once': a value that must not repeat within a given context. Its job is to make each message, request or operation unique so that an attacker cannot replay an old one or exploit a repeated value. Depending on the protocol a nonce may be random, sequential or a timestamp, but the one non-negotiable rule is uniqueness for the key or session it is tied to.
The main threat is the replay attack: an attacker captures a valid, authenticated message and sends it again later to repeat its effect, for example re-submitting a 'transfer 5000 rupees' request. If every request carries a fresh nonce that the server records and rejects on reuse, the replayed copy is dropped because its nonce has already been seen.
nonce in the CSP header and the same value on each trusted <script> tag. The browser runs only scripts whose nonce matches, which blocks injected inline scripts. A new nonce is generated per response, so it is unguessable.nonce to bind an ID token to a specific login request and stop token replay. HTTP Digest auth uses a server nonce.These three are often confused because all add variation, but they serve different goals.
| Value | Purpose | Must be unique? | Secret? |
|---|---|---|---|
| Nonce | Prevent replay and repetition per operation | Yes, per key/session | Not necessarily |
| Salt | Make identical passwords hash differently | Yes, per password | No, stored with the hash |
| IV | Randomise the start of a cipher so equal plaintexts differ | Yes, and for CBC unpredictable | No, sent with the ciphertext |
A salt defends against precomputation and rainbow tables on password hashes. An IV ensures encrypting the same plaintext twice gives different ciphertext. A nonce ensures a message or request is fresh. None of them needs to be secret; what matters is that they do not repeat.
import crypto from 'node:crypto';
app.use((req, res, next) => {
// fresh, unguessable value for each response
res.locals.nonce = crypto.randomBytes(16).toString('base64');
res.setHeader(
'Content-Security-Policy',
`script-src 'self' 'nonce-${res.locals.nonce}'`
);
next();
});
// in the template, only tagged scripts run
// <script nonce="<%= nonce %>">...</script>
A new random nonce per response means an attacker who injects an inline script cannot guess the valid nonce, so the browser refuses to execute the injected script.
Nonce, Replay Protection, CSP, Initialization Vector, Cryptography