How to generate an RSA key pair in Node.js
Generate an RSA public/private key pair in Node.js for RS256 JWT signing. Start with the browser RSA Key Generator for PEM output, or create keys with crypto + jsonwebtoken, then sign with the private key and verify with the public key — never commit private keys to git.
Last updated August 26, 2026
Steps
- 1
Open the RSA Key Generator and create a 2048-bit (or 4096-bit) key pair in your browser.
- 2
Copy the PEM private and public keys — generation is client-side; nothing is sent to a server.
- 3
In Node.js, load those PEMs (or generate with crypto + jsonwebtoken) and sign a test JWT using RS256.
- 4
Verify the token with the public key and an explicit algorithms: ['RS256'] allowlist.
- 5
Store the private key in a secrets manager or HSM; publish only the public key (or JWKS) to verifiers.
Code Example
const { generateKeyPairSync } = require('crypto');
const jwt = require('jsonwebtoken');
const { privateKey, publicKey } = generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: { type: 'spki', format: 'pem' },
privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
});
// Or paste PEMs from the browser RSA Key Generator.
const token = jwt.sign({ sub: 'user-1' }, privateKey, { algorithm: 'RS256' });
const claims = jwt.verify(token, publicKey, { algorithms: ['RS256'] });Other languages
Related Articles
Frequently Asked Questions
Should I use 2048 or 4096-bit RSA for JWTs?
2048-bit is the standard for new RS256 deployments. Choose 4096-bit for long-lived roots or compliance mandates. Avoid 1024-bit keys.
How do I use generated RSA keys in Node.js?
Load the PEM private key to sign RS256 tokens and the PEM public key (or JWKS) to verify. With crypto + jsonwebtoken, always pin algorithms to RS256 so algorithm-confusion attacks fail.
Is browser RSA key generation safe?
Yes — keys are created with Web Crypto in your browser. Still treat the private key as secret: do not screenshot it into tickets or commit it.
When should I prefer RS256 over HS256?
Prefer RS256 when many services must verify tokens but only one should hold the signing key. HS256 is simpler when a single shared secret is acceptable.