encrypt a file in openssl in python

To encrypt a file in OpenSSL in Python, you can use the cryptography library. Here's how:

main.py
from cryptography.fernet import Fernet

# generate a new symmetric key to encrypt the file
key = Fernet.generate_key()

# create a Fernet object with the key
fernet = Fernet(key)

# open the file to be encrypted
with open('original_file.txt', 'rb') as f:
    original_bytes = f.read()

# encrypt the bytes using the Fernet object
encrypted_bytes = fernet.encrypt(original_bytes)

# write the encrypted bytes to a new file
with open('encrypted_file.txt', 'wb') as f:
    f.write(encrypted_bytes)

# save the key used to encrypt the file to a file
with open('key.key', 'wb') as f:
    f.write(key)
596 chars
23 lines

In the above example, a new symmetric encryption key is generated using Fernet.generate_key(). This key is used to create a Fernet object, which is used to encrypt the contents of the original file. The encrypted bytes are then written to a new file, and the encryption key is saved to a separate file.

To decrypt the encrypted file, you can use the same key and Fernet object:

main.py
from cryptography.fernet import Fernet

# read the encryption key from a file
with open('key.key', 'rb') as f:
    key = f.read()

# create a Fernet object with the key
fernet = Fernet(key)

# open the encrypted file
with open('encrypted_file.txt', 'rb') as f:
    encrypted_bytes = f.read()

# decrypt the bytes using the Fernet object
decrypted_bytes = fernet.decrypt(encrypted_bytes)

# write the decrypted bytes to a new file
with open('decrypted_file.txt', 'wb') as f:
    f.write(decrypted_bytes)
503 chars
20 lines

In the above code, the encryption key is read from the file that was saved earlier. The Fernet object is created with the key, and then used to decrypt the contents of the encrypted file. The decrypted bytes are then written to a new file.

gistlibby LogSnag