Skip to content

Instantly share code, notes, and snippets.

@cbscribe
Last active February 3, 2022 05:51
Show Gist options
  • Save cbscribe/b319bf37af54a3f308b6078163349b70 to your computer and use it in GitHub Desktop.
Save cbscribe/b319bf37af54a3f308b6078163349b70 to your computer and use it in GitHub Desktop.
Encrypt/Decrypt with RSA
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import base64
def encrypt():
keyfile = input("Public key file: ")
with open(keyfile, "r") as file:
data = file.read()
public_key = RSA.import_key(data)
cleartext = input("Cleartext: ").encode()
cipher = PKCS1_OAEP.new(public_key)
ciphertext = cipher.encrypt(cleartext)
print(base64.b64encode(ciphertext).decode())
def decrypt():
with open("private.key", "r") as file:
data = file.read()
private_key = RSA.import_key(data)
ciphertext = input("Ciphertext: ").encode()
ciphertext = base64.b64decode(ciphertext)
cipher = PKCS1_OAEP.new(private_key)
cleartext = cipher.decrypt(ciphertext)
print(cleartext.decode())
choice = input("(E)ncrypt or (D)ecrypt: ").lower()
if choice == "e":
encrypt()
elif choice == "d":
decrypt()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment