Skip to content

Instantly share code, notes, and snippets.

@makkes
Last active June 3, 2024 08:38
Show Gist options
  • Save makkes/afc4be311a4ac8c720fc45e104596542 to your computer and use it in GitHub Desktop.
Save makkes/afc4be311a4ac8c720fc45e104596542 to your computer and use it in GitHub Desktop.
Decrypt AES encrypted data using a key in turn encrypted using RSA 256
from Crypto.Cipher import AES
from Crypto.PublicKey import RSA
from Crypto.Cipher import AES, PKCS1_v1_5
from Crypto.Random import get_random_bytes
import base64
import sys
import zlib
def decrypt(session_key, privkey_fname, payload_fname, out_fname):
enc_session_key = base64.b64decode(session_key)
private_key = RSA.import_key(open(privkey_fname).read(), "p")
# Decrypt the session key with the private RSA key
sentinel = get_random_bytes(16)
cipher_rsa = PKCS1_v1_5.new(private_key)
session_key = cipher_rsa.decrypt(enc_session_key, sentinel)
if session_key == sentinel:
raise Exception("unable to decrypt session key")
# Load the encrypted file into memory
with open(payload_fname, 'rb') as f:
nonce = f.read(12)
ciphertext = f.read()
tag = ciphertext[len(ciphertext)-16:]
# Decrypt the data with the AES session key
cipher_aes = AES.new(session_key, AES.MODE_GCM, nonce)
data = zlib.decompress(cipher_aes.decrypt_and_verify(
ciphertext[:len(ciphertext)-16], tag))
with open(out_fname, 'wb') as f:
f.write(data)
if __name__ == '__main__':
session_key = sys.argv[1]
privkey_fname = sys.argv[2]
payload_fname = sys.argv[3]
out_fname = payload_fname + '.dec'
if len(sys.argv) >= 5:
out_fname = sys.argv[4]
decrypt(session_key, privkey_fname, payload_fname, out_fname)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment