Write a python program to achieve Advanced Encryption Standard 128 bit key length encoding and decoding of text.
Program should be algorithm based rather than using any library function. Write both ENCODING and DECODING.
Input text
“To be, or not to be, that is the question: Whether 'tis nobler in the mind to suffer
The slings and arrows of outrageous fortune,
Or to take arms against a sea of troubles
And by opposing end them. To die—to sleep,
No more; and by a sleep to say we end
The heart-ache and the thousand natural shocks
That flesh is heir to: 'tis a consummation
Devoutly to be wish'd. To die, to sleep;
To sleep, perchance to dream—ay, there's the rub:
For in that sleep of death what dreams may come,
When we have shuffled off this mortal coil,
Must give us pause—there's the respect
That makes calamity of so long life.
When he himself might his quietus make
With this regard their currents turn awry
And lose the name of action.”
For this first we need to install Cryptography library using the pip command as follows:
pip install cryptography
Now, the code is as follows:
Note- keep input text in file 'ínputFile.txt'
from cryptography.fernet import Fernet
# Use Fernet to generate the key file.
key = Fernet.generate_key() # Store the file to disk to be accessed for en/de:crypting later.
with open('secret.key', 'wb') as new_key_file:
new_key_file.write(key)
#-------------------Encryption-----------------------
file = open('inputFile.txt')
msg = file.read()
# (Refer to Encoding types above).
msg = msg.encode()
#encrypt the message
# Instantiate the object with your key.
f = Fernet(key)# Pass your bytes type message into encrypt.
ciphertext = f.encrypt(msg)
print('\nencrypted message is as following: \n')
print(ciphertext)
#-----------------Decryption-------------------------------#
# Load the private key from a file.
with open('secret.key', 'rb') as my_private_key:
key = my_private_key.read()# Instantiate Fernet on the recip system.
f = Fernet(key)# Decrypt the message.
cleartext = f.decrypt(ciphertext)# Decode the bytes back into a string.
decrypted_message = cleartext.decode()
print("\nmassage after decryption:\n")
print(decrypted_message)
output:
Comments
Dear BLAZE V please post a new question
I need the same program but need not store the message as a file and expected output: O426pZT/JplIF8kyaiz3BDnCS5gfsMqAQS3P4ddM6ymaAlpSJBd8BNkZMJwux18ScbGM/HQn8RGNb/5hS4x81tMZ4QGerqPt3eI+qx/JJGSXM234gWesQsdJp66AoNLUCxDqXSU2IgR58rQOsCpghHJFtFG/H5Vsu2RKiYHTaSHj9mKlkNjwvZQWPzmfMXIyulOEgIK46yCFm+PG15cDHN+/JvUF5f1A2swfkzrgnoiSahrZcC6HYQTrsqOs0rA6Yasi4nCXk3+lgCK9brL0TKqXVRsA3vGBBz3lTxf1lr2esRzi0nU6ZJMIevaZRK7ADPqE7Ry1Pnpft8Q6CPBEFfZOOfxdaNccHBMo7SZMiSz68G7Tfc2mEGCQ==
Leave a comment