In this article we will discuss how to encrypt and decrypt files using Python.

Table of Contents


Introduction

In the evolving world of data and information transfer, security of the file contents remain to be one of the greatest concerns for companies. Some information can be password protected (emails, logins) while other information being transferred via emails or FTP lacks efficiency if protected by some keyword. This is where file encryption plays a big role and provides security and convenience sought by parties engaged in file transfers.

So what is encryption? It is a process of converting information into some form of a code to hide its true content. The only way to access the file information then is to decrypt it. The process of encryption/decryption is called cryptography.

Let’s see how we can encrypt and decrypt some of our files using Python. We will follow symmetric encryption which means using the same key to encrypt and decrypt the files.

To continue following this tutorial we will need the following Python library: cryptography.

If you don’t have it installed, please open “Command Prompt” (on Windows) and install it using the following code:


pip install cryptography

And we will also need a sample file we will be working with. Below is the sample .csv file with some data on students’ grades:


Creating a key

In our example we will be using symmetric equation:


from cryptography.fernet import Fernet

Fernet is authenticated cryptography which doesn’t allow to read and/or modify the file without a “key”.

Now, let’s create the key and save it in the same folder as our data file:


key = Fernet.generate_key()

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

If you check the directory where you Python code is located, you should see the mykey.key file. You can open it with any text editor (in my case it shows up in the local directory because I use VS Code). The file should contain one line which is a string of some order of characters.

For me it is “VlD8h2tEiJkQpKKnDNKnu8ya2fpIBMOo5oc7JKNasvk=”.


Loading a key

After we generated the encryption key, we would need to load it into our environment in order to encrypt/decrypt the files.

The following step is very simple, and requires to just open the mykey.key file and store it in local memory:


with open('mykey.key', 'rb') as mykey:
    key = mykey.read()

print(key)

And just to verify, we will see the following output:

VlD8h2tEiJkQpKKnDNKnu8ya2fpIBMOo5oc7JKNasvk=

The encryption key is now stored locally as the key variable.


Encrypt a file using Python

Now that we have the file to encrypt and the encryption key, we will now write a function to utilize these and return the encrypted file:


f = Fernet(key)

with open('grades.csv', 'rb') as original_file:
    original = original_file.read()

encrypted = f.encrypt(original)

with open ('enc_grades.csv', 'wb') as encrypted_file:
    encrypted_file.write(encrypted)

Let’s discuss what we did here:

  • We initialize the Fernet object as store is as a local variable f
  • Next, we read our original data (grades.csv file) into original
  • Then we encrypt the data using the Fernet object and store it as encrypted
  • And finally, we write it into a new .csv file called “enc_grades.csv”

You can take a look at the encrypted file here:


Decrypt a File using Python

After you encrypted the file and, for example, successfully transferred the file to another location, you will want to access it. Now, that data is in the encrypted format. The next step is to decrypt it back to the original content.

The process we will follow now is the reverse of the encryption in the previous part. Exactly the same process, but now we will go from encrypted file to decrypted file:


f = Fernet(key)

with open('enc_grades.csv', 'rb') as encrypted_file:
    encrypted = encrypted_file.read()

decrypted = f.decrypt(encrypted)

with open('dec_grades.csv', 'wb') as decrypted_file:
    decrypted_file.write(decrypted)

Let’s discuss what we did here:

  • We initialize the Fernet object as store is as a local variable f
  • Next, we read our encrypted data (enc_grades.csv file) into encrypted
  • Then we decrypt the data using the Fernet object and store it as decrypted
  • And finally, we write it into a new .csv file called “dec_grades.csv”

You can take a look at the decrypted file here:

Comparing “dec_grades.csv” with the original “grades.csv”, you will see that in fact these two have identical contents. Our encryption/decryption process was successful.


Complete object-oriented programming example

This is a bonus part where I organized everything in a more structured format:


class Encryptor():

    def key_create(self):
        key = Fernet.generate_key()
        return key

    def key_write(self, key, key_name):
        with open(key_name, 'wb') as mykey:
            mykey.write(key)

    def key_load(self, key_name):
        with open(key_name, 'rb') as mykey:
            key = mykey.read()
        return key


    def file_encrypt(self, key, original_file, encrypted_file):
        
        f = Fernet(key)

        with open(original_file, 'rb') as file:
            original = file.read()

        encrypted = f.encrypt(original)

        with open (encrypted_file, 'wb') as file:
            file.write(encrypted)

    def file_decrypt(self, key, encrypted_file, decrypted_file):
        
        f = Fernet(key)

        with open(encrypted_file, 'rb') as file:
            encrypted = file.read()

        decrypted = f.decrypt(encrypted)

        with open(decrypted_file, 'wb') as file:
            file.write(decrypted)

And this is an example of encryption/decryption using the above class:


encryptor=Encryptor()

mykey=encryptor.key_create()

encryptor.key_write(mykey, 'mykey.key')

loaded_key=encryptor.key_load('mykey.key')

encryptor.file_encrypt(loaded_key, 'grades.csv', 'enc_grades.csv')

encryptor.file_decrypt(loaded_key, 'enc_grades.csv', 'dec_grades.csv')

Conclusion

This article introduces basic symmetric file encryption and decryption using Python. We have discussed some parts of cryptography library as well as created a full process example.

Feel free to leave comments below if you have any questions or have suggestions for some edits and check out more of my Python Programming articles.