开发手册 欢迎您!
软件开发者资料库

密码学的Python模块

使用Python进行密码学习 - Python密码学模块 - 从简单易学的步骤学习使用Python进行密码学从基本到高级概念,包括概述,双强度加密,Python概述和安装,反向密码,凯撒密码,ROT13算法,转置密码,加密转置密码的解密,转置密码的解密,文件加密,文件解密,Base64编码和解码,XOR处理,乘法密码,仿射密码,黑客单字母密码,简单替换密码,简单替换密码测试,简单替换密码解密,密码学的Python模块,了解Vignere密码,实现Vignere密码,一次填充密码,一次填充密码的实现,对称和非对称密码,理解RSA算法,创建RSA密钥,RSA密码加密,RSA密码解密,黑客攻击RSA密码。

在本章中,您将详细了解Python中各种加密模块.

加密模块

它包含所有配方和基元,并在Python中提供高级编码接口.您可以使用以下命令安装加密模块 :

  pip install cryptography


PIP Install

代码

您可以使用以下代码实现加密模块 :

from cryptography.fernet import Fernetkey = 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)

输出

上面给出的代码产生以下输出 :

Authentication

此处给出的代码用于验证密码并创建其哈希值.它还包括用于验证密码以进行身份验证的逻辑.

import uuidimport hashlibdef 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() + ':' + saltdef 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 ,在实现哈希函数之前,将随机序列添加到密码字符串中.