Skip to content

Instantly share code, notes, and snippets.

@Orbifold
Created July 20, 2018 17:11
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Orbifold/74997a786237bc74af6df2fdc2a51d9a to your computer and use it in GitHub Desktop.
Save Orbifold/74997a786237bc74af6df2fdc2a51d9a to your computer and use it in GitHub Desktop.
RSA mechanics with pycryptodome
#========================================
# create public and private keys
#========================================
from Crypto.PublicKey import RSA
key = RSA.generate(2048)
private_key = key.exportKey()
with open("./private.pem", "wb") as f:
f.write(private_key)
public_key = key.publickey().exportKey()
with open("receiver.pem", "wb") as f:
f.write(public_key)
#========================================
# encrypt
#========================================
from Crypto.PublicKey import RSA
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES, PKCS1_OAEP
data = "Time is a thief.".encode("utf-8")
with open("encrypted_data.bin", "wb") as f:
recipient_key = RSA.import_key(open("./receiver.pem").read())
session_key = get_random_bytes(16)
# Encrypt the session key with the public RSA key
cipher_rsa = PKCS1_OAEP.new(recipient_key)
enc_session_key = cipher_rsa.encrypt(session_key)
# Encrypt the data with the AES session key
cipher_aes = AES.new(session_key, AES.MODE_EAX)
ciphertext, tag = cipher_aes.encrypt_and_digest(data)
[ f.write(x) for x in (enc_session_key, cipher_aes.nonce, tag, ciphertext) ]
#========================================
# decrypt
#========================================
from Crypto.PublicKey import RSA
from Crypto.Cipher import AES, PKCS1_OAEP
with open("encrypted_data.bin", "rb") as f:
private_key = RSA.import_key(open("private.pem").read())
enc_session_key, nonce, tag, ciphertext = \
[ f.read(x) for x in (private_key.size_in_bytes(), 16, 16, -1) ]
# Decrypt the session key with the private RSA key
cipher_rsa = PKCS1_OAEP.new(private_key)
session_key = cipher_rsa.decrypt(enc_session_key)
# Decrypt the data with the AES session key
cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)
data = cipher_aes.decrypt_and_verify(ciphertext, tag)
print(data.decode("utf-8"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment