How To Decrypt A File In Python

In this tutorial, we will learn how to decrypt a file in Python using the cryptography library. Decrypting a file means converting the encrypted (unreadable) content back to its original readable form.

This is useful in various practical scenarios, such as ensuring the confidentiality and integrity of sensitive files shared across the network.

Step 1: Install the cryptography library

Before we start decrypting files, we need to install the cryptography library in Python. This library provides various cryptographic recipes, including file encryption and decryption. To install the library, open your command prompt, and type the following command:

Step 2: Create an encrypted file

In this tutorial, we will use a symmetric-key algorithm called Fernet to decrypt our file. Before that, we need to have an encrypted file.

Following is a sample Python program to encrypt a given file:

This script reads the content of the “test.txt” file, encrypts it, and saves the encrypted content in a new file called “encrypted_test.txt”. Make sure to save the generated key (output of the program) safely, as it will be required for decryption.

Example:

Suppose the content of the “test.txt” file is:

Hello, World!

The key used for encryption is:

b'me4Z4YjwWde_NG5v5C9D5h5f-syWtv3g54vQtNbLvHw='

Step 3: Decrypt the file

Now, we will write a Python script to decrypt the “encrypted_test.txt” file using the key generated during the encryption.

This script reads the content of the “encrypted_test.txt” file, decrypts it, and saves the decrypted content in a new file called “decrypted_test.txt”.

Full Code

Conclusion

In this tutorial, we learned how to decrypt files in Python using the cryptography library.

We created an encrypted file, then encrypted it and stored it in a new file. Finally, we used the same key to decrypt the encrypted file to get the original content.

This method can be employed in real-world applications to ensure the confidentiality and integrity of files.