Timing Attacks on RSA in Python
In case you haven't read former 2 articles on this topic, below are the links: Side-channel attacks The first 2 articles focused mainly on the idea and implementation of RSA. As such they left out a relevant topic in modern encryption. Side-channel attacks take advantage of data we'd usually…
Your RSA code can be mathematically correct and still hand the key to an attacker — not through the math, but through the clock. Timing attacks exploit the fact that operations take different amounts of time, and on a remote server the attacker never touches your machine.
The leak, demonstrated
Paul Kocher's observation: if reduction runs faster when a < b than when a ≥ b, decryption time leaks the private exponent's bits. Watch a textbook square-and-multiply:
def modpow(b, e, n):
tst, siz = 1, 0
while e >= tst:
tst <<= 1
siz += 1
siz -= 1
r = 1
for i in range(siz, -1, -1):
r = (r * r) % n
if (e >> i) & 1:
r = (r * b) % n # the leak: this line runs only when bit i is 1
return rWhether the conditional multiply fires depends on bit i. Craft two messages where one forces it and one skips it, measure the time difference, and a bit of the key falls out. Repeat per bit — a few thousand measurements reconstruct the whole exponent.
Measuring it yourself
import time
def timed(b, e, n, trials=50):
t0 = time.perf_counter_ns()
for _ in range(trials):
modpow(b, e, n)
return (time.perf_counter_ns() - t0) / trialsEven on a laptop you'll see the variance. Network jitter blurs it — which is why real attacks take many samples, not one.
What real defenses look like
Constant-time code: no data-dependent branches, no early exits — Montgomery multiplication makes every reduction take the same path. Blinding adds a random factor before decryption and removes it after, so the measured time decorrelates from the key. Neither is a patch you bolt on; the code is designed so timing carries nothing.
The actual lesson
Never deploy homegrown RSA — not because the math is hard (pow(b, e, n) is one call) but because every shortcut that makes crypto fast also makes it leak. Learn on code you never ship.
$ tail -f /forums
Discussion
Comments live on the community forums — sign in there to reply.