In: Computer Science
how can we use cryptography libraries in Python
For using cryptographic modules, we need to install it first. It includes all the recipes and primitives, and provides a high level interface of coding in Python. We can install cryptography module using the following command at the command prompt. Make sure that the command prompt should be be opened as "Run as administrator". Go to the folder in which pip tool resides which comes along with the basic installation of Python.
For me it is C:\Python37-32\Scripts\ - Here type the command pip install cryptography and press enter.
The screenshot for the installation is pasted below.
Following shows an example Python program which encrypts a string if it contains only digits,letters, comma and spaces.
from cryptography.fernet import
Fernet
key = Fernet.generate_key()
#Reading a string for encryption
str=input("Enter a string for encryption:")
#Checking whether string contains only digits,letters,comma and
spaces
for char in str:
if char in "0123456789
.,abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ":
flag=0
else:
flag=1
break
if flag==1:
print("Invalid string.Try again")
else:
#Generating key for encryption
message = str.encode()
f = Fernet(key)
#Encryption
encrypted = f.encrypt(message)
#printing encrypted message
print("Encrypted message:",encrypted)
#Decryption
decrypted = f.decrypt(encrypted)
#printing decrypted message
print("Decrypted message:",decrypted)
Python code in IDLE pasted for better understanding of the indent
Output