How to generate an RSA key pair in Java

Generate an RSA public/private key pair in Java for RS256 JWT signing. Start with the browser RSA Key Generator for PEM output, or create keys with KeyPairGenerator + java-jwt/jjwt, 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. 1

    Open the RSA Key Generator and create a 2048-bit (or 4096-bit) key pair in your browser.

  2. 2

    Copy the PEM private and public keys — generation is client-side; nothing is sent to a server.

  3. 3

    In Java, load those PEMs (or generate with KeyPairGenerator + java-jwt/jjwt) and sign a test JWT using RS256.

  4. 4

    Verify the token with the public key and an explicit algorithms: ['RS256'] allowlist.

  5. 5

    Store the private key in a secrets manager or HSM; publish only the public key (or JWKS) to verifiers.

Code Example

Java
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.util.Base64;

KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair pair = kpg.generateKeyPair();

// Prefer full PEM blocks from the browser RSA Key Generator for quick testing.
String privateB64 = Base64.getMimeEncoder(64, new byte[]{'\n'})
    .encodeToString(pair.getPrivate().getEncoded());
String publicB64 = Base64.getMimeEncoder(64, new byte[]{'\n'})
    .encodeToString(pair.getPublic().getEncoded());

// Sign/verify RS256 with java-jwt or jjwt using the private/public keys.
System.out.println("-----BEGIN PRIVATE KEY-----\n" + privateB64 + "\n-----END PRIVATE KEY-----");
System.out.println("-----BEGIN PUBLIC KEY-----\n" + publicB64 + "\n-----END PUBLIC KEY-----");
Open RSA Key Generator

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 Java?

Load the PEM private key to sign RS256 tokens and the PEM public key (or JWKS) to verify. With KeyPairGenerator + java-jwt/jjwt, 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.