13] Python program to encrypt and decrypt files.
The Program:
# import required module
from [Link] import Fernet
key = Fernet.generate_key()
# Generate a key and save it in the same folder
with open('[Link]', 'wb') as mykey:
[Link](key)
# To see the generated key
with open('[Link]', 'rb') as mykey:
key = [Link]()
print("The generated key: ",key)
# encrypt file
f = Fernet(key)
with open('[Link]', 'rb') as original_file:
original = original_file.read()
encrypted = [Link](original)
with open ('encrypted_tips.txt', 'wb') as encrypted_file:
encrypted_file.write(encrypted)
1|Page Cyber Security Lab Manual – KAMALAKAR HEGDE
# To see encrypted file contents
file1 = open("encrypted_tips.txt","r+")
print("The encrypted file content ")
print([Link]())
print()
#decrypt file
with open('encrypted_tips.txt', 'rb') as encrypted_file:
encrypted = encrypted_file.read()
decrypted = [Link](encrypted)
with open('decrypted_tips.txt', 'wb') as decrypted_file:
decrypted_file.write(decrypted)
file1 = open("decrypted_tips.txt","r+")
print("The decrypted file content ")
print([Link]())
print()
OUTPUT:
The generated key: b'w-t0UuSRazj6fZLR0ZA2UFfWHGo6lBGriCoDwChreEU='
The encrypted file content
gAAAAABlcpnUdEBoWdj--fmzEKeEGwz6pvrtcAJh-
25aIWuPNjQ3zddHr3ZE1SORGMX3OOfaynplPsSCF-
TwcUrEDwUaTBMTOswrn31umMVSS_NpP9y2WIhug4lgKNJJ1cPs-
2|Page Cyber Security Lab Manual – KAMALAKAR HEGDE
WJjU0chmmSN1JfOrjgUIwDcELC1JeF6dwECWRMPYtArWsyaVDyDVbkiG4LDiIFsrz2
ciUI-LZGzX_RAWBgrl3aKjrHEnYfNOZNvxesUu_v87GyQBfeeR5iufkt82Xj0JyEXPFok
The decrypted file content (same as [Link] file)
user1,Pas1$Ku1
user2,password
user3,password123
user4,password123$
user5,Password6#(%
user6,Germany#12
user7,USA12^$#
user8,England0#
Fernet
Fernet is a symmetric encryption technique available to users in the cryptography module in
Python that makes it easy to encrypt and decrypt text and provides an easy interface for
beginners in cryptography.
Fernet uses the Advanced Encryption Standard (AES) algorithm to encode and decode
messages. AES is a highly secure, widely used and popular cryptography algorithm used by
developers.
The cipher texts of Fernet are URL-safe, which means, we can send the cipher texts through the
World Wide Web, making data transmission more convenient.
Fernet generates a highly secure alphanumeric key using a random number generator. It is a
32-byte long key, making it highly resistant to brute-force attacks.
It also supports key rotation, that is, the ability to generate new keys and replace the old keys
all the time.
Fernet supports time stamping and serialization of data to be attached along with the key. This
is done in order to improve the security of the key since attaching a timestamp to the key will
ensure that it has limited validity.
3|Page Cyber Security Lab Manual – KAMALAKAR HEGDE