RSA Encryption in Java: Key Pairs, Encrypt/Decrypt & Digital Signatures
RSA uses a key pair: anything encrypted with the public key can only be decrypted with the private key, and a signature made with the private key can be checked by anyone with the public key. That removes the need to share a secret in advance, at the cost of being slow and limited to small inputs.
Contents
How RSA works
RSA (Rivest, Shamir and Adleman, 1977) is a public-key algorithm: a key pair has a public half that anyone may have and a private half that only its owner keeps. Its security rests on factoring: the public key contains a modulus n = p × qpqnede × d = 1(p-1)(q-1)c = me mod nm = cd mod n
Raw RSA has serious weaknesses, shown below, so real RSA always adds a padding scheme: OAEP for encryption, and PKCS#1 v1.5 or PSS for signatures. Each key pair has two halves, used in opposite directions:
| Operation | Key | Purpose |
|---|---|---|
| Encrypt | Recipient's public key | Only the recipient can read it |
| Decrypt | Recipient's private key | Recover the data |
| Sign | Signer's private key | Prove who produced the data |
| Verify | Signer's public key | Anyone can check the signature |
| Algorithm | Since | Use |
|---|---|---|
| RSA with OAEP, PKCS#1 v1.5 signatures | Java 1.2 to 5 | Encryption and signatures; the most widely supported |
| RSASSA-PSS | Java 11 | Modern RSA signatures |
| ECDSA (for example P-256) | Java 7 | Signatures with small keys, as in TLS certificates |
| Ed25519, Ed448 | Java 15 (JEP 339) | Fast, simple signatures |
| ML-KEM, ML-DSA (post-quantum) | Java 24 (JEP 496, 497) | Key exchange and signatures safe against quantum computers |
All programs use only the JDK and were run on JDK 21.
RSA arithmetic by hand, and why padding is needed
With tiny primes, the whole algorithm fits in a few BigInteger
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPublicKey;
public class TextbookRsa {
public static void main(String[] args) throws Exception {
// Tiny numbers to see the arithmetic: n = p * q, e * d = 1 mod (p-1)(q-1)
BigInteger p = BigInteger.valueOf(61);
BigInteger q = BigInteger.valueOf(53);
BigInteger n = p.multiply(q);
BigInteger phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
BigInteger e = BigInteger.valueOf(17);
BigInteger d = e.modInverse(phi);
System.out.println("p=61, q=53 -> n=" + n + ", phi=" + phi + ", e=17, d=" + d);
BigInteger m = BigInteger.valueOf(65);
BigInteger c = m.modPow(e, n);
System.out.println("encrypt 65: 65^17 mod 3233 = " + c + "; decrypt: " + c + "^" + d
+ " mod 3233 = " + c.modPow(d, n));
System.out.println("encrypt 65 again: " + m.modPow(e, n)
+ " (textbook RSA is deterministic)");
// Malleable: multiplying ciphertexts multiplies the hidden plaintexts
BigInteger c2 = BigInteger.valueOf(2).modPow(e, n);
BigInteger product = c.multiply(c2).mod(n);
System.out.println("E(65) * E(2) decrypts to " + product.modPow(d, n) + " = 65 * 2");
// A real key: the same structure, with 3072-bit numbers
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(3072);
KeyPair kp = kpg.generateKeyPair();
RSAPublicKey pub = (RSAPublicKey) kp.getPublic();
RSAPrivateCrtKey priv = (RSAPrivateCrtKey) kp.getPrivate();
System.out.println("real key: modulus " + pub.getModulus().bitLength() + " bits, e = "
+ pub.getPublicExponent() + ", primes of " + priv.getPrimeP().bitLength()
+ " and " + priv.getPrimeQ().bitLength() + " bits");
System.out.println("p * q == n: " + priv.getPrimeP().multiply(priv.getPrimeQ())
.equals(pub.getModulus()) + ", e * d = 1 mod (p - 1): " + pub.getPublicExponent()
.multiply(priv.getPrivateExponent()).mod(priv.getPrimeP()
.subtract(BigInteger.ONE)).equals(BigInteger.ONE));
}
}
Output:
p=61, q=53 -> n=3233, phi=3120, e=17, d=2753
encrypt 65: 65^17 mod 3233 = 2790; decrypt: 2790^2753 mod 3233 = 65
encrypt 65 again: 2790 (textbook RSA is deterministic)
E(65) * E(2) decrypts to 130 = 65 * 2
real key: modulus 3072 bits, e = 65537, primes of 1536 and 1536 bits
p * q == n: true, e * d = 1 mod (p - 1): true
found d = 2753, and 6517 mod 3233 = 2790 decrypted back to 65 with that d.modInverse- Encrypting 65 twice gave 2790 both times. Raw RSA is deterministic, so an attacker can encrypt guesses such as "yes" and "no" with the public key and compare.
- Multiplying two ciphertexts gave a valid ciphertext of the product, 130 = 65 × 2. An attacker can change an encrypted value without decrypting it. OAEP's random padding removes both problems.
- The generated key has a 3072-bit modulus made of two 1536-bit primes and e = 65537, and the same identities hold. The JDK stores private keys in CRT form, with p, q and some precomputed values, which makes decryption and signing about four times faster.
Encrypting with RSA-OAEP
The program generates a 3072-bit key pair, sends the public half through its standard X.509 encoding (as it would travel to another system) and encrypts with OAEP padding using SHA-256. It then probes the size limit.
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PublicKey;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.spec.OAEPParameterSpec;
import javax.crypto.spec.PSource;
public class RsaOaep {
static final String TRANSFORMATION = "RSA/ECB/OAEPPadding"; // "ECB" is just a name here
static final OAEPParameterSpec OAEP_SHA256 = new OAEPParameterSpec("SHA-256", "MGF1",
MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT);
public static void main(String[] args) throws Exception {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(3072);
KeyPair pair = kpg.generateKeyPair();
// Public keys are shared as X.509 (SubjectPublicKeyInfo) bytes
byte[] encodedPublic = pair.getPublic().getEncoded();
System.out.println("public key format " + pair.getPublic().getFormat() + ", "
+ encodedPublic.length + " bytes; private key format "
+ pair.getPrivate().getFormat());
PublicKey received = KeyFactory.getInstance("RSA")
.generatePublic(new X509EncodedKeySpec(encodedPublic));
Cipher enc = Cipher.getInstance(TRANSFORMATION);
enc.init(Cipher.ENCRYPT_MODE, received, OAEP_SHA256);
byte[] secret = "session key or other small secret".getBytes(StandardCharsets.UTF_8);
byte[] c1 = enc.doFinal(secret);
byte[] c2 = enc.doFinal(secret);
System.out.println("ciphertext size: " + c1.length + " bytes (the key size)");
System.out.println("same input encrypted twice is identical: " + Arrays.equals(c1, c2));
Cipher dec = Cipher.getInstance(TRANSFORMATION);
dec.init(Cipher.DECRYPT_MODE, pair.getPrivate(), OAEP_SHA256);
System.out.println("decrypted: " + new String(dec.doFinal(c1), StandardCharsets.UTF_8));
// OAEP with SHA-256 can encrypt at most k - 2*32 - 2 bytes (k = key size in bytes)
int max = 3072 / 8 - 2 * 32 - 2;
System.out.println("largest input for 3072-bit OAEP-SHA256: " + max + " bytes, works: "
+ (enc.doFinal(new byte[max]).length == 384));
try {
enc.doFinal(new byte[max + 1]);
} catch (IllegalBlockSizeException e) {
System.out.println((max + 1) + " bytes: IllegalBlockSizeException");
}
}
}
Output:
public key format X.509, 422 bytes; private key format PKCS#8
ciphertext size: 384 bytes (the key size)
same input encrypted twice is identical: false
decrypted: session key or other small secret
largest input for 3072-bit OAEP-SHA256: 318 bytes, works: true
319 bytes: IllegalBlockSizeException
- A ciphertext is always as long as the key: 3072 bits = 384 bytes.
- OAEP adds random padding, so encrypting the same input twice gives different ciphertexts. Old
is vulnerable to padding-oracle attacks for encryption; use OAEP.PKCS1Padding - RSA can only encrypt a small amount of data. With OAEP-SHA256 the limit is key bytes − 2 × hash bytes − 2 = 384 − 64 − 2 = 318 bytes, and 319 bytes fail with
.IllegalBlockSizeException - The OAEP parameters are passed explicitly. The name
looks equivalent, but in the JDK provider it uses SHA-1 for the MGF1 part, which can break interoperability with other systems."RSA/ECB/OAEPWithSHA-256AndMGF1Padding" - "ECB" in the transformation is a historical label; RSA encrypts a single block.
Use at least 2048-bit keys; 3072 bits is the NIST recommendation for protection beyond 2030. Key generation takes a noticeable fraction of a second, so generate keys once and store them.
Digital signatures
A signature proves that data came from the private key holder and was not changed. The program signs a release note with three algorithms and verifies both the original and a forged version.
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Signature;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.PSSParameterSpec;
public class Signatures {
static byte[] sign(String alg, KeyPair kp, byte[] data) throws Exception {
Signature s = Signature.getInstance(alg);
if (alg.equals("RSASSA-PSS")) {
s.setParameter(new PSSParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256,
32, 1));
}
s.initSign(kp.getPrivate());
s.update(data);
return s.sign();
}
static boolean verify(String alg, KeyPair kp, byte[] data, byte[] sig) throws Exception {
Signature s = Signature.getInstance(alg);
if (alg.equals("RSASSA-PSS")) {
s.setParameter(new PSSParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256,
32, 1));
}
s.initVerify(kp.getPublic());
s.update(data);
return s.verify(sig);
}
public static void main(String[] args) throws Exception {
KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA");
rsaGen.initialize(3072);
KeyPair rsa = rsaGen.generateKeyPair();
KeyPair ed = KeyPairGenerator.getInstance("Ed25519").generateKeyPair();
byte[] release = "app-2.4.1.jar sha256=9f2c...".getBytes(StandardCharsets.UTF_8);
byte[] forged = "app-2.4.1.jar sha256=0000...".getBytes(StandardCharsets.UTF_8);
String[][] algs = {{"SHA256withRSA", "rsa"}, {"RSASSA-PSS", "rsa"}, {"Ed25519", "ed"}};
for (String[] a : algs) {
KeyPair kp = a[1].equals("rsa") ? rsa : ed;
byte[] sig = sign(a[0], kp, release);
System.out.printf("%-14s signature %3d bytes, valid: %b, forged text valid: %b%n",
a[0], sig.length, verify(a[0], kp, release, sig),
verify(a[0], kp, forged, sig));
}
System.out.println("public key sizes: RSA " + rsa.getPublic().getEncoded().length
+ " bytes, Ed25519 " + ed.getPublic().getEncoded().length + " bytes");
}
}
Output:
SHA256withRSA signature 384 bytes, valid: true, forged text valid: false
RSASSA-PSS signature 384 bytes, valid: true, forged text valid: false
Ed25519 signature 64 bytes, valid: true, forged text valid: false
public key sizes: RSA 422 bytes, Ed25519 44 bytes
- All three accept the original and reject the forgery.
(PKCS#1 v1.5 signatures) is still widely used and considered secure for signing.SHA256withRSA is the more modern RSA scheme with a security proof and randomized output, and it needs its parameters set explicitly.RSASSA-PSS (Java 15, JEP 339) signs with 64-byte signatures and 44-byte public keys, against 384 and 422 bytes for 3072-bit RSA, and is much faster at generating keys and signing. For new systems that do not need RSA compatibility, it is a good default.Ed25519
Storing and loading keys
Keys must travel between systems and survive restarts. Java's getEncoded()-----BEGIN ...-----
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
public class KeyEncoding {
static String pem(String type, byte[] der) {
String body = Base64.getMimeEncoder(64, "\n".getBytes(StandardCharsets.US_ASCII))
.encodeToString(der);
return "-----BEGIN " + type + "-----\n" + body + "\n-----END " + type + "-----\n";
}
static byte[] fromPem(String pem) {
String b64 = pem.replaceAll("-----(BEGIN|END) [A-Z ]+-----", "").replaceAll("\\s", "");
return Base64.getDecoder().decode(b64);
}
public static void main(String[] args) throws Exception {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair kp = kpg.generateKeyPair();
// Standard encodings: X.509 SubjectPublicKeyInfo and PKCS#8 for the private key
System.out.println("public key format: " + kp.getPublic().getFormat() + ", "
+ kp.getPublic().getEncoded().length + " bytes");
System.out.println("private key format: " + kp.getPrivate().getFormat() + ", "
+ kp.getPrivate().getEncoded().length + " bytes");
String publicPem = pem("PUBLIC KEY", kp.getPublic().getEncoded());
String privatePem = pem("PRIVATE KEY", kp.getPrivate().getEncoded());
System.out.print(publicPem.lines().limit(2).reduce("", (a, b) -> a + b + "\n"));
System.out.println("... " + publicPem.lines().count() + " lines in total");
// Load both back, as another program would, and check they still work together
KeyFactory kf = KeyFactory.getInstance("RSA");
PublicKey pub = kf.generatePublic(new X509EncodedKeySpec(fromPem(publicPem)));
PrivateKey priv = kf.generatePrivate(new PKCS8EncodedKeySpec(fromPem(privatePem)));
byte[] data = "deploy v2.4.1".getBytes(StandardCharsets.UTF_8);
Signature signer = Signature.getInstance("SHA256withRSA");
signer.initSign(priv);
signer.update(data);
byte[] sig = signer.sign();
Signature verifier = Signature.getInstance("SHA256withRSA");
verifier.initVerify(pub);
verifier.update(data);
System.out.println("keys loaded from PEM sign and verify: " + verifier.verify(sig));
// The wrong spec class for the data is a clear error
try {
kf.generatePrivate(new PKCS8EncodedKeySpec(fromPem(publicPem)));
} catch (Exception e) {
System.out.println("public key bytes as PKCS#8: " + e.getClass().getSimpleName());
}
}
}
Output (the key itself is random):
public key format: X.509, 294 bytes
private key format: PKCS#8, 1217 bytes
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAktk1H4Hd0T9AzS79UmRm
... 9 lines in total
keys loaded from PEM sign and verify: true
public key bytes as PKCS#8: InvalidKeySpecException
- The public key is encoded as X.509
(294 bytes for 2048 bits) and loaded withSubjectPublicKeyInfo . The private key is PKCS#8 (about 1,200 bytes, because it holds the CRT values) and loaded withX509EncodedKeySpec .PKCS8EncodedKeySpec - PEM is Base64 in 64-character lines between the BEGIN and END markers, so stripping the markers and whitespace and decoding gives the binary form back. Java has no built-in PEM API before JDK 25's preview of one (JEP 470), so a few lines like these are common.
- Passing public key bytes to the PKCS#8 spec failed with
. OpenSSL's older "BEGIN RSA PRIVATE KEY" files use PKCS#1 instead of PKCS#8 and need converting first, withInvalidKeySpecException .openssl pkcs8 -topk8 - An unencrypted PKCS#8 file is the private key in plain text. In production, keep private keys in a password-protected PKCS#12
, a hardware security module or a cloud key service.KeyStore
Hybrid encryption: RSA plus AES
Because RSA is slow and limited to a few hundred bytes, real systems (TLS, PGP, JWE) use it only to protect a random symmetric key, and encrypt the data itself with AES. The program generates a fresh AES-256 key per message, wraps it with the recipient's public RSA key, and encrypts an 85,000-byte document with AES-GCM.
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.MGF1ParameterSpec;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.OAEPParameterSpec;
import javax.crypto.spec.PSource;
public class HybridEncryption {
static final OAEPParameterSpec OAEP = new OAEPParameterSpec("SHA-256", "MGF1",
MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT);
// Layout: wrapped AES key (384 bytes) | IV (12) | AES-GCM ciphertext and tag
static byte[] encrypt(PublicKey recipient, byte[] data) throws Exception {
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(256);
SecretKey aesKey = kg.generateKey(); // a new key for every message
Cipher rsa = Cipher.getInstance("RSA/ECB/OAEPPadding");
rsa.init(Cipher.WRAP_MODE, recipient, OAEP);
byte[] wrapped = rsa.wrap(aesKey);
byte[] iv = new byte[12];
new SecureRandom().nextBytes(iv);
Cipher aes = Cipher.getInstance("AES/GCM/NoPadding");
aes.init(Cipher.ENCRYPT_MODE, aesKey, new GCMParameterSpec(128, iv));
byte[] body = aes.doFinal(data);
return ByteBuffer.allocate(wrapped.length + 12 + body.length)
.put(wrapped).put(iv).put(body).array();
}
static byte[] decrypt(PrivateKey key, byte[] msg) throws Exception {
Cipher rsa = Cipher.getInstance("RSA/ECB/OAEPPadding");
rsa.init(Cipher.UNWRAP_MODE, key, OAEP);
SecretKey aesKey = (SecretKey) rsa.unwrap(Arrays.copyOf(msg, 384), "AES",
Cipher.SECRET_KEY);
Cipher aes = Cipher.getInstance("AES/GCM/NoPadding");
aes.init(Cipher.DECRYPT_MODE, aesKey, new GCMParameterSpec(128, msg, 384, 12));
return aes.doFinal(msg, 396, msg.length - 396);
}
public static void main(String[] args) throws Exception {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(3072);
KeyPair bob = kpg.generateKeyPair();
byte[] document = "quarterly report ".repeat(5000).getBytes(StandardCharsets.UTF_8);
byte[] msg = encrypt(bob.getPublic(), document);
System.out.println("document " + document.length + " bytes -> message " + msg.length
+ " bytes (384 wrapped key + 12 IV + data + 16 tag)");
byte[] back = decrypt(bob.getPrivate(), msg);
System.out.println("decrypted correctly: " + Arrays.equals(back, document));
}
}
Output:
document 85000 bytes -> message 85412 bytes (384 wrapped key + 12 IV + data + 16 tag)
decrypted correctly: true
The overhead is fixed: 384 bytes for the wrapped key, 12 for the IV and 16 for the GCM tag, 412 bytes whatever the document size. For the AES part and its pitfalls, see
How fast are RSA and its alternatives?
RSA's operations have very different costs: verifying is cheap, signing and decrypting are expensive, and generating a key means searching for large primes. The program measures key generation, signing and verification for three RSA sizes, ECDSA on curve P-256 and Ed25519, with a warm-up batch and the best of 3 batches. This is a rough comparison on a 2-CPU Linux machine with JDK 21; RSA key generation times vary a lot from run to run, because the prime search takes a random number of attempts.
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Signature;
import java.security.spec.ECGenParameterSpec;
public class RsaSpeed {
interface Op {
void run() throws Exception;
}
// Average microseconds per operation, best of 3 batches after a warm-up batch
static long micros(Op op, int n) throws Exception {
long best = Long.MAX_VALUE;
for (int batch = 0; batch < 4; batch++) {
long t0 = System.nanoTime();
for (int i = 0; i < n; i++) {
op.run();
}
if (batch > 0) {
best = Math.min(best, (System.nanoTime() - t0) / n);
}
}
return best / 1000;
}
static void row(String name, KeyPairGenerator gen, String sigAlg, int keygens)
throws Exception {
KeyPair kp = gen.generateKeyPair();
byte[] data = new byte[100];
Signature s = Signature.getInstance(sigAlg);
s.initSign(kp.getPrivate());
s.update(data);
byte[] sig = s.sign();
long keygen = micros(gen::generateKeyPair, keygens);
long sign = micros(() -> {
s.initSign(kp.getPrivate());
s.update(data);
s.sign();
}, 50);
Signature v = Signature.getInstance(sigAlg);
long verify = micros(() -> {
v.initVerify(kp.getPublic());
v.update(data);
v.verify(sig);
}, 200);
System.out.printf("%-14s keygen %,9d us sign %,6d us verify %,5d us sig %3d bytes%n",
name, keygen, sign, verify, sig.length);
}
public static void main(String[] args) throws Exception {
for (int bits : new int[] {2048, 3072, 4096}) {
KeyPairGenerator g = KeyPairGenerator.getInstance("RSA");
g.initialize(bits);
row("RSA-" + bits, g, "SHA256withRSA", bits == 4096 ? 2 : 4);
}
KeyPairGenerator ec = KeyPairGenerator.getInstance("EC");
ec.initialize(new ECGenParameterSpec("secp256r1"));
row("ECDSA P-256", ec, "SHA256withECDSA", 50);
row("Ed25519", KeyPairGenerator.getInstance("Ed25519"), "Ed25519", 50);
}
}
Output of the signature speed run:
RSA-2048 keygen 72,841 us sign 808 us verify 31 us sig 256 bytes
RSA-3072 keygen 267,933 us sign 2,201 us verify 61 us sig 384 bytes
RSA-4096 keygen 187,607 us sign 7,391 us verify 95 us sig 512 bytes
ECDSA P-256 keygen 416 us sign 480 us verify 1,438 us sig 71 bytes
Ed25519 keygen 413 us sign 684 us verify 1,580 us sig 64 bytes
- RSA verification took tens of microseconds, because the public exponent 65537 is small. Signing took milliseconds and grew quickly with the key size, since the private exponent is as large as the modulus.
- RSA key generation took tens to hundreds of milliseconds, against a fraction of a millisecond for the elliptic-curve keys. Generate RSA keys once and store them.
- ECDSA and Ed25519 signed several times faster than RSA-3072, with signatures of 64 to 72 bytes instead of 384. Their verification is slower than RSA's, which matters for systems that verify far more often than they sign.
- Encryption with the public key costs about the same as verification, and decryption about the same as signing. In a hybrid scheme this cost is paid once per message, not per byte.
Choosing a public-key scheme
| Need | Use |
|---|---|
| Encrypt a small secret, such as a key, for a recipient | RSA-OAEP with SHA-256 and explicit OAEPParameterSpec |
| Encrypt data of any size for a recipient | Hybrid: RSA-OAEP wraps a fresh AES-GCM key |
| Signatures that must work everywhere | SHA256withRSA |
| New signatures without legacy constraints | Ed25519 |
| Small signatures in certificates and TLS | ECDSA P-256 |
| Long-term protection against quantum computers | ML-KEM and ML-DSA (JDK 24 and later) |
| A shared secret between two parties |