Skip to content

Instantly share code, notes, and snippets.

@RichardEllicott
Created May 2, 2018 12:31
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 RichardEllicott/2e2eb0acea3ee15bf1a3691d86a35244 to your computer and use it in GitHub Desktop.
Save RichardEllicott/2e2eb0acea3ee15bf1a3691d86a35244 to your computer and use it in GitHub Desktop.
from __future__ import absolute_import, division, print_function
from Cryptodome.PublicKey import RSA
from Cryptodome.Random import get_random_bytes
from Cryptodome.Cipher import AES, PKCS1_OAEP
data = "I met aliens in UFO. Here is the map.".encode("utf-8")
recipient_key = RSA.import_key(open("shroomery_encrypt_key_cache/1024.public.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)
# [ open("encrypted_data.bin", "wb").write(x) for x in (enc_session_key, cipher_aes.nonce, tag, ciphertext) ] # ORGINAL EXAMPLE
with open('encrypted_data.bin', 'wb') as f: #REPLACEMENT
f.write(enc_session_key+cipher_aes.nonce+tag+ ciphertext)
from Cryptodome.PublicKey import RSA
from Cryptodome.Cipher import AES, PKCS1_OAEP
private_key = RSA.import_key(open("shroomery_encrypt_key_cache/1024.private.pem").read())
# enc_session_key, nonce, tag, ciphertext = [ open("encrypted_data.bin", 'rb').read(x) for x in (private_key.size_in_bytes(), 16, 16, -1) ] #replace neat thing
full_packet_as_string = open('encrypted_data.bin', 'rb').read() #looks crap but works
enc_session_key = full_packet_as_string[: private_key.size_in_bytes()]
nonce = full_packet_as_string[private_key.size_in_bytes(): private_key.size_in_bytes() + 16]
tag = full_packet_as_string[private_key.size_in_bytes() + 16: private_key.size_in_bytes() + 32]
ciphertext = full_packet_as_string[private_key.size_in_bytes() + 32:]
print('enc_session_key:',enc_session_key.encode('hex'))
# 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