Cryptography With Python 简明教程
Python Modules of Cryptography
在本章中,您将详细了解 Python 中加密的各种模块。
In this chapter, you will learn in detail about various modules of cryptography in Python.
Cryptography Module
它包括所有配方和原语,并提供 Python 中的高级编码接口。您可以使用以下命令安装加密模块 −
It includes all the recipes and primitives, and provides a high level interface of coding in Python. You can install cryptography module using the following command −
pip install cryptography

Code
您可以使用以下代码实现加密模块 −
You can use the following code to implement the cryptography module −
from cryptography.fernet 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)
Output
上面给出的代码生成以下输出了 −
The code given above produces the following output −

这里给出的代码用于验证密码并创建其哈希。它还包括用于验证用于身份验证目的的密码的逻辑。
The code given here is used to verify the password and creating its hash. It also includes logic for verifying the password for authentication purpose.
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(salt.encode() + password.encode()).hexdigest() + ':' + salt
def check_password(hashed_password, user_password):
password, salt = hashed_password.split(':')
return password == hashlib.sha256(salt.encode() + 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')