You can simply substitute the values I previously used for message with the contents of a file. To encrypt and decrypt files, you will need to use read and write binary when opening files. The RSA public key is stored in a file called receiver.pem. SHA256 (), label = None ) ) # Checking the results > original_message b 'encrypt me!' > message = original_message True Encrypting and Decrypting Files The following code encrypts a piece of data for a receiver we have the RSA public key of. SHA256 (), label = None ) ) > original_message = private_key. read (), backend = default_backend () ) # Encrypting and decrypting > from import hashes > from import padding > message = b 'encrypt me!' > encrypted = public_key.
read (), password = None, backend = default_backend () ) > with open ( 'public_key.pem', 'rb' ) as key_file : public_key = serialization. write ( pem ) # Reading the keys back in (for demonstration purposes) > from import default_backend > from import serialization > with open ( 'private_key.pem', 'rb' ) as key_file : private_key = serialization. SubjectPublicKeyInfo ) > with open ( 'public_key.pem', 'wb' ) as f : f. NoEncryption () ) > with open ( 'private_key.pem', 'wb' ) as f : f. PKCS8, encryption_algorithm = serialization. private_bytes ( encoding = serialization. public_key () # Storing the keys > from import serialization > pem = private_key. generate_private_key ( public_exponent = 65537, key_size = 2048, backend = default_backend () ) > public_key = private_key. # Generating a key > from import default_backend > from import rsa > private_key = rsa.