#!/usr/bin/python3 import json import base64 import asyncio from cryptography.fernet import Fernet from cryptography.hazmat.primitives.asymmetric import rsa # Generate a new RSA key pair private_key = rsa.generate_private_key() public_key = private_key.public_key() # Asynchronously encrypt and decrypt a JSON document async def encrypt_decrypt_json(json_data: dict) -> dict: # Convert the JSON data to a string json_str = json.dumps(json_data) # Encode the JSON string as bytes json_bytes = json_str.encode() # Encrypt the JSON bytes using Fernet fernet = Fernet(base64.urlsafe_b64encode(public_key.public_bytes( encoding=rsa.Encoding.DER, format=rsa.PublicFormat.SubjectPublicKeyInfo ))) encrypted_json_bytes = fernet.encrypt(json_bytes) # Decrypt the encrypted JSON bytes using Fernet decrypted_json_bytes = fernet.decrypt(encrypted_json_bytes) # Decode the decrypted JSON bytes back to a string decrypted_json_str = decrypted_json_bytes.decode() # Convert the decrypted JSON string back to a dictionary decrypted_json_data = json.loads(decrypted_json_str) return decrypted_json_data # Example usage json_data = { "user": "johnsmith", "password": "correcthorsebatterystaple" } # Asynchronously encrypt and decrypt the JSON data decrypted_json_data = asyncio.run(encrypt_decrypt_json(json_data)) # Print the decrypted JSON