Skip to content

Instantly share code, notes, and snippets.

@olooney
Last active March 4, 2026 18:49
Show Gist options
  • Select an option

  • Save olooney/b50e7a2b9a2bccafeb33daaeeb8fe82c to your computer and use it in GitHub Desktop.

Select an option

Save olooney/b50e7a2b9a2bccafeb33daaeeb8fe82c to your computer and use it in GitHub Desktop.
Attempts a timing attack on the Python string comparison operator
import time
import string
def check_password(password):
return password == "abc123"
alphabet = string.ascii_letters + string.digits
def measure(pwd, n=1_000_000):
start = time.perf_counter()
for _ in range(n):
check_password(pwd)
return (time.perf_counter() - start) / n
def timing_attack(max_len=6):
guess = ""
for pos in range(max_len):
timings = []
for c in alphabet:
candidate = guess + c + "A" * (max_len - pos - 1)
t = measure(candidate)
timings.append((t, c))
timings.sort(reverse=True)
best = timings[0][1]
guess += best
print(f"Position {pos}: best='{best}' current_guess='{guess}'")
return guess
@olooney
Copy link
Author

olooney commented Mar 4, 2026

Result:

Position 0: best='e' current_guess='e'
Position 1: best='Y' current_guess='eY'
Position 2: best='h' current_guess='eYh'
Position 3: best='o' current_guess='eYho'
Position 4: best='J' current_guess='eYhoJ'
Position 5: best='m' current_guess='eYhoJm'
Recovered guess: eYhoJm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment