Nonce Generator
Generate cryptographic nonces for secure one-time use in authentication and encryption.
What is a Nonce?
A nonce (number used once) is a random or pseudo-random number that should only be used once in cryptographic communication.
Common uses include preventing replay attacks, ensuring freshness in authentication protocols, and initialization vectors for encryption.
What Is a Nonce and Why Does It Matter?
A nonce — short for "number used once" — is a randomly generated value that plays a foundational role in modern cryptography and web security. The defining property of a nonce is that it must never be reused within the same security context. Once a nonce has been consumed in a protocol exchange, reusing it can expose secrets, allow replay attacks, or undermine the entire security guarantee that the nonce was designed to provide.
Nonces appear in an enormous range of security-critical scenarios. In TLS handshakes, client and server each contribute a random nonce to prevent an eavesdropper from reusing recorded traffic. In OAuth 2.0 and OpenID Connect, a nonce bound to the authentication request prevents token substitution attacks. In HTTP Content Security Policy (CSP), script nonces allow specific inline scripts to execute while blocking injected malicious code. In challenge-response authentication, the server issues a fresh nonce that the client must sign, proving possession of a secret without transmitting it.
The security of all these mechanisms depends directly on the unpredictability of the nonce. If an attacker can predict the next nonce, they can forge tokens, bypass CSP protections, or mount replay attacks. This is why nonces must be generated using a cryptographically secure pseudorandom number generator (CSPRNG) — not Math.random() or any other general-purpose random source. This calculator uses the browser's built-in crypto.getRandomValues() API, which draws from the operating system's CSPRNG and is suitable for security-sensitive applications.
Nonce length also matters. An 8-byte (64-bit) nonce provides approximately 1.8 × 1019 possible values — large enough for most applications, but a 32-byte (256-bit) nonce gives a astronomically larger space and is recommended for long-lived systems or high-volume token issuance where birthday-paradox collisions become a practical concern. As a rule of thumb, choose at least 16 bytes (128 bits) for general use and 32 bytes for high-security environments.
How This Nonce Generator Works
This nonce generator uses the Web Cryptography API's crypto.getRandomValues() function, which fills a typed array with cryptographically secure random bytes sourced from the operating system entropy pool. The raw bytes are then encoded into the chosen output format. No server requests are made — all generation happens locally in your browser, so nonces are never transmitted or logged.
The generator supports five output formats to match different integration requirements:
- Hexadecimal (hex): Each byte is converted to a two-character lowercase hex string (e.g., byte value 255 becomes "ff"). A 16-byte nonce produces a 32-character hex string. This is the most common format for tokens and session identifiers.
- Base64: The raw bytes are encoded using standard Base64 (RFC 4648). A 16-byte input produces a 24-character Base64 string (including padding "=" characters). This format is compact and widely supported in HTTP headers.
- Base64 URL: URL-safe Base64 replaces "+" with "-", "/" with "_", and strips padding "=" characters. This makes the nonce safe to embed directly in URLs and JWT headers without percent-encoding.
- Decimal: Each byte (0–255) is zero-padded to three digits and concatenated. A 16-byte nonce produces a 48-digit decimal string. This format is useful when only numeric characters are acceptable.
- UUID: The first 16 bytes are formatted as a UUID string (8-4-4-4-12 hex groups). Note that this tool generates random UUID-like strings from secure random bytes; the version and variant bits are not set per RFC 4122, so the output should not be treated as a standards-compliant UUID v4.
You can also enable a timestamp prefix. When enabled, the current Unix timestamp in milliseconds is converted to Base-36 (using Date.now().toString(36)) and prepended to the nonce with a hyphen separator. This makes nonces time-sortable and enables approximate issuance-time recovery without storing metadata separately — useful for token auditing and short-lived credential systems.
Nonce Output Length by Format
Where:
- n= Number of random bytes (8, 12, 16, 24, or 32)
- hex= Each byte → 2 lowercase hex characters via toString(16).padStart(2,'0')
- base64= Raw bytes → btoa(String.fromCharCode(...bytes))
- base64url= Base64 with '+' → '-', '/' → '_', '=' stripped
- decimal= Each byte → 3-digit decimal via toString().padStart(3,'0')
- uuid= 16 hex bytes formatted as xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
Output Length Reference Table
The output character count varies by both the byte length you select and the output format. Understanding the relationship helps you allocate the right amount of storage or column width in your database or configuration system. The table below shows the exact output length for each combination:
| Bytes | Hex (chars) | Base64 (chars) | Base64 URL (chars) | Decimal (chars) | UUID (chars) |
|---|---|---|---|---|---|
| 8 | 16 | 12 | 11 | 24 | 36 |
| 12 | 24 | 16 | 16 | 36 | 36 |
| 16 | 32 | 24 | 22 | 48 | 36 |
| 24 | 48 | 32 | 32 | 72 | 36 |
| 32 | 64 | 44 | 43 | 96 | 36 |
Note that the UUID format always produces 36 characters regardless of byte length, because it uses only the first 16 bytes and formats them in the fixed 8-4-4-4-12 hyphenated pattern. If you need variable-length output that scales with byte count, use hex, Base64, or decimal instead.
When designing a system that stores nonces (e.g., in a database for CSRF token validation or OAuth state parameter tracking), choose a column type wide enough for the largest format you might use. A VARCHAR(96) covers all formats up to 32 bytes, or use VARCHAR(128) for future headroom when the timestamp prefix is enabled.
Common Security Use Cases for Nonces
Understanding where nonces are used in practice helps you choose the right settings for your specific integration. Different protocols have different expectations for nonce format, length, and uniqueness guarantees.
Content Security Policy (CSP) Script Nonces
The CSP script-src 'nonce-...' directive allows inline scripts only when their nonce attribute matches the server-generated value in the CSP header. The nonce must be a fresh, cryptographically random value on every page load — never a static string. A 16-byte Base64 URL nonce (22 characters) is typical. Reusing a CSP nonce across requests defeats its purpose and exposes users to XSS attacks.
CSRF Protection Tokens
Cross-Site Request Forgery (CSRF) tokens are nonces tied to a user's session. The server embeds the token in a form or custom header, and the server validates that incoming requests carry the matching value. A 16–32 byte hex nonce stored server-side per session is the standard approach. The "double submit cookie" pattern uses the nonce both in a cookie and a form field, verifying they match without server-side storage.
OAuth 2.0 and OpenID Connect State Parameter
The state parameter in OAuth 2.0 authorization requests is a nonce the client generates, stores locally, and verifies upon callback. It prevents CSRF against the OAuth flow. A 16-byte Base64 URL nonce (22 characters) is the recommended format because it is URL-safe and compact enough for query parameters without percent-encoding.
Replay Attack Prevention in APIs
APIs that sign requests (HMAC-SHA256, AWS Signature v4, etc.) include a nonce and timestamp in the signed payload. The server caches seen nonces for a short window (e.g., 5 minutes) and rejects any request that presents a previously used nonce within that window, even if the signature is otherwise valid. A 12–16 byte hex or Base64 nonce provides sufficient uniqueness for high-throughput APIs without excessive storage overhead.
Encryption Initialization Vectors (IVs)
In symmetric encryption modes like AES-GCM, the 12-byte (96-bit) initialization vector must be unique per encryption operation with a given key. Generating a fresh random IV for every encrypt call using a CSPRNG — exactly what this generator does — is the standard practice recommended by NIST SP 800-38D. Reusing an IV with the same key in GCM mode can expose the authentication key and allow forgeries.
Best Practices for Nonce Generation and Management
Generating a cryptographically strong nonce is only half the battle. How you store, transmit, validate, and expire nonces determines whether your system is actually secure. The following best practices cover the full lifecycle of a nonce from generation to retirement.
Always use a CSPRNG. General-purpose random functions like JavaScript's Math.random(), Python's random.random(), or PHP's rand() are not cryptographically secure. They may be seeded with predictable values or have internal state that an attacker can reconstruct. Always use crypto.getRandomValues() in browsers, crypto.randomBytes() in Node.js, secrets.token_bytes() in Python, or the equivalent OS-level secure random source.
Match nonce length to your threat model. For most web application use cases (CSRF tokens, CSP nonces, OAuth state), 16 bytes (128 bits) provides an astronomically small collision probability even under heavy load. For high-security applications, cryptographic keys, or long-lived tokens, prefer 32 bytes (256 bits). Shorter nonces (8 bytes / 64 bits) may be acceptable for short-lived, low-value tokens where storage is constrained.
Enforce single use. A nonce that can be reused is not a nonce — it is a static token. Implement server-side tracking of consumed nonces within the validity window. For short-lived nonces (under 5 minutes), a Redis set or in-memory cache with TTL expiry is efficient. For long-lived nonces (session tokens, invitation links), a database column with a "used" flag or deletion on consumption is appropriate.
Set expiration times. Nonces should expire after a reasonable window. CSRF nonces typically expire with the session. One-time invitation link nonces should expire after 24–72 hours. CSP nonces expire with the page response. Never issue nonces that are valid indefinitely — this creates a growing attack surface as the list of valid nonces grows.
Transmit nonces over encrypted channels only. A nonce intercepted in transit can be replayed by the interceptor. Always use HTTPS/TLS when transmitting nonces in headers, cookies, or request bodies. Set the Secure flag on cookies that carry nonce values to prevent transmission over plain HTTP.
Do not log nonces verbatim in application logs. Application logs are often shipped to monitoring systems, stored long-term, and accessible to more personnel than security tokens should be. Hash nonces (SHA-256) before logging if you need audit trails, so that the log entry cannot be replayed even if the log is compromised.
Worked Examples
16-Byte Hex Nonce for CSRF Token
Problem:
Generate a CSRF token for a web form using 16 bytes in hexadecimal format, without a timestamp prefix.
Solution Steps:
- 1Select 16 bytes as the nonce length. This gives 128 bits of entropy — the standard recommendation for CSRF tokens.
- 2Select the Hexadecimal (hex) format. Each of the 16 random bytes is converted to two lowercase hex digits via toString(16).padStart(2,'0'), producing a 32-character string.
- 3Leave the timestamp prefix disabled. CSRF tokens do not need to encode issuance time; they just need to be unique and unpredictable.
- 4Click 'Generate Nonce'. The output is a 32-character string such as 'a3f7c2e1b8490d56f3a2c7e4d1b09823'. Embed this in your form as a hidden input and in the user's session for server-side verification.
Result:
A 32-character hex string (e.g., a3f7c2e1b8490d56f3a2c7e4d1b09823) suitable for use as a CSRF token. 16 bytes × 2 hex chars/byte = 32 characters total.
12-Byte Base64 URL Nonce for OAuth State Parameter
Problem:
Generate a URL-safe nonce for the OAuth 2.0 state parameter that will be embedded in a redirect URL without percent-encoding.
Solution Steps:
- 1Select 12 bytes as the nonce length. Twelve bytes give 96 bits of entropy — sufficient for OAuth state parameters with a short expiry.
- 2Select Base64 URL format. The 12 raw bytes are first Base64-encoded (btoa), then '+' is replaced with '-', '/' with '_', and trailing '=' padding is stripped. Twelve bytes encode to exactly 16 Base64 URL characters.
- 3Leave the timestamp prefix disabled for a clean URL-safe token.
- 4Click 'Generate Nonce'. Append the result as ?state=<nonce> in your OAuth authorization URL. Store the nonce locally (sessionStorage or server session) and verify it matches when the authorization server returns the user.
Result:
A 16-character Base64 URL string (e.g., 'xK3mQpL7nWrT4Yvc') safe for direct use in URLs. 12 bytes × (4/3) = 16 Base64 characters (no padding needed since 12 is a multiple of 3).
32-Byte Hex Nonce with Timestamp for Audit Logging
Problem:
Generate a high-entropy nonce for a one-time download link that also encodes approximate issuance time for audit purposes.
Solution Steps:
- 1Select 32 bytes as the nonce length. Thirty-two bytes provide 256 bits of entropy — appropriate for high-security one-time tokens.
- 2Select Hexadecimal format. Each of the 32 bytes becomes two hex characters, giving a 64-character base token.
- 3Enable 'Include Timestamp Prefix'. The current Unix timestamp in milliseconds is converted to Base-36 (e.g., Date.now().toString(36) at a recent timestamp produces a string like 'lhk2q4p') and prepended with a hyphen.
- 4Click 'Generate Nonce'. The final token looks like 'lhk2q4p-a3f7c2e1b8490d56f3a2c7e4d1b09823...' (7–9 char Base-36 timestamp + '-' + 64 hex chars). Store this as the download token in your database with a 24-hour expiry.
Result:
A timestamped token approximately 73–75 characters long. The Base-36 prefix lets you decode the approximate issuance time as parseInt(prefix, 36) milliseconds since epoch, without querying the database.
8-Byte Nonce for AES-GCM IV (Illustrative)
Problem:
Understand how a 12-byte random nonce would serve as an AES-GCM initialization vector in a Node.js application.
Solution Steps:
- 1Select 12 bytes as the nonce length. AES-GCM uses a 96-bit (12-byte) IV — the exact size recommended by NIST SP 800-38D for random IV generation.
- 2Select Base64 format for easy storage alongside the ciphertext. Twelve bytes produce a 16-character Base64 string.
- 3Generate the nonce and convert it back to raw bytes on the server: Buffer.from(nonce, 'base64'). Pass these bytes as the IV to crypto.createCipheriv('aes-256-gcm', key, iv).
- 4Store the Base64 nonce alongside the ciphertext. When decrypting, retrieve the nonce, decode it, and pass it as the IV to createDecipheriv. Never reuse the same nonce with the same AES-GCM key.
Result:
A 16-character Base64 string representing 12 cryptographically random bytes, suitable for use as an AES-GCM initialization vector. One fresh nonce must be generated per encryption operation.
Tips & Best Practices
- ✓Use at least 16 bytes (128 bits) for any nonce used in a web security context — CSRF tokens, OAuth state, CSP nonces, or API replay prevention.
- ✓Always generate a fresh nonce per request or page load; never store and reuse a nonce across multiple operations.
- ✓Choose Base64 URL format when the nonce will appear in a URL query parameter, JWT header, or cookie, to avoid percent-encoding and character set issues.
- ✓Choose Hexadecimal format when the nonce will be stored in a database or compared server-side — it is human-readable, lowercase-safe, and widely supported.
- ✓Enable the timestamp prefix when building one-time invitation links or download tokens to recover approximate issuance time without an extra database column.
- ✓Set expiry times on all nonces: use Redis TTL for short-lived tokens (under 15 minutes) and a database expiry column for longer-lived one-time links.
- ✓Never log raw nonce values in application logs; hash them with SHA-256 first so that log access does not enable replay attacks.
- ✓For AES-GCM encryption, always use a fresh 12-byte random IV per encryption operation — reusing an IV with the same key breaks GCM's authentication guarantee.
- ✓Use the quantity slider to generate a batch of nonces (up to 20) at once for pre-seeding a token pool or testing your validation logic with multiple values.
- ✓Test your nonce validation logic by generating several nonces and verifying that your server correctly accepts the first use and rejects any repeated submission.
Frequently Asked Questions
Sources & References
- Web Cryptography API — MDN Web Docs (2024)
- NIST SP 800-38D: Recommendation for Block Cipher Modes of Operation — Galois/Counter Mode (GCM) (2007)
- RFC 5905 — Network Time Protocol (Nonce Usage in Time Synchronization) (2010)
- Content Security Policy Level 3 — W3C Specification (Script Nonces) (2023)
- RFC 6749 — The OAuth 2.0 Authorization Framework (State Parameter) (2012)
Last updated: 2026-06-05
Help us improve!
How would you rate the Nonce Generator?
Editorial Note
MyCalcBuddy Editorial Team
This page is maintained as an educational calculator reference.
Formula Source: Standard Mathematical References
by Various