Python密码学

Python密码学模块

Python密码学模块详细操作教程
在本章中,您将详细了解Python中各种加密模块。

密码模块

它包含所有食谱和原语,并提供了Python编码的高级接口。您可以使用以下命令安装加密模块-
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-28
pip install cryptography
 PIP安装

代码

您可以使用以下代码实现加密模块-
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-28
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)

输出

上面给出的代码产生以下输出-
认证
此处提供的代码用于验证密码并创建其哈希。它还包括用于验证密码以进行身份​​验证的逻辑。
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-28
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')

输出

场景1 -如果输入了正确的密码,则可以找到以下输出-
正确的密码
场景2 -如果我们输入了错误的密码,则可以找到以下输出-
错误密码

说明

Hashlib 软件包用于在数据库中存储密码。在此程序中,使用 salt 在实现哈希函数之前在密码字符串中添加随机序列。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4