Skip to content

Instantly share code, notes, and snippets.

@ProfAvery
Created October 7, 2025 15:18
Show Gist options
  • Save ProfAvery/7090ec91bcc90398248d7f4198529aac to your computer and use it in GitHub Desktop.
Save ProfAvery/7090ec91bcc90398248d7f4198529aac to your computer and use it in GitHub Desktop.
Toy RSA implementation (Understanding Cryptography, Second Edition, pp. 206-208)
#!/usr/bin/env python3
import math, random
# RSA Key Generation, p. 208
p = int(input('p? '))
q = int(input('q? '))
n = p * q
phi = (p - 1) * (q - 1)
e = random.choice([e for e in range(1, phi) if math.gcd(e, phi) == 1])
d = next(iter([d for d in range(1, phi) if ((d *e ) % phi) == 1]))
k_pub = (n, e)
k_pr = d
print(f'{k_pub = }, {k_pr = }')
# RSA Encryption (7.1), p. 206
x = int(input('x? '))
y = (x ** e) % n
print(f'{y = }')
# RSA Decryption (7.2), p. 207
print(f'({y} ** {d}) % {n} = {(y ** d) % n}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment