How to generate an RSA key pair in Ruby

Generate an RSA public/private key pair in Ruby for RS256 JWT signing. Start with the browser RSA Key Generator for PEM output, or create keys with OpenSSL::PKey::RSA + ruby-jwt, 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 Ruby, load those PEMs (or generate with OpenSSL::PKey::RSA + ruby-jwt) 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

Ruby
require 'openssl'
require 'jwt'

key = OpenSSL::PKey::RSA.new(2048)
# Or OpenSSL::PKey.read(File.read('private.pem')) from the browser tool.

token = JWT.encode({ sub: 'user-1' }, key, 'RS256')
payload, = JWT.decode(token, key.public_key, true, { algorithm: 'RS256' })
puts payload
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 Ruby?

Load the PEM private key to sign RS256 tokens and the PEM public key (or JWKS) to verify. With OpenSSL::PKey::RSA + ruby-jwt, 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.