Encrypt And Decrypt files Using Python
In this tutorial, we will learn how to Encrypt and Decrypt files using Python. Before going to encrypting and decrypting files first let’s discuss a few points about encryption and Decryption.
What is Encryption
The process of converting plain text to cipher text is called encryption. It is also called encoding. The only way to access the file’s information then is to decrypt it.
What is Decryption
The process of converting encryption text or cipher text into its plain text is called decryption. It is also called decoding.
The process of encryption and decryption is called cryptography. Python has a cryptography module used to encrypt and decrypt files in just a few lines. That can be installed by using
pip install cryptography
You can find the file that used for this example here
Encrypt and Decrypt files
1. Generate a key and save it in the same folder as the encryption and decryption script. A key is required for encryption and decryption of the file.
key = Fernet.generate_key() with open('mykey.key', 'wb') as mykey: mykey.write(key)
To see the generated key
with open('mykey.key', 'rb') as mykey: key = mykey.read() print("The generated key: ",key)
The generated key: b'N9nTz67LTqon6OqfaWl2fy_BNQcb6XGFiX-74Ft10LE='
Encrypting a file
1. Firstly initialize the Fernet object as a local variable f.
2. Read the file that needs to be encrypted.
3. Encrypt the file using the Fernet object and store it.
4. Finally, write it in a new file.
f = Fernet(key) with open('tips.txt', 'rb') as original_file: original = original_file.read() encrypted = f.encrypt(original) with open ('encrypted_tips.txt', 'wb') as encrypted_file: encrypted_file.write(encrypted)
You can take a look at the encrypted file here
Decrypting a file
1. Initialize the Fernet object as local variable f.
2. Read the encrypted file into encrypted.
3. Then decrypt the file using the Fernet object.
4. Finally, write in a new file.
with open('encrypted_tips.txt', 'rb') as encrypted_file: encrypted = encrypted_file.read() decrypted = f.decrypt(encrypted) with open('decrypted_tips.txt', 'wb') as decrypted_file: decrypted_file.write(decrypted)
You can take a look at the decrypted file here
Leave a Reply