Diniz Martins

Jun 1, 20222 min

Encryption/Decryption Files

How to encrypt and decrypt files in Python

When you need to encrypt text, it is important to understand the different options you have. There are different ways to encrypt text, like using a password, using a key, and using a symmetric cipher. When you use a password, you are encrypting the text with an algorithm that uses a password to make text unreadable. A key is another way of encrypting text. A key is a piece of information that is used to encrypt and decrypt text. With a key, you must know the key in order to decrypt text. Using a symmetric cipher is another way to encrypt text. A symmetric cipher encrypts data using the same key.

Using Python and the symmetric cryptography function ciphers, you can encrypt and decrypt text files or any other files. This is one of the simplest ways to encrypt and decrypt files.Encrypting files is a difficult task, but you can use Python to do it. You will have to use a password to encrypt the file. You will also have to use a salt to encrypt the file. A salt is a random string of letters and numbers that is used to encrypt your file. Here is how you can encrypt a file using Python.

Encryption is a process that allows you to transform information, typically in a way that makes it unreadable to people who do not have the key.

Required Modules:

pip install cryptography

Cryptography is a package which provides cryptographic recipes and primitives to Python developers. The main goal is for it to be your “cryptographic standard library”. It supports Python 3.6+ and PyPy3 7.2+.

Cryptography includes both high level recipes and low level interfaces to common cryptographic algorithms such as symmetric ciphers, message digests, and key derivation functions.

Encryption:

from cryptography.fernet import Fernet
 

 
key = Fernet.generate_key()
 

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

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

 
fernet = Fernet(key)
 

 
with open('file-name.txt', 'rb') as file:
 
original = file.read()
 

 
encrypted = fernet.encrypt(original)
 

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

Decryption:

from cryptography.fernet import Fernet
 

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

 
fernet = Fernet(key)
 

 
with open('file-name.txt', 'rb') as enc_file:
 
encrypted = enc_file.read()
 

 
decrypted = fernet.decrypt(encrypted)
 

 
with open('file-name.txt', 'wb') as dec_file:
 
dec_file.write(decrypted)

file-name.txt normal file:

STENGE.info

file-name.txt encrypted:

gAAAAABilnsVpHR8TX-VlnB7JnRnawBTXjI2OvOUA3YQbumIa0wTQ06m0Fqqbm-lAtk313MD_ol6hFymm95aiOj2FK2AAe4jUQ==

filekey.key:

dAnDP2Y7lwvtrL2Q51Ug7KOTjTd4eOtkhVaWMr8PvBc=

    330
    4