Skip to content

Instantly share code, notes, and snippets.

@JafarAkhondali
Created July 31, 2020 15:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JafarAkhondali/230a7763230f45caaf181e36967084af to your computer and use it in GitHub Desktop.
Save JafarAkhondali/230a7763230f45caaf181e36967084af to your computer and use it in GitHub Desktop.
Super simple code to implement RSA encryption
#!/usr/bin/python3
"""
Sample code snippet to work with RSA encryption ( Don't use it in production :| )
"""
import libnum
def generate_keys(p, q, e):
n = p * q
phi = (p - 1) * (q - 1)
d = libnum.invmod(e, phi)
return n, d
def encrypt_text(e, n, plain_text):
plain_number = libnum.s2n(plain_text)
cipher_number = pow(plain_number, e, n)
return cipher_number
def decrypt_text(d, n, encrypted_number):
decrypted_number = pow(encrypted_number, d, n)
decrypted_text = libnum.n2s(decrypted_number)
return decrypted_text
p = 1071456887129021
q = 627715068764519
e = 65537
n, d = generate_keys(p, q, e)
plain_text = "I'm secret"
encrypted_text = encrypt_text(e, n, plain_text)
print("Encrypted text as number = {}".format(encrypted_text))
# Prints: Encrypted text as number = 661208835941892016866488406464
decrypted_text = decrypt_text(d, n, encrypted_text)
print("Decrypted text = {}".format(decrypted_text))
# Prints: Decrypted text = I'm secret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment