Skip to content

Instantly share code, notes, and snippets.

@aalmazan
Created August 18, 2023 00:17
Show Gist options
  • Save aalmazan/d987f8fefb721cdd2584995a281bc146 to your computer and use it in GitHub Desktop.
Save aalmazan/d987f8fefb721cdd2584995a281bc146 to your computer and use it in GitHub Desktop.
import base64
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
IVLength = 16
AESKeyLength = 32
def decrypt_rsa(private_key, message):
index = message.index(b":")
enc_aes_key = message[:index]
encrypted_message = message[index + 1:]
aes_key = private_key.decrypt(
base64.b64decode(enc_aes_key),
padding=padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
label=None
),
)
return decrypt_aes(aes_key, encrypted_message)
def decrypt_aes(aes_key, encrypted_message):
iv, ciphertext = encrypted_message.split(b":")
cipher = Cipher(
algorithms.AES(bytes.fromhex(aes_key.decode())),
modes.CBC(bytes.fromhex(iv.decode()))
)
decryptor = cipher.decryptor()
decrypted_data = decryptor.update(bytes.fromhex(ciphertext.decode())) + decryptor.finalize()
return decrypted_data
def main():
encrypted_message = b"message here"
with open("key.pem", "rb") as private_key:
loaded_key = serialization.load_pem_private_key(private_key.read(), password=None)
decrypted_data = decrypt_rsa(loaded_key, encrypted_message)
print(decrypted_data.decode())
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment