Generate RSA Keys with Web Crypto API

Learn how to generate RSA key pairs directly in the browser using the Web Crypto API. See code examples for key generation, export to PEM, signing, and encryption.

Use Cases

Detailed Explanation

Generate RSA Keys with Web Crypto API

The Web Crypto API provides a native, standards-based way to generate RSA key pairs directly in the browser. No libraries or server-side processing are required — keys are generated entirely on the client side.

Basic Key Generation

// Generate an RSA-OAEP key pair for encryption
const keyPair = await window.crypto.subtle.generateKey(
  {
    name: "RSA-OAEP",
    modulusLength: 2048,
    publicExponent: new Uint8Array([1, 0, 1]), // 65537
    hash: "SHA-256",
  },
  true,       // extractable — allows exporting the key
  ["encrypt", "decrypt"]
);

Algorithm Options

The Web Crypto API supports three RSA algorithms:

Algorithm Purpose Key Usages
RSA-OAEP Encryption/decryption encrypt, decrypt, wrapKey, unwrapKey
RSASSA-PKCS1-v1_5 Digital signatures sign, verify
RSA-PSS Digital signatures (preferred) sign, verify

Exporting Keys to PEM

async function exportToPem(key, type) {
  const format = type === "private" ? "pkcs8" : "spki";
  const exported = await crypto.subtle.exportKey(format, key);
  const b64 = btoa(String.fromCharCode(...new Uint8Array(exported)));
  const lines = b64.match(/.{1,64}/g).join("\n");
  const label = type === "private" ? "PRIVATE KEY" : "PUBLIC KEY";
  return `-----BEGIN ${label}-----\n${lines}\n-----END ${label}-----`;
}

const privatePem = await exportToPem(keyPair.privateKey, "private");
const publicPem = await exportToPem(keyPair.publicKey, "public");

Signing with Web Crypto

const encoder = new TextEncoder();
const data = encoder.encode("Message to sign");

const signature = await crypto.subtle.sign(
  { name: "RSA-PSS", saltLength: 32 },
  keyPair.privateKey,
  data
);

const isValid = await crypto.subtle.verify(
  { name: "RSA-PSS", saltLength: 32 },
  keyPair.publicKey,
  signature,
  data
);

Browser Support

The Web Crypto API is supported in all modern browsers (Chrome, Firefox, Safari, Edge) and in Node.js. RSA key generation of 2048-bit and 4096-bit is universally supported. The extractable flag must be true to export keys.

Security Note

Keys generated with Web Crypto never leave the browser unless you explicitly export them. This makes it ideal for privacy-sensitive applications where users should generate and control their own keys.

Use Case

Web developers use the Web Crypto API to build client-side encryption tools, browser-based key generators, end-to-end encrypted messaging apps, and local JWT signing utilities. Since all operations happen in the browser, it is perfect for tools like DevToolbox that prioritize client-side privacy.

Try It — RSA Key Pair Generator

Open full tool