I kept bumping into RSA puzzles, opening somebody else’s blog, and scrolling around to find the same handful of equations. This is the version I wanted on my own blog: what do I already know, what’s missing, and which calculation gets me there?
Going from a message to a ciphertext
Call the original message $m$ and the encrypted number $c$. The public key has two parts, $(n,e)$. To build it, pick two large, distinct primes $p$ and $q$ and multiply them:
$$
n=pq
$$
The public exponent $e$ needs to be coprime to $\phi(n)$. A common choice is 65537. If you see 0x10001 in a challenge, that’s the same number written in hex. Encryption is then:
$$
c=m^e\bmod n
$$
Going back the other way
The private key is $(n,d)$. With that exponent in hand, decrypting is just another modular power:
$$
m=c^d\bmod n
$$
In the kind of puzzle I was doing, I had $c$, $n$, and $e$ right in front of me. The missing piece was $d$. Here’s how the pieces fit together.
- Get the two factors of the challenge modulus. I used
factordb.comto see whether someone had already factored that particular $n$. If the factors are known, that’s $p$ and $q$. - Calculate the totient. For two distinct primes, $\phi(n)=(p-1)(q-1)$. Knowing the factors is what makes this step easy.
- Find the private exponent. I want a number $d$ such that multiplying it by $e$ leaves remainder 1 modulo $\phi(n)$. In Python,
d = gmpy2.invert(e, (p-1)*(q-1))gives me that modular inverse. - Turn the decrypted number back into bytes. Python’s three-argument
pow(c, d, n)calculates the modular power directly. The result is an integer. If the puzzle originally encoded a message as bytes, there’s still one more step before I can read it.
In my notes I used binascii.a2b_hex(hex(m)[2:]): write the integer in hex, strip off Python’s 0x prefix, and decode each pair of hex digits as one byte. That pairwise decoding expects an even number of digits. A hex decoder or a short script both do the job.



