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
pip install

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 −

authentication

这里给出的代码用于验证密码并创建其哈希。它还包括用于验证用于身份验证目的的密码的逻辑。

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')

Output

Scenario 1 − 如果您输入了正确的密码,您可以找到以下输出 −

Scenario 1 − If you have entered a correct password, you can find the following output −

correct password

Scenario 2 − 如果我们输入错误密码,您可以找到以下输出 −

Scenario 2 − If we enter wrong password, you can find the following output −

wrong password

Explanation

Hashlib 包用于将密码存储在数据库中。在此程序中,使用了 “ salt ”,它在实现哈希函数之前向密码字符串添加随机序列。

Hashlib package is used for storing passwords in a database. In this program, salt is used which adds a random sequence to the password string before implementing the hash function.