How to generate an RSA key pair in Go

Generate an RSA public/private key pair in Go for RS256 JWT signing. Start with the browser RSA Key Generator for PEM output, or create keys with crypto/rsa + golang-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 Go, load those PEMs (or generate with crypto/rsa + golang-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

Go
import (
    "crypto/rand"
    "crypto/rsa"
    "crypto/x509"
    "encoding/pem"

    "github.com/golang-jwt/jwt/v5"
)

key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil { panic(err) }
privBytes, err := x509.MarshalPKCS8PrivateKey(key)
if err != nil { panic(err) }
privPEM := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privBytes})
pubBytes, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
if err != nil { panic(err) }
pubPEM := pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: pubBytes})

privateKey, err := jwt.ParseRSAPrivateKeyFromPEM(privPEM)
if err != nil { panic(err) }
token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{"sub": "user-1"})
tokenString, err := token.SignedString(privateKey)
if err != nil { panic(err) }
_ = pubPEM
_ = tokenString
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 Go?

Load the PEM private key to sign RS256 tokens and the PEM public key (or JWKS) to verify. With crypto/rsa + golang-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.