How to Encrypt and Decrypt Files in Python?

Posted in /  

How to Encrypt and Decrypt Files in Python?
vinaykhatri

Vinay Khatri
Last updated on May 30, 2024

    In Encryption, we encode the data information that presents in plain text to an alternative ciphertext that is impossible to read and make sense of it. We generally use encryption to keep some data secret so that only authorized people can see the actual data.

    Although there are various encryption algorithms out there, in this tutorial, we will be using Symmetric Encryption in which we require the same key to encrypt and decrypt the data.

    The advantage of symmetric encryption is we only need to create one key that will be shared between the authorized people, and only those people can decrypt the encoded file.

    In this Python tutorial, I will walk you through the Python program to encrypt and decrypt a text file using the cryptography library.

    Install the Python cryptography Library

    cryptography is an open-source Python library that contains many cryptographic algorithms to cipher the data. In this tutorial, we will be using this library for Symmetric ciphering and generating keys to encrypt and decrypt a text file.

    To download the Python cryptography library, run the following pip install command on your terminal.

    pip install cryptography

    Encrypt a Text file in Python?

    Let's start with importing the Fernet module from the cryptography library.

    from cryptography.fernet import Fernet

    Now generate the key and save or write it locally using Python file handling.

    #generate a key
    key = Fernet.generate_key()
    
    #save the key locally
    with open("my_key.key", "wb") as key_data:
        key_data.write(key)

    The generate_key() function will generate random bytes keys. And using Python file handling, I wrote the key in binary format and saved it locally. We have saved the key locally because we require the same key to decrypt the encrypted file. Now let's read the data.txt file which we are supposed to encrypt.

    #get data.txt file
    with open("data.txt", "r") as file:
        data = file.read()
    
    print("The actual Data before Encryption:\n ", data)

    Before we encrypt the data, let's encode the string data with UTF-8 using the string encode() function. Because the encrypt function of the Fernet object requires byte encoded data.

    #convert data into bytes
    byte_data = data.encode()

    Now we need to initialize the Fernet object using the key we just generated.

    #initialize Fernet object
    f= Fernet(key)

    Now let's encrypt the byte_data using the encrypt() function.

    #encrypt bytes data
    encrypt_data = f.encrypt(byte_data)

    The Fernet object f encrypt() function will encrypt the byte_data based on the key . Now write the encrypt_data to the existing data.txt file.

    #write encoded data into data.txt
    with open("data.txt", "wb") as file:
        file.write(encrypt_data)
    
    print("The Encrypted data is\n: ", encrypt_data)

    As you can see that I wrote them excrypt_data into the data.txt file with write binary mode. Now put the code together and execute.

    Python Program to Encrypt File

    from cryptography.fernet import Fernet
    
    #generate a key
    key = Fernet.generate_key()
    
    #save the key locally
    with open("my_key.key", "wb") as key_data:
        key_data.write(key)
    
    
    #get data.txt file
    with open("data.txt", "r") as file:
        data = file.read()
    
    print("The actual Data before Encryption:\n ", data)
    
    #convert data into bytes
    byte_data = data.encode()
    
    #initialize Fernet object
    f= Fernet(key)
    
    #encrypt bytes data
    encrypt_data = f.encrypt(byte_data)
    
    #write encoded data into data.txt
    with open("data.txt", "wb") as file:
        file.write(encrypt_data)
    
    print("\nThe Encrypted data is:\n ", encrypt_data)

    Output

    The actual Data before Encryption:
    Step up and begin your game and if you are already in the journey, and enter the league of Tech Pros!
    Read tutorials, try examples, learn to code. Do whatever it takes to lead the tech world in this era!
    
    The Encrypted data is:
    b'gAAAAABgJmwywqYFtqW-pXUe9pwIx0KnZjLYkuPXEf2nb7SZzan_aTOtxMmXpw2viA96lgsztjzu3_LqKdWNwbOmIZNZWmpc4g1u3P0eeC-eMxiqSZGHFBEbR3Ekty8ccgNcVQXz1aw6cP1QodkoSU2fBbyfUTUekBWuSaCh53adGqJ28doyfTR5O-C9-IGU08I-PlYYd0nWBnqvrSMWJGlgoOnH2qMjUjMmn6wdy1aGAww_iT39bA3aPBzP93hBxGzZ9XIL-Qgfl5gReAQ7ts2UikShppwbvDCGmA3LRx2RwP0EKgk3n1PukkTzvefdEjmWXtAiJJ5vsEJ4B8AFKOqoigKKbcK9cw=='

    From the output, you can see that the Actual data has been encrypted. Now, if you will check your Python script directory there, you will see a new file my_key.key that contains the key data for the encrypted file. In the next program, I will use the my_key.key key to decrypt the encrypted file.

    Decrypt a Text file in Python?

    Now let's decrypt the data.txt file using the key that we created and saved in the above file. Let's begin with importing the Fernet module from the cryptography library.

    from cryptography.fernet import Fernet

    Now let's load the encrypted data.txt and my_key.key data, and print the Encrypted data.

    #load the key
    with open("my_key.key" ,"rb") as my_key:
        key = my_key.read()
    
    #load encrypted file
    with open("data.txt", "rb") as file:
        encryp_data = file.read()
    
    print("The Encrypted Data is:\n", encryp_data)

    Now initialize the Fernet object with the loaded key .

    #initialize Fernet object with key
    f = Fernet(key)

    Now decrypt the encrypted data using the Fernet object decrypt() function.

    #decrypt data
    decrypt_data = f.decrypt(encryp_data)
    
    print("\nThe Actual Data is:\n", decrypt_data.decode())

    The decode() is the string function that decodes the encoded UTF-8 string. Now, put all the code together and execute

    Python Program to decrypt a file

    from cryptography.fernet import Fernet
    
    #load the key
    with open("my_key.key" ,"rb") as my_key:
        key = my_key.read()
    
    #load encrypted file
    with open("data.txt", "rb") as file:
        encryp_data = file.read()
    
    print("The Encrypted Data is:\n", encryp_data)
    
    #initialize Fernet object with key
    f = Fernet(key)
    
    #decrypt data
    decrypt_data = f.decrypt(encryp_data)
    
    print("\nThe Actual Data is:\n", decrypt_data.decode())

    Output

    The Encrypted Data is:
    b'gAAAAABgJmwywqYFtqW-pXUe9pwIx0KnZjLYkuPXEf2nb7SZzan_aTOtxMmXpw2viA96lgsztjzu3_LqKdWNwbOmIZNZWmpc4g1u3P0eeC-eMxiqSZGHFBEbR3Ekty8ccgNcVQXz1aw6cP1QodkoSU2fBbyfUTUekBWuSaCh53adGqJ28doyfTR5O-C9-IGU08I-PlYYd0nWBnqvrSMWJGlgoOnH2qMjUjMmn6wdy1aGAww_iT39bA3aPBzP93hBxGzZ9XIL-Qgfl5gReAQ7ts2UikShppwbvDCGmA3LRx2RwP0EKgk3n1PukkTzvefdEjmWXtAiJJ5vsEJ4B8AFKOqoigKKbcK9cw=='
    
    The Actual Data is:
    Step up and begin your game and if you are already in the journey, and enter the league of Tech Pros!

    Conclusion

    In this Python tutorial, we learned "How to Encrypt and Decrypt files in Python?". You can also encrypt and decrypt a file based on a simple and logical algorithm. But with the help of the Python cryptography library, you do not need to implement an algorithm of your own. You can simply use its generate_key(), encrypt, and decrypt function for file ciphering.

    People are also reading:

    Leave a Comment on this Post

    0 Comments