Skip to content

Instantly share code, notes, and snippets.

@gunvirranu
Created November 16, 2021 09:07
Show Gist options
  • Save gunvirranu/823d0fe1e67e790a6ac7cf9a537758ca to your computer and use it in GitHub Desktop.
Save gunvirranu/823d0fe1e67e790a6ac7cf9a537758ca to your computer and use it in GitHub Desktop.
A small Python snippet demonstrating how RSA works.
# Generating some parameters and the public-private key-pair
p, q = 997, 991 # Two "big" secret prime numbers
N = p * q # This is public
phi = (p - 1) * (q - 1) # This *must* be private!
public = 65537 # Choose some prime that's not a factor of `phi`
assert phi % public != 0
# Inverse of `e` mod `phi` found using Euclidean algo
# The important part is that you *need* `phi` to calculate this
private = 919313
assert (private * public) % phi == 1 # Make sure it's the inverse
# Some actual encryption and decryption
to_encrypt = b"here is some plain-text"
print(f"{to_encrypt=}")
encrypted = [pow(x, public, N) for x in to_encrypt]
print(f"{encrypted[:4]=}...") # Looks pretty encrypted :P
decrypted = bytes(pow(x, private, N) for x in encrypted)
print(f"{decrypted=}")
assert to_encrypt == decrypted # It works!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment