Home › Developer Tools › PKCE Code Challenge Generator

PKCE Code Challenge Generator

Create a cryptographically random PKCE code_verifier and its S256 code_challenge with the Web Crypto API, exactly as RFC 7636 specifies. Build a ready authorization URL and token request for testing, or check that an existing verifier and challenge belong together.

Last updated:

Authorization URL & token request builder
1. Authorization request (open in the browser)

    
2. Token request (replace AUTHORIZATION_CODE)

  

Verify a pair

Advertisement
Advertisement

How to use the PKCE Code Challenge Generator

  1. Click Generate New Pair (a pair is ready when the page loads). Adjust the verifier length if needed.
  2. Copy the code_challenge and send it with code_challenge_method=S256 in the authorization request, or use the URL builder.
  3. Store the code_verifier securely in your app (memory or session storage) until the user returns with an authorization code.
  4. Exchange the code: send the code_verifier in the token request (see the curl example).
  5. Debugging? Paste a verifier and a challenge into Verify a pair to see whether they match.

How the PKCE flow works

  1. Create the verifier. The client generates a high-entropy random code_verifier (43-128 characters from A-Z a-z 0-9 - . _ ~) and keeps it secret.
  2. Derive the challenge. code_challenge = BASE64URL(SHA256(code_verifier)), Base64URL without = padding.
  3. Authorization request. The client redirects the user to the authorization server with code_challenge and code_challenge_method=S256. The server stores the challenge with the authorization code it issues.
  4. Token request. The client sends the authorization code together with the original code_verifier.
  5. Check. The server hashes the verifier and compares it with the stored challenge. Only the client that started the flow can complete it.

Test vector from RFC 7636 (Appendix B)

code_verifierdBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
code_challenge (S256)E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM

Click Load RFC 7636 Example to reproduce it with this tool. If your own code gives a different result, the usual culprits are standard Base64 instead of Base64URL, leftover = padding, hashing the hex string of the digest, or hashing a string that contains a trailing newline.

Generating PKCE in code

JavaScript (browser or Node 18+):

const b64url = b => btoa(String.fromCharCode(...new Uint8Array(b)))
  .replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
const verifier = b64url(crypto.getRandomValues(new Uint8Array(32)));
const challenge = b64url(await crypto.subtle.digest('SHA-256',
  new TextEncoder().encode(verifier)));

Python:

import base64, hashlib, secrets
verifier = secrets.token_urlsafe(32)  # 43 characters
challenge = base64.urlsafe_b64encode(
    hashlib.sha256(verifier.encode('ascii')).digest()).rstrip(b'=').decode()

Frequently asked questions

What is PKCE?

PKCE (Proof Key for Code Exchange, pronounced "pixy") is an OAuth 2.0 extension defined in RFC 7636. The client creates a secret code_verifier, sends only its hash (the code_challenge) with the authorization request, and later proves it started the flow by sending the verifier with the token request. An attacker who intercepts the authorization code cannot use it without the verifier.

How is the S256 code challenge calculated?

code_challenge = BASE64URL-ENCODE(SHA256(ASCII(code_verifier))). The SHA-256 digest of the verifier's ASCII bytes is Base64URL encoded: + becomes -, / becomes _, and the trailing = padding is removed. A SHA-256 challenge is therefore always 43 characters long.

What are the rules for a code_verifier?

It must be 43 to 128 characters long and use only the unreserved characters A-Z, a-z, 0-9, hyphen, period, underscore and tilde. RFC 7636 recommends generating 32 random bytes and Base64URL encoding them, which gives a 43-character verifier with 256 bits of entropy.

Should I use S256 or plain?

Always use S256 when the client can compute SHA-256, which every modern platform can. With plain, the challenge equals the verifier, so anyone who sees the authorization request also learns the verifier. OAuth 2.1 and many providers require S256.

Do I still need a state parameter with PKCE?

PKCE protects against authorization code interception and also prevents CSRF when the server enforces it, but many providers and libraries still expect a state value, and it is useful for carrying app context. Using both is the common recommendation.

Is PKCE only for mobile and single-page apps?

No. PKCE was designed for public clients such as mobile and browser apps that cannot keep a client secret, but the OAuth 2.0 Security Best Current Practice (RFC 9700) recommends it for confidential server-side clients too, and OAuth 2.1 makes it required for the authorization code flow.

Is it safe to generate a code_verifier on a website?

This page creates values locally with the browser's cryptographic random generator and never transmits them. For production, though, your application should generate a fresh verifier for every login; use this tool for learning, testing and debugging.

Are all the tools on FreeToolCabin tested for quality and accuracy?

Yes! Every tool on our site undergoes automated Q/A testing in real browser environments to ensure high precision, correct output, and zero errors. If you happen to spot a bug or have a suggestion, please contact us at [email protected] and our team will review it right away.

Related tools

JWT DecoderDecode JSON Web Tokens, read the claims and expiry, and verify HS256 signatures.JWT GeneratorCreate and sign HS256, HS384 or HS512 JSON Web Tokens in your browser and verify them.SHA-256 Hash GeneratorSHA-256 and HMAC-SHA256 hashes of text, lines or files, in hex or Base64.Random String GeneratorGenerate secure random strings and tokens in bulk with any length and character set.QR Code GeneratorMake QR codes for links, Wi-Fi, email and more.Barcode GeneratorCreate Code 128, EAN-13, UPC-A, EAN-8, Code 39 and ITF-14 barcodes as PNG or SVG.UUID GeneratorGenerate UUID v4 and v7 / GUIDs in bulk and copy or download them.Schema Markup Generator (JSON-LD)Create JSON-LD structured data for FAQ, Product, Article and more.Htaccess & Nginx Redirect GeneratorBuild 301 redirects for .htaccess, Nginx and Netlify or Cloudflare _redirects.Fake Data GeneratorGenerate mock data as JSON, CSV or SQL.API Key GeneratorCreate secure API keys and secrets with prefixes, checksums and SHA-256 hashes for storage.MIME Type LookupFind the MIME type for any file extension, or the extensions for a MIME type, in 400+ entries.Cron Expression GeneratorBuild crontab schedules visually, read them in plain English and see the next run times.URL Slug GeneratorTurn titles into clean, SEO-friendly URL slugs: accents, stop words, separators and bulk lines.JSON Schema GeneratorTurn sample JSON into a draft 2020-12 JSON Schema with types, required fields and formats.Gitignore GeneratorBuild a .gitignore from 50+ templates for languages, frameworks, IDEs and OS, merged and deduped.License GeneratorCreate a LICENSE file for MIT, Apache, GPL, BSD, ISC, MPL or Unlicense with your name and year.ULID GeneratorGenerate sortable ULIDs and UUID v7 in bulk, monotonic option, and decode their timestamps.Htpasswd GeneratorCreate .htpasswd entries with bcrypt, APR1-MD5 or SHA-1 for Apache and Nginx basic auth.Placeholder Image GeneratorCreate placeholder images in any size, color and text as PNG, JPG, WebP, SVG or data URI.Ads.txt GeneratorCreate or validate ads.txt and app-ads.txt files: seller lines, cert IDs and variables.Docker Run to Compose ConverterConvert docker run commands to docker-compose.yml, or a compose file back to docker run.Dockerfile GeneratorGenerate a production Dockerfile and .dockerignore for Node, Python, Go or a static nginx site.HTML Boilerplate GeneratorTick the options you need and get a clean HTML5 starter template with meta, OG tags and CSS reset.JSON to Zod SchemaInfer a Zod (or Yup) schema from sample JSON with optional, nullable and z.infer types.Linux Commands Cheat SheetSearchable Linux and bash command reference with flags explained, examples and copy buttons.LLMs.txt GeneratorBuild an llms.txt file for AI crawlers: summary and link sections, import from your sitemap.Nano ID GeneratorGenerate secure Nano IDs with custom alphabet, length and count, plus a collision calculator.Nginx Config GeneratorBuild an nginx server block: static site, SPA, reverse proxy or PHP, with SSL, gzip and redirects.OpenAPI / Swagger ViewerView OpenAPI 2/3 JSON or YAML as interactive API docs with validation and an endpoint list.package.json GeneratorFill a form and get a valid, npm-ready package.json with scripts, dependencies and checks.README GeneratorFill in a form and get a polished README.md with badges, install, usage and license, live preview.Regex GeneratorBuild regular expressions visually from blocks or presets (email, date, phone) and test them live.Commit Message GeneratorBuild Conventional Commit messages with type, scope, body, breaking change and issue refs.Database Schema DesignerDesign tables and relationships visually, then export SQL for MySQL, PostgreSQL or SQLite.Docker Compose GeneratorBuild a docker-compose.yml with a form: services, ports, volumes, env, healthchecks and presets.Dummy File GeneratorCreate test files of an exact size in KB, MB or GB with zeros, random bytes or text.FFmpeg Command GeneratorPick a task and options, get the exact ffmpeg command with every flag explained.OpenAPI EditorEdit OpenAPI/Swagger YAML or JSON side by side with live API docs, validation and download.OpenAPI ValidatorValidate OpenAPI 3.0/3.1 and Swagger 2.0 specs: schema errors, broken $refs, line numbers.Pivot Table MakerBuild pivot tables from CSV or Excel by drag and drop: sum, count, average, charts, export.SQL Query BuilderBuild SELECT queries visually: joins, filters, GROUP BY, ORDER BY and LIMIT, as clean SQL.Truth Table GeneratorType a logic expression and get its full truth table, minterms and canonical DNF/CNF.TypeScript PlaygroundWrite TypeScript with live type checking, see the compiled JavaScript and run it in your browser.Article Schema GeneratorCreate Article, BlogPosting or NewsArticle JSON-LD with headline, authors, dates and images.Event Schema GeneratorCreate Event JSON-LD with dates, venue or online location, tickets, organizer and performers.Google Search Query BuilderBuild advanced Google searches with site:, filetype:, intitle:, exact phrases and date operators.HowTo Schema GeneratorCreate HowTo JSON-LD with steps, tools, supplies, total time and cost, then copy it.Htaccess GeneratorBuild an Apache .htaccess file: HTTPS, www, gzip, caching, error pages, IP blocks, hotlinks.HTML Email Template BuilderDrag and drop blocks to build a responsive, table-based HTML email with inline styles.Organization Schema GeneratorCreate Organization JSON-LD with logo, URL, contact points, address and social profiles.PIN GeneratorGenerate random 4, 6 or 8-digit PINs that avoid sequences, repeats, dates and common PINs.Product Schema GeneratorBuild Product JSON-LD with price, availability, brand, GTIN, ratings and reviews.Question Keyword GeneratorFind the questions people ask about a topic, grouped by who, what, why, how, can and more.Recipe Schema GeneratorCreate Recipe JSON-LD with ingredients, steps, prep and cook times, nutrition and ratings.Security Headers GeneratorPick HSTS, CSP, frame, referrer and permissions options and get Apache, Nginx, Netlify or Cloudflare config.SKU GeneratorBuild consistent SKUs from brand, category, size and color, then export every variant as CSV.Typography Scale GeneratorBuild a modular type scale from a base size and ratio, then copy CSS variables or a Tailwind config.WordPress Salt GeneratorGenerate fresh WordPress security keys and salts for wp-config.php, .env or Docker in one click.ANSI Color Code GeneratorStyle terminal text with 16, 256 or RGB colors and get escape codes for bash, Python, JS and C.Apache Virtual Host GeneratorCreate an Apache VirtualHost config with SSL, redirects, reverse proxy or PHP-FPM in seconds.Bash Prompt GeneratorDrag and drop a custom PS1 prompt for bash or zsh with colors, git branch and a live preview.Changelog GeneratorTurn Conventional Commit messages into a grouped Keep a Changelog Markdown file per version.cURL Command BuilderBuild curl commands from a form: method, headers, query, JSON or form body, auth and flags.Docker Compose to KubernetesConvert docker-compose.yml into Kubernetes Deployment, Service, ConfigMap and PVC manifests.Docker Compose ValidatorCheck a docker-compose.yml for YAML errors, schema mistakes, broken references and deprecated keys.Dockerfile LinterLint a Dockerfile for best practices: pinned tags, apt cleanup, non-root USER and layer count.Dockerignore GeneratorBuild a .dockerignore from Node, Python, Go and Java templates, plus your own entries.
See all 85 Code Generators & Builders →