How to encrypt and decrypt files using Python?

by | Jun 4, 2021 | Cryptography And Python, Encryption, Featured

output_filename will store the encrypted data.

We are reading the secret key from the file as a string. So, we would need to encode the string to get bytes. We would use the encoded bytes to initialize the Fernet.

Once the Fernet is initialized, we can read the data from the input file, encrypt the data and store it in the output file. Please note that Fernet.encrypt() method takes bytes as arguments and file.write() method takes a string as an argument. So, we need to encode and decode the data respectively.

The decryption function can be implemented in the following way:

def decrypt_file(encrypted_filename, key_filename, filename):

    with open(key_filename, "r") as key_file:
        key = key_file.read()

        fernet = Fernet(key.encode())

        with open(encrypted_filename, "r") as file:
            data = file.read()

            decrypted_text = fernet.decrypt(data.encode())

            with open(filename, "w") as output_file:
                output_file.write(decrypted_text.decode())

Here, we are taking encrypted_filename as input, reading the encrypted data from the file. We are also reading the secret key from the key file. After retrieving the key from the key file, we are decrypting the encrypted data and storing the decrypted data in another file filename. Here also we would need to use encode and decode to convert a string into bytes and bytes into a string respectively.

The complete code for encryption and decryption of file using Python is given below:

from cryptography.fernet import Fernet

def generate_private_key(key_file):

    key = Fernet.generate_key()

    with open(key_file, "w") as file:
        file.write(key.decode())


def encrypt_file(filename, key_filename, output_filename):

    with open(key_filename, "r") as key_file:
        key = key_file.read()

        fernet = Fernet(key.encode())

        with open(filename, "r") as file:
            data = file.read()

            token = fernet.encrypt(data.encode())

            with open(output_filename, "w") as output_file:
                output_file.write(token.decode())


def decrypt_file(encrypted_filename, key_filename, filename):

    with open(key_filename, "r") as key_file:
        key = key_file.read()

        fernet = Fernet(key.encode())

        with open(encrypted_filename, "r") as file:
            data = file.read()

            decrypted_text = fernet.decrypt(data.encode())

            with open(filename, "w") as output_file:
                output_file.write(decrypted_text.decode())


filename = "test.txt"
key_file = "private_key.txt"
encrypted_file = "encrypted_test.txt"
generate_private_key(key_file)
encrypt_file(filename, key_file, encrypted_file)
decrypt_file(encrypted_file, key_file, filename)

I hope this helps. However, readers who want to know more about how different cryptographic algorithms work and how they are used in various secure network protocols can refer to the book “Cryptography And Public Key Infrastructure.”

Facebooktwitterredditpinterestlinkedinmail

Calculate the pseudoinverse of a matrix using Python

What is the pseudoinverse of a matrix? We know that if A is a square matrix with full rank, then A-1 is said to be the inverse of A if the following condition holds: $latex AA^{-1}=A^{-1}A=I $ The pseudoinverse or the Moore-Penrose inverse of a matrix is a...

Cholesky decomposition using Python

What is Cholesky decomposition? A square matrix A is said to have Cholesky decomposition if it can be written as a product of a lower triangular matrix and its conjugate transpose. $latex A=LL^{*} $ If all the entries of A are real numbers, then the conjugate...

Tensor Hadamard Product using Python

In one of our previous articles, we already discussed what the Hadamard product in linear algebra is. We discussed that if A and B are two matrices of size mxn, then the Hadamard product of A and B is another mxn matrix C such that: $latex H_{i,j}=A_{i,j} \times...

Perform tensor addition and subtraction using Python

We can use numpy nd-array to create a tensor in Python. We can use the following Python code to perform tensor addition and subtraction. import numpy A = numpy.random.randint(low=1, high=10, size=(3, 3, 3)) B = numpy.random.randint(low=1, high=10, size=(3, 3, 3)) C =...

How to create a tensor using Python?

What is a tensor? A tensor is a generalization of vectors and matrices. It is easily understood as a multidimensional array. For example, in machine learning, we can organize data in an m-way array and refer it as a data tensor. Data related to images, sounds, movies,...

How to combine NumPy arrays using horizontal stack?

We can use the hstack() function from the numpy module to combine two or more NumPy arrays horizontally. For example, we can use the following Python code to combine three NumPy arrays horizontally. import numpy A = numpy.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) B =...

How to combine NumPy arrays using vertical stack?

Let’s say we have two or more NumPy arrays. We can combine these NumPy arrays vertically using the vstack() function from the numpy module. For example, we can use the following Python code to combine three NumPy arrays vertically. import numpy A = numpy.array([[1, 2,...

Singular Value Decomposition (SVD) using Python

What is Singular Value Decomposition (SVD)? Let A be an mxn rectangular matrix. Using Singular Value Decomposition (SVD), we can decompose the matrix A in the following way: $latex A_{m \times n}=U_{m \times m}S_{m \times n}V_{n \times n}^T $ Here, U is an mxm matrix....

Eigen decomposition of a square matrix using Python

Let A be a square matrix. Let’s say A has k eigenvalues λ1, λ2, ... λk. And the corresponding eigenvectors are X1, X2, ... Xk. $latex X_1=\begin{bmatrix} x_{11} \\ x_{21} \\ x_{31} \\ ... \\ x_{k1} \end{bmatrix} \\ X_2=\begin{bmatrix} x_{12} \\ x_{22} \\ x_{32} \\ ......

How to calculate eigenvalues and eigenvectors using Python?

In our previous article, we discussed what eigen values and eigenvectors of a square matrix are and how we can calculate the eigenvalues and eigenvectors of a square matrix mathematically. We discussed that if A is a square matrix, then $latex (A- \lambda I) \vec{u}=0...

Amrita Mitra

Author

Ms. Amrita Mitra is an author, who has authored the books “Cryptography And Public Key Infrastructure“, “Web Application Vulnerabilities And Prevention“, “A Guide To Cyber Security” and “Phishing: Detection, Analysis And Prevention“. She is also the founder of Asigosec Technologies, the company that owns The Security Buddy.

0 Comments

Submit a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Not a premium member yet?

Please follow the link below to buy The Security Buddy Premium Membership.

Featured Posts

Translate »