encrypt a file with aes-256 using a password in python

To encrypt a file using AES-256 encryption with a password in Python, you can use the cryptography library. Here's an example code:

main.py
from cryptography.fernet import Fernet
import os

def encrypt_file(file_path, password):
    """
    Encrypts a file using AES-256 with a password

    Args:
        file_path (str): path of the file to be encrypted
        password (str): password to be used for encryption
    """
    with open(file_path, 'rb') as file:
        file_data = file.read()

    key = Fernet.generate_key()

    fernet = Fernet(key)

    encrypted_data = fernet.encrypt(file_data)

    with open(file_path, 'wb') as file:
        file.write(encrypted_data)

    with open('key.key', 'wb') as key_file:
        key_file.write(key)

    return os.path.abspath('key.key')
650 chars
28 lines

To encrypt a file, you can call the function like this:

main.py
encrypt_file('example.txt', 'my_password')
43 chars
2 lines

This will encrypt the file example.txt using the password my_password and save the encryption key in a new file named key.key, which will be returned by the function.

Note that this example uses the same key for all encrypted files. In a real-world scenario, you would want to use a different key for each encrypted file to improve security, and keep the keys secure by storing them in a secure location such as a vault or a key management system.

gistlibby LogSnag