atmathExploreไทย

Curious math · Cryptography, part 2

A padlock anyone can lock but only one person can open: how does RSA work?

Short answer: RSA uses 2 keys. The public key is like a padlock you hand out to anyone; it is used to lock. The private key stays with you alone; it is used to unlock. Nobody else can work out the private key, because that means splitting a huge number into a product of 2 primes, and no one knows a fast way to do that.

The problem: sending a secret to someone you’ve never met

If one key both locks and unlocks, you first have to get that key to the other person, and it could be stolen on the way. In 1977–1978, Rivest, Shamir and Adleman (RSA for short) proposed a way to publish the locking key without revealing the unlocking key. Anyone who wants to send us a secret can just pick up our padlock and lock it.

Making the keys in 4 steps (small numbers · demo only)

  1. Pick 2 prime numbers: p = 61, q = 53, and multiply them: n = 61 × 53 = 3233
  2. Compute φ = (p − 1)(q − 1) = 60 × 52 = 3120
  3. Choose e = 17 with gcd(e, φ) = 1 ⇒ public key = (n, e) = (3233, 17)
  4. Find d so that e × d leaves remainder 1 when divided by φ (using the Euclidean algorithm) ⇒ d = 2753, because 17 × 2753 = 46801 = 15 × 3120 + 1 ⇒ private key = d

Euclidean algorithm for 3120 and 17: 3120 = 183 × 17 + 9 · 17 = 1 × 9 + 8 · 9 = 1 × 8 + 1 · 8 = 8 × 1 + 0 ⇒ gcd = 1, and working back up gives d

Lock, then unlock

First turn the message into numbers, e.g. the letter “A” = 65 (its ASCII code)

🔒 Lock: 6517 mod 3233 = 2790 · anyone can do this, because n and e are public

🔑 Unlock: 27902753 mod 3233 = 65 = “A” · you need d, which only the owner has

“mod 3233” = divide by 3233 and keep the remainder · huge powers can be computed quickly by squaring again and again and taking the remainder at every step

Try it

1 · Make your own keys

2 · Lock a message, then unlock it

3 · Be the attacker: split n

You only know the public key. If you can split n into p × q, you can compute d · try dividing by one prime at a time

Why nobody else can unlock it

Why unlocking gives back the original message

Because e × d = 15 × φ + 1 ⇒ (me)d = m15φ + 1 = (mφ)15 × m · Euler’s theorem says mφ leaves remainder 1 when divided by n (when m and n share no common factor) ⇒ only m is left · when they do share a factor, you still get m back (we checked every message from 0 to 3,232)

Where it is really used

Watch the video

Long video: Encrypt · Check · Repair: The Math That Protects Your Data Every Day (Thai / English audio)
Watch on YouTube

The video loads from YouTube (youtube-nocookie.com) only after you press play. · YouTube channel: atmath (@atmathapp)

The math behind it

Good to know

Next (cryptography series, part 3): how a hash works, step by step from letters to a 64-character hash

References

Accessed 19 Nov 2026 · the numbers on this page were computed with our own script (every message from 0 to n − 1 was locked and unlocked)

← More from Explore