Python: Encrypt and Decrypt File Using cryptography

In this tutorial, we will introduce how to use cryptography to encrypt and decrypt a file in python.

Python: Encrypt and Decrypt File Using cryptography

We have introduced how to encrypt and decrypt a string using cryptography. Here is the tutorial:

Python: Encrypt and Decrypt String Using cryptography

Encrypt and decrypt a file is similar to encrypt and decrypt a string, we also need a key.

1.Create a function to encrypt a file by key

def encrypt(filename, key):
    """
    Given a filename (str) and key (bytes), it encrypts the file and write it
    """
    f = Fernet(key)
    with open(filename, "rb") as file:
        # read all file data
        file_data = file.read()
    # encrypt data
    encrypted_data = f.encrypt(file_data)
    # write the encrypted file
    with open(filename, "wb") as file:
        file.write(encrypted_data)

Here key is created in this tuturial:

Python: Encrypt and Decrypt String Using cryptography

2.Create a function to decrypt a file by key

def decrypt(filename, key):
    """
    Given a filename (str) and key (bytes), it decrypts the file and write it
    """
    f = Fernet(key)
    with open(filename, "rb") as file:
        # read the encrypted data
        encrypted_data = file.read()
    # decrypt data
    decrypted_data = f.decrypt(encrypted_data)
    # write the original file
    with open(filename, "wb") as file:
        file.write(decrypted_data)

Then, we can start to encrypt and decrypt a file in python.

3.Encrypt a file

key = load_key()
# file name
file = "data.csv"
# encrypt it
encrypt(file, key)

4.decrypt a file

# decrypt the file
decrypt(file, key)