Skip to content
Blog

← All articles

Primes and Remainders: How Modular Arithmetic Locks and Unlocks RSA

The number theory behind RSA, one tested step at a time: clock arithmetic, square-and-multiply, Euler's theorem (the reason decryption gives the message back), modular inverses, finding 1024-bit primes with Miller-Rabin, a 2048-bit key built from scratch that OpenSSL accepts, what's inside a real private key file, and the attacks that break RSA when the math is used carelessly.

By 20 min read

RSA is often described in one sentence: multiply two big primes, and only someone who knows them can undo the encryption. That sentence is true, but it skips everything interesting. Why does raising a number to one power and then another give the original back? Where does the private key come from? How do you find a prime with 300 digits, and why does a computer that can do that in a fraction of a second have no hope of splitting their product apart?

This article answers those questions with the math and with code. Each idea is a short JavaScript program (with a Python one-liner where Python does it for you), and at the end they combine into a real 2,048-bit key, built from scratch, that OpenSSL accepts and uses. Every output below comes from running the code: Node.js 24, Python 3.14, OpenSSL 3.5, and Go 1.25, two full runs.

If you want the bigger picture first (where RSA sits next to AES and elliptic curves, and why it's only used for small things), read symmetric vs. asymmetric encryption. This one goes inside.

The short answer#

message
m = 65
me mod n
public key (3233, 17)
locked
c = 2790
cd mod n
private key (3233, 413)
unlocked
m = 65
The toy key used throughout: p = 61, q = 53, n = 3233, e = 17, d = 413.

Remainders: arithmetic on a clock#

"Mod n" means: divide by n and keep only the remainder. It's the arithmetic of a clock. Fifteen o'clock is three o'clock, and eight hours after nine is five, because (9 + 8) mod 12 = 5. The numbers wrap around and never grow past n − 1.

The property that makes this useful is that you can take the remainder at any step. Reducing after every addition or multiplication gives the same answer as doing the whole calculation and reducing once at the end. That's what lets a computer work with powers that have millions of digits without ever writing one down:

clock.mjs
// clock.mjs: arithmetic "mod n" keeps only the remainder, and you can take it at any step.
console.log(15 % 12); // 3: fifteen o'clock is three o'clock
console.log((9 + 8) % 12); // 5: eight hours after nine

// Reducing as you go gives the same answer as reducing at the end...
const a = 123456789n, b = 987654321n, n = 1000n;
console.log((a * b) % n, ((a % n) * (b % n)) % n); // 269n 269n

// ...which is what keeps the numbers small: 7^100 has 85 digits, but mod 13 it's one multiplication at a time.
let x = 1n;
for (let i = 0; i < 100; i++) x = (x * 7n) % 13n;
console.log(x, 7n ** 100n % 13n); // 9n 9n

// A trap: JavaScript's % keeps the sign of the left side, so it isn't "mod" for negative numbers.
console.log(-7 % 3); // -1
const mod = (x, n) => ((x % n) + n) % n;
console.log(mod(-7, 3)); // 2: the mathematician's answer (Python's -7 % 3 gives 2 too)

One trap for JavaScript and Java developers: their % operator returns a remainder with the sign of the left side, so -7 % 3 is -1, not the 2 that mathematics (and Python's %) gives. Every place RSA code might subtract and end up negative (you'll see two below) has to correct for it.

Powers without giant numbers#

RSA's one operation is xk mod n with a k that has hundreds of digits. Multiplying x by itself k times would take longer than the universe has existed. Square-and-multiply takes one step per bit of k instead: square the base at every step (x, x2, x4, x8, …) and multiply the ones whose bit is 1 into the result, reducing mod n every time.

modpow.mjs
// modpow.mjs: square-and-multiply computes base^exp mod m one bit of the exponent at a time.
let multiplications = 0;

function modPow(base, exp, m) {
  let result = 1n;
  base %= m;
  while (exp > 0n) {
    if (exp & 1n) {
      result = (result * base) % m; // this bit is 1: multiply it in
      multiplications++;
    }
    base = (base * base) % m; // base, base^2, base^4, base^8, ...
    multiplications++;
    exp >>= 1n;
  }
  return result;
}

console.log(modPow(4n, 13n, 497n), 4n ** 13n % 497n); // 445n 445n

// The costs that matter for RSA: a 2,048-bit modulus, the public exponent 65537, and a 2,048-bit private exponent.
const bits = (k) => BigInt("0x" + crypto.getRandomValues(new Uint8Array(k / 8)).reduce((s, b) => s + b.toString(16).padStart(2, "0"), "")) | (1n << BigInt(k - 1));
const m = bits(2048), x = bits(2040);
for (const [name, exp] of [["e = 65537", 65537n], ["2,048-bit d", bits(2048)]]) {
  multiplications = 0;
  const t = performance.now();
  modPow(x, exp, m);
  console.log(`${name}: ${multiplications} multiplications, ${(performance.now() - t).toFixed(2)} ms`);
}

Output:

445n 445n
e = 65537: 19 multiplications, 0.22 ms
2,048-bit d: 3070 multiplications, 17.12 ms

That's the whole cost model of RSA. The public exponent 65537 is 216 + 1, binary 10000000000000001: 17 squarings and 2 multiplications, 19 in total. A 2,048-bit private exponent needs about 2,048 squarings and, on average, half as many multiplications: 3,070 to 3,106 in our runs. That's why encrypting and verifying signatures are fast, and decrypting and signing are slow: OpenSSL took 0.015 ms for the public operation on a 2,048-bit key and 0.36–0.37 ms for the private one, about 24 times longer. (Our BigInt code, even with the speed-up described later, is 11 to 12 times slower than OpenSSL. Use it to learn, not to ship.)

The one-way street#

Public-key cryptography needs a trapdoor: something easy to do, hard to undo, and easy to undo if you know a secret. RSARSA's is built fromapos;s trapdoor is built from two facts about numbers:

  • Multiplying is easy; factoring is hard. Multiplying two 1,024-bit primes takes microseconds. Getting them back from the 2,048-bit product is the factoring problem, and the best-known algorithm (the general number field sieve) grows faster than any polynomial in the number of digits. The record for an RSA-style number is RSA-250, 829 bits, factored in 2020 with about 2,700 CPU core-years.
  • Powers mod n are easy; roots mod n are hard. Computing me mod n takes 19 multiplications. Undoing it, finding the e-th root mod n, has no known shortcut unless you can factor n.

The secret that opens the trapdoor is the factorization, and the next section shows exactly how it's used.

Why unlocking works: Euler's theorem#

Take any number and keep multiplying it by itself mod a prime, and you'll come back to 1. Here are the powers of 1 to 6, mod 7:

aa1a2a3a4a5a6
1111111
2241241
3326451
4421421
5546231
6616161
Every row reaches 1 by the 6th power. Some (2, 4) get there sooner, but all of them are back at 1 at power 6 = 7 − 1.

That's Fermat's little theorem: for a prime p and any a it doesn't divide, ap−1 mod p = 1. Euler extended it to any modulus: aφ(n) mod n = 1, where φ(n) counts the numbers below n that share no factor with it. For n = p × q, φ(n) = (p − 1)(q − 1).

Once a power is 1, multiplying one more time gives the number back. So if e × d = 1 + kφ(n) for some whole number k, then

(me)d = m1 + k·φ(n) = m · (mφ(n))k = m · 1k = m (mod n)

That's the whole reason RSA decryption works. And there's a refinement every real library uses: φ(n) isn't the shortest cycle. Carmichael's function λ(n) = lcm(p − 1, q − 1) also works for every m, and it's smaller (because p − 1 and q − 1 are both even, at least half as big). This program checks all of that for the toy key, by brute force:

euler.mjs
// euler.mjs: powers mod n go round in cycles, and Euler's theorem says how long the cycle is.
const modPow = (b, e, m) => { let r = 1n; for (b %= m; e > 0n; e >>= 1n, b = (b * b) % m) if (e & 1n) r = (r * b) % m; return r; };
const gcd = (a, b) => (b === 0n ? a : gcd(b, a % b));

// Mod the prime 7, every power sequence returns to 1 by the 6th power (Fermat's little theorem: a^(p-1) = 1).
for (const a of [2n, 3n]) console.log(`${a}^1..12 mod 7:`, Array.from({ length: 12 }, (_, k) => modPow(a, BigInt(k + 1), 7n)).join(" "));

// Mod n = p*q, the numbers that share no factor with n all return to 1 at the power phi = (p-1)(q-1)...
const p = 61n, q = 53n, n = p * q;
const phi = (p - 1n) * (q - 1n); // 3120
const lambda = phi / gcd(p - 1n, q - 1n); // 780 = lcm(60, 52): Carmichael's function, the smallest such power
let coprime = 0, phiWorks = 0, lambdaWorks = 0;
for (let m = 1n; m < n; m++) {
  if (gcd(m, n) !== 1n) continue;
  coprime++;
  if (modPow(m, phi, n) === 1n) phiWorks++;
  if (modPow(m, lambda, n) === 1n) lambdaWorks++;
}
console.log({ coprime, phiWorks, lambdaWorks }); // all 3120

// ...so if e*d = 1 + k*lambda, then m^(e*d) = m * (m^lambda)^k = m. It even holds for the 112 values of m that share a
// factor with n (multiples of 61 or 53), which a proof by the Chinese remainder theorem covers.
const e = 17n, d = 413n; // 17 * 413 = 7021 = 9 * 780 + 1
let roundTrips = 0;
for (let m = 0n; m < n; m++) if (modPow(modPow(m, e, n), d, n) === m) roundTrips++;
console.log(`${roundTrips} of ${n} messages come back`); // 3233 of 3233

Output:

2^1..12 mod 7: 2 4 1 2 4 1 2 4 1 2 4 1
3^1..12 mod 7: 3 2 6 4 5 1 3 2 6 4 5 1
{ coprime: 3120, phiWorks: 3120, lambdaWorks: 3120 }
3233 of 3233 messages come back

The last line covers a worry people often raise: Euler's theorem needs m to share no factor with n, so what about the 112 messages that are multiples of 61 or 53? They round-trip too. Looking at the problem mod p and mod q separately (the Chinese remainder theorem, which comes back later as a speed-up) shows each side works on its own. In practice it doesn't matter anyway: hitting a multiple of p by chance with a 2,048-bit key is as likely as guessing p.

Finding the private key: modular inverses#

So d must satisfy e × d mod λ(n) = 1. That makes d the modular inverse of e, and there's a 2,300-year-old way to find it: Euclid's algorithm for the greatest common divisor, extended to keep track of how each remainder was built. When the gcd reaches 1, the bookkeeping is the inverse.

inverse.mjs
// inverse.mjs: the extended Euclidean algorithm finds d with e*d = 1 (mod m), the private exponent.
function modInverse(a, m) {
  let [oldR, r] = [a, m]; // remainders, as in Euclid's gcd
  let [oldS, s] = [1n, 0n]; // and how many a's each remainder is made of
  while (r !== 0n) {
    const quotient = oldR / r;
    [oldR, r] = [r, oldR - quotient * r];
    [oldS, s] = [s, oldS - quotient * s];
  }
  if (oldR !== 1n) throw new RangeError(`${a} has no inverse mod ${m}: they share the factor ${oldR}`);
  return ((oldS % m) + m) % m; // oldS * a = 1 (mod m); make it positive
}

console.log(modInverse(17n, 780n)); // 413n: d for the toy key, mod lambda
console.log(modInverse(17n, 3120n)); // 2753n: the textbook d, mod phi; both work
console.log((17n * 413n) % 780n, (17n * 2753n) % 3120n); // 1n 1n
try {
  modInverse(3n, 780n);
} catch (err) {
  console.log(err.message); // 3 has no inverse mod 780: they share the factor 3
}

Both answers decrypt: 2,753 is the classic textbook value (worked out mod φ = 3,120), and 413 is the smaller one, mod λ = 780. The error at the end is why e must share no factor with λ(n): if it does, there's no inverse, and key generation has to pick new primes. Python has all of this built in, including the inverse, as pow(e, -1, m) since 3.8:

rsa_small.py
# rsa_small.py: Python has the three building blocks built in: pow() with a modulus, pow() with -1, and math.lcm.
import math

p, q, e = 61, 53, 17
n = p * q                    # 3233
lam = math.lcm(p - 1, q - 1) # 780
d = pow(e, -1, lam)          # 413: the modular inverse (Python 3.8+)
c = pow(65, e, n)            # encrypt the message 65
print(n, lam, d, c, pow(c, d, n))  # 3233 780 413 2790 65

This is the trapdoor closing. λ(n) needs p and q. Anyone can see n and e; to compute d, they'd need λ(n), and computing λ(n) from n alone is as hard as factoring it.

Finding 300-digit primes#

A 2,048-bit key needs two random primes of 1,024 bits, about 309 decimal digits each. Two facts make that practical.

Primes are common. The prime number theorem says a random number near x is prime with probability about 1/ln x. For 1,024-bit numbers, ln 21024 ≈ 710, and skipping even numbers halves that: one odd candidate in about 355 is prime. Our generators agreed: an average of 358 candidates per prime over 2,000 primes in Node.js, 361 over 2,000 in Python, and 337 over another 500 in Node.js.

Testing is fast, if you don't ask for proof. Fermat's little theorem gives an obvious test: if an−1 mod n isn't 1, n is certainly not prime. The trouble is the converse. Some composites, the Carmichael numbers, pass for every base. The Miller–Rabin test closes the gap: it also checks the square roots of 1 that appear along the way, and a composite number fails it for at least three out of four random bases. Forty rounds leave a chance below 4−40 (2−80) of being fooled, and for random candidates the real figure is far smaller still.

primes.mjs
// primes.mjs: why the simple primality test fails, and the Miller-Rabin test that real libraries use.
const modPow = (b, e, m) => { let r = 1n; for (b %= m; e > 0n; e >>= 1n, b = (b * b) % m) if (e & 1n) r = (r * b) % m; return r; };

// Fermat's test: if a^(n-1) mod n isn't 1, n is certainly composite. But 56052361 = 211 * 421 * 631 gives 1 for every
// a that shares no factor with it: it's a Carmichael number.
const carmichael = 56052361n;
console.log(modPow(2n, carmichael - 1n, carmichael), modPow(3n, carmichael - 1n, carmichael)); // 1n 1n: "prime", and wrong

function randomBits(bits) {
  const bytes = crypto.getRandomValues(new Uint8Array(Math.ceil(bits / 8)));
  const x = BigInt("0x" + Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""));
  return x >> BigInt(bytes.length * 8 - bits);
}

const SMALL_PRIMES = [2n, 3n, 5n, 7n, 11n, 13n, 17n, 19n, 23n, 29n, 31n, 37n, 41n, 43n, 47n];

function isProbablePrime(n, rounds = 40) {
  if (n < 2n) return false;
  for (const sp of SMALL_PRIMES) {
    if (n === sp) return true;
    if (n % sp === 0n) return false; // cheap filter: most candidates stop here
  }
  let d = n - 1n, s = 0; // write n - 1 = d * 2^s with d odd
  while ((d & 1n) === 0n) { d >>= 1n; s++; }
  witness: for (let i = 0; i < rounds; i++) {
    let a;
    do a = randomBits(n.toString(2).length); while (a < 2n || a > n - 2n); // a random base in [2, n-2]
    let x = modPow(a, d, n);
    if (x === 1n || x === n - 1n) continue;
    for (let r = 1; r < s; r++) {
      x = (x * x) % n;
      if (x === n - 1n) continue witness;
    }
    return false; // a proved n composite
  }
  return true; // composite with probability below 4^-rounds
}

console.log(isProbablePrime(carmichael), isProbablePrime(2n ** 127n - 1n)); // false true

// A random prime: set the top two bits (so p*q has exactly twice the bits) and the bottom bit (odd), then test.
function randomPrime(bits) {
  for (let tries = 1; ; tries++) {
    const candidate = randomBits(bits) | (3n << BigInt(bits - 2)) | 1n;
    if (isProbablePrime(candidate)) return { prime: candidate, tries };
  }
}

const t = performance.now();
const { prime, tries } = randomPrime(1024);
console.log(`a 1024-bit prime after ${tries} odd candidates, ${(performance.now() - t).toFixed(0)} ms:`);
console.log(prime.toString(16));

Output (the prime is different every run):

1n 1n
false true
a 1024-bit prime after 318 odd candidates, 258 ms:
dede6162a46b49ccf63109e65891ef0e61085149ce3bf2d01a547e8ec8d8ba99fae9093ee0de58e05c07b061290bff27…

The trial division by the first 15 primes stops 72% of candidates before any exponentiation, which is why libraries always do it first. Two more details matter. Setting the top two bits guarantees that the product of two such primes has exactly 2,048 bits, not 2,047. And the random bits must come from a cryptographically secure generator (here crypto.getRandomValues): if an attacker can predict the candidates, they can predict the primes. Predictable Chaos shows how quickly a non-secure generator gives itself away.

We had OpenSSL's own openssl prime confirm the primes our Miller–Rabin accepted: 100 out of 100, plus the one in each test run.

A real key from scratch#

The functions from the sections above, collected into one module:

rsa-math.mjs
// rsa-math.mjs: the functions from the sections above, in one module, for rsa.mjs, inspect-key.mjs and attacks.mjs.
export function modPow(base, exp, m) {
  let result = 1n;
  for (base %= m; exp > 0n; exp >>= 1n, base = (base * base) % m) if (exp & 1n) result = (result * base) % m;
  return result;
}

export const gcd = (a, b) => { while (b) [a, b] = [b, a % b]; return a; };

export function modInverse(a, m) {
  let [oldR, r, oldS, s] = [a, m, 1n, 0n];
  while (r !== 0n) {
    const quotient = oldR / r;
    [oldR, r, oldS, s] = [r, oldR - quotient * r, s, oldS - quotient * s];
  }
  if (oldR !== 1n) throw new RangeError(`${a} has no inverse mod ${m}`);
  return ((oldS % m) + m) % m;
}

export function randomBits(bits) {
  const bytes = crypto.getRandomValues(new Uint8Array(Math.ceil(bits / 8)));
  const x = BigInt("0x" + Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""));
  return x >> BigInt(bytes.length * 8 - bits);
}

const SMALL_PRIMES = [2n, 3n, 5n, 7n, 11n, 13n, 17n, 19n, 23n, 29n, 31n, 37n, 41n, 43n, 47n];

export function isProbablePrime(n, rounds = 40) {
  if (n < 2n) return false;
  for (const sp of SMALL_PRIMES) {
    if (n === sp) return true;
    if (n % sp === 0n) return false;
  }
  let d = n - 1n, s = 0;
  while ((d & 1n) === 0n) { d >>= 1n; s++; }
  witness: for (let i = 0; i < rounds; i++) {
    let a;
    do a = randomBits(n.toString(2).length); while (a < 2n || a > n - 2n);
    let x = modPow(a, d, n);
    if (x === 1n || x === n - 1n) continue;
    for (let r = 1; r < s; r++) {
      x = (x * x) % n;
      if (x === n - 1n) continue witness;
    }
    return false;
  }
  return true;
}

export function randomPrime(bits) {
  for (;;) {
    const candidate = randomBits(bits) | (3n << BigInt(bits - 2)) | 1n;
    if (isProbablePrime(candidate)) return candidate;
  }
}

// BigInt <-> the big-endian base64url that JWKs use
export const toB64u = (x) => { const h = x.toString(16); return Buffer.from(h.length % 2 ? "0" + h : h, "hex").toString("base64url"); };
export const fromB64u = (s) => BigInt("0x" + Buffer.from(s, "base64url").toString("hex"));

And the key: two primes, λ, d, then locking and unlocking a message. To prove these are real RSA numbers and not just numbers that happen to agree with our own code, the last part hands them to Node's crypto module, which is OpenSSL, as a JSON Web Key:

rsa.mjs
// rsa.mjs: a 2048-bit RSA key from scratch, used to lock and unlock a message, then handed to Node's own crypto
// (OpenSSL) to prove it's a real key.
import crypto from "node:crypto";
import { writeFileSync } from "node:fs";
import { gcd, modInverse, modPow, randomPrime, toB64u } from "./rsa-math.mjs";

// 1. Two secret primes, and the public modulus.
const e = 65537n;
let p, q, lambda;
do {
  p = randomPrime(1024);
  q = randomPrime(1024);
  lambda = ((p - 1n) * (q - 1n)) / gcd(p - 1n, q - 1n); // lcm(p-1, q-1): needs p and q
} while (p === q || gcd(e, lambda) !== 1n);
const n = p * q;

// 2. The private exponent: the inverse of e, mod lambda.
const d = modInverse(e, lambda);
console.log(`n: ${n.toString(2).length} bits, d: ${d.toString(2).length} bits`);

// 3. Lock with the public key (n, e), unlock with the private key (n, d).
const message = BigInt("0x" + Buffer.from("attack at dawn").toString("hex")); // any number below n
const locked = modPow(message, e, n);
const unlocked = modPow(locked, d, n);
console.log(Buffer.from(unlocked.toString(16), "hex").toString()); // attack at dawn

// 4. The same unlock, faster: two half-size exponentiations, joined by the Chinese remainder theorem.
const dp = d % (p - 1n), dq = d % (q - 1n), qi = modInverse(q, p);
const mp = modPow(locked, dp, p), mq = modPow(locked, dq, q);
const crt = mq + q * ((qi * (mp - mq + p)) % p);
console.log("CRT gives the same message:", crt === message);

// 5. Hand the numbers to OpenSSL as a JWK, and let it do the math.
const key = crypto.createPrivateKey({
  format: "jwk",
  key: { kty: "RSA", n: toB64u(n), e: toB64u(e), d: toB64u(d), p: toB64u(p), q: toB64u(q), dp: toB64u(dp), dq: toB64u(dq), qi: toB64u(qi) },
});
console.log(key.asymmetricKeyDetails); // { modulusLength: 2048, publicExponent: 65537n }

const raw = crypto.privateDecrypt({ key, padding: crypto.constants.RSA_NO_PADDING }, Buffer.from(locked.toString(16).padStart(512, "0"), "hex"));
console.log("OpenSSL unlocks our ciphertext:", BigInt("0x" + raw.toString("hex")) === message);

const sealed = crypto.publicEncrypt({ key, oaepHash: "sha256" }, Buffer.from("attack at dawn")); // real, padded RSA-OAEP
console.log("OAEP round trip:", crypto.privateDecrypt({ key, oaepHash: "sha256" }, sealed).toString());

writeFileSync("key.pem", key.export({ type: "pkcs8", format: "pem" })); // `openssl pkey -in key.pem -check` accepts it

Output:

n: 2048 bits, d: 2045 bits
attack at dawn
CRT gives the same message: true
{ modulusLength: 2048, publicExponent: 65537n }
OpenSSL unlocks our ciphertext: true
OAEP round trip: attack at dawn

OpenSSL decrypted the ciphertext our 20 lines of math produced, encrypted and decrypted with real OAEP padding using our key, and openssl pkey -check reports the exported file as Key is valid.

Step 4 is the Chinese remainder theorem (CRT) speed-up every library uses. Instead of one exponentiation mod the 2,048-bit n, it does two mod the 1,024-bit primes and combines them. Multiplication cost grows with the square of the size, and the exponents are half as long too, so each half costs about an eighth and the pair a quarter. Our BigInt decryption went from 15.0 ms to 4.1–4.3 ms, 3.5–3.7 times faster. The + p in mp - mq + p is the negative-remainder trap from the first section: without it, % can go below zero.

What's inside a private key file#

A PEM private key is Base64 around a DER structure that stores eight numbers. OpenSSL prints their names, and the JWK format uses shorter ones:

OpenSSLJWKWhat it is
modulusnp × q; public
publicExponenteAlmost always 65537; public
privateExponentde−1 mod λ(n)
prime1, prime2p, qThe two primes
exponent1, exponent2dp, dqd mod (p − 1), d mod (q − 1): the CRT exponents
coefficientqiq−1 mod p: joins the two CRT halves

Only n and e are public; the other six are redundant (any one of p, q or d lets you compute the rest), stored to make decryption fast. This script opens a key and checks every relationship:

inspect-key.mjs
// inspect-key.mjs: open a real RSA private key and check the number theory inside it.
//   node inspect-key.mjs key.pem     (no argument: a fresh 2048-bit key from Node)
import crypto from "node:crypto";
import { readFileSync } from "node:fs";
import { fromB64u, gcd, isProbablePrime, modInverse } from "./rsa-math.mjs";

const key = process.argv[2]
  ? crypto.createPrivateKey(readFileSync(process.argv[2]))
  : crypto.generateKeyPairSync("rsa", { modulusLength: 2048 }).privateKey;
const jwk = key.export({ format: "jwk" });
const [n, e, d, p, q, dp, dq, qi] = ["n", "e", "d", "p", "q", "dp", "dq", "qi"].map((k) => fromB64u(jwk[k]));

const phi = (p - 1n) * (q - 1n);
const lambda = phi / gcd(p - 1n, q - 1n);
const checks = {
  "p and q are prime": isProbablePrime(p) && isProbablePrime(q),
  "n = p * q": n === p * q,
  "e * d = 1 (mod lambda)": (e * d) % lambda === 1n,
  "d = inverse of e mod lambda": d === modInverse(e, lambda),
  "d = inverse of e mod phi": d === modInverse(e, phi),
  "dp = d mod (p - 1)": dp === d % (p - 1n),
  "dq = d mod (q - 1)": dq === d % (q - 1n),
  "qi = inverse of q mod p": qi === modInverse(q, p),
};
console.log(`${n.toString(2).length}-bit n, e = ${e}, gcd(p - 1, q - 1) = ${gcd(p - 1n, q - 1n)}`);
for (const [check, ok] of Object.entries(checks)) console.log(ok ? "yes" : "no ", check);
openssl-key.sh
# openssl-key.sh: make a key with OpenSSL, list the numbers it stores, and check them with inspect-key.mjs.
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out openssl-key.pem
openssl pkey -in openssl-key.pem -text -noout | grep -E '^[a-zA-Z]'
node inspect-key.mjs openssl-key.pem

We ran it on keys from five sources: our rsa.mjs, Node.js (OpenSSL 3.5), the openssl command, Python's cryptography 50 (OpenSSL 4.0), and Go 1.25's crypto/rsa. Every relationship held for all of them, and they agree on one detail textbooks usually get wrong: every one stores d = e−1 mod λ(n), the smaller exponent, not the mod-φ(n) value most explanations show. (About half the time the two happen to coincide, which is why some keys pass both checks.) It makes no difference to the result, since both decrypt correctly, but if you recompute d mod φ to "check" a key, you'll get a different number and think it's broken.

When the math is used carelessly#

Nothing above is secure on its own. The math is only safe with randomized padding and well-made primes, and each missing safeguard has broken real systems. Three attacks, each in a few lines:

attacks.mjs
// attacks.mjs: three ways RSA's math breaks when it's used without padding or with badly chosen primes.
import { gcd, isProbablePrime, modInverse, modPow, randomBits, randomPrime } from "./rsa-math.mjs";

function iroot(x, k) { // the integer k-th root, rounded down (Newton's method)
  if (x < 2n) return x;
  let r = 1n << BigInt(Math.ceil(x.toString(2).length / Number(k)));
  for (;;) {
    const next = ((k - 1n) * r + x / r ** (k - 1n)) / k;
    if (next >= r) return r;
    r = next;
  }
}

// 1. e = 3 and no padding: a 128-bit AES key cubed is only 384 bits, far below n, so "mod n" never happens.
let p, q;
do { p = randomPrime(1024); q = randomPrime(1024); } while (p % 3n !== 2n || q % 3n !== 2n); // gcd(3, p-1) = 1
const n = p * q;
const aesKey = randomBits(128);
const c = modPow(aesKey, 3n, n);
console.log("1. cube root of the ciphertext is the AES key:", iroot(c, 3n) === aesKey);

// 2. Two keys that share a prime (a weak random generator at boot): one gcd factors both.
const shared = randomPrime(1024);
const n1 = shared * randomPrime(1024), n2 = shared * randomPrime(1024);
const found = gcd(n1, n2);
console.log("2. gcd(n1, n2) is the shared prime:", found === shared, "-> n1 / p =", isProbablePrime(n1 / found) ? "prime" : "?");

// 3. Primes too close together: Fermat's method writes n = a^2 - b^2 = (a - b)(a + b), starting at a = sqrt(n).
const p3 = randomPrime(1024);
let q3 = p3 + 2n;
while (!isProbablePrime(q3)) q3 += 2n; // the next prime after p3
const n3 = p3 * q3;
let a = iroot(n3, 2n);
if (a * a < n3) a++;
for (let step = 1; ; step++, a++) {
  const b = iroot(a * a - n3, 2n);
  if (b * b === a * a - n3) {
    console.log(`3. Fermat factored a 2048-bit n in ${step} step(s):`, a - b === p3 && a + b === q3);
    break;
  }
}

// Any of the three gives the private key straight away:
const d1 = modInverse(65537n, (found - 1n) * (n1 / found - 1n));
console.log("   private key from the factors works:", modPow(modPow(42n, 65537n, n1), d1, n1) === 42n);

Output:

1. cube root of the ciphertext is the AES key: true
2. gcd(n1, n2) is the shared prime: true -> n1 / p = prime
3. Fermat factored a 2048-bit n in 1 step(s): true
   private key from the factors works: true
  1. Small exponent, no padding. With e = 3, a 128-bit AES key cubed is only 384 bits, far smaller than the 2,048-bit n, so "mod n" never wraps anything and the ciphertext is just the plain cube. An ordinary integer cube root recovers the key. Padding fixes this by filling the number up to nearly the size of n with random bytes; it's also why everyone uses e = 65537 rather than 3.
  2. Shared primes. If two keys share a prime, Euclid's gcd finds it in microseconds, and both keys fall. That sounds unlikely until a batch of devices generates keys at first boot with almost no randomness. In 2012, the "Mining Your Ps and Qs" study computed the gcd of every pair of 11 million public keys from the internet and recovered the private keys of 0.50% of TLS hosts.
  3. Primes too close together. If p and q are close, n is close to a perfect square, and Fermat's 1643 method (write n = a2 − b2, starting from a = √n) finds them almost at once: one step, here. In 2022, Hanno Böck found Canon and Fujifilm printers whose certificates used keys from a library that chose its two primes too close together (CVE-2022-26320). A properly generated key has primes that differ in their first bits, which puts Fermat's method hopelessly out of reach.

The bare math has two more problems that padding exists to solve. It's deterministic: the same message always gives the same ciphertext, so an attacker can encrypt guesses and compare. And it's malleable: multiplying a ciphertext by xe multiplies the hidden message by x. So:

How big is safe, and for how long#

Factoring algorithms improve slowly and predictably, so key sizes map to security levels: NIST rates a 2,048-bit modulus at 112-bit security, 3,072 bits at 128, and 15,360 bits at 256. Size grows quickly because the general number field sieve is so much better than brute force, which is one reason elliptic curves, with their 256-bit keys, took over key exchange (see From SSL to TLS 1.3, where RSA key exchange was removed entirely in favor of forward-secret ECDHE).

The deadline that matters more is quantum. Shor's algorithm factors in polynomial time on a large enough quantum computer, and no key size helps against it. NIST's transition plan (IR 8547) deprecates RSA after 2030 and disallows it after 2035, in favor of ML-KEM for key exchange and ML-DSA for signatures. RSA will keep verifying old signatures for years, but new systems should plan for its replacement.

FAQ#

Why 65537?

It's prime, so it's unlikely to share a factor with λ(n), and it has only two 1 bits, so encrypting and verifying take 19 multiplications. It's large enough to avoid the small-exponent problems of 3. Most libraries use nothing else.

Does the private key have to be a separate, random number?

No. Only p and q are random. d is fully determined by them and e, which is why leaking p (or d, or dp) is as bad as leaking the whole key.

How is signing different from encrypting?

The same operation in the other direction: the owner raises a padded hash to the power d, and anyone raises the signature to e and checks the hash comes back. An RS256 JWT, or the signature in a TLS certificate, is exactly this; see private key JWT for one in use.

Can I encrypt a file with RSA directly?

No: the message must be a number smaller than n, and OAEP padding takes some of that space. With a 2,048-bit key and SHA-256, that's 190 bytes at most. Real systems encrypt the file with AES and use RSA only for the AES key.

Is the Miller–Rabin "probably prime" good enough?

Yes. With 40 random bases, the chance of accepting a composite is below 2−80, much less likely than a hardware error during the computation. Proving primality is possible, but no mainstream library bothers for key generation.

Try it in your browser