In this chapter, you will learn more about the various cryptographic modules in Python.
cryptographic module
It contains all recipes and primitives and provides an advanced coding interface in Python. You can install the encryption module using the following command :
pip install cryptography
coding
You can implement the encryption module using the following code :
from import Fernet key = Fernet.generate_key() cipher_suite = Fernet(key) cipher_text = cipher_suite.encrypt("This example is used to demonstrate cryptography module") plain_text = cipher_suite.decrypt(cipher_text)
exports
The code given above produces the following output :.
The code given here is used to validate the password and create its hash value.
It also includes logic for verifying passwords for authentication purposes.
import uuid import hashlib def hash_password(password): # uuid is used to generate a random number of the specified password salt = uuid.uuid4().hex return hashlib.sha256(() + ()).hexdigest() + ':' + salt def check_password(hashed_password, user_password): password, salt = hashed_password.split(':') return password == hashlib.sha256(() + user_password.encode()).hexdigest() new_pass = input('Please enter a password: ') hashed_password = hash_password(new_pass) print('The string to store in the db is: ' + hashed_password) old_pass = input('Now please enter the password again to check: ') if check_password(hashed_password, old_pass): print('You entered the right password') else: print('Passwords do not match')
exports
Scenario 1 : If you have entered the correct password, you can find the following outputs :
Scenario 2 : If we enter the wrong password, you can find the following outputs :
clarification
The Hashlib package is used to store passwords in a database. In this program, salt is used to add a random sequence to the password string before implementing the hash function.
Above is the details of python cryptography various encryption module tutorial, more information about Python cryptography encryption module please pay attention to my other related articles!