Python的cryptography库介绍

2024-01-07 12:20
文章标签 python 介绍 cryptography

本文主要是介绍Python的cryptography库介绍,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

      Python的cryptography是密码库,源码地址为:https://github.com/pyca/cryptography,最新发布版本为41.0.7,license为Apache 2.0/BSD 3,它支持在Windows、Linux、macOS上使用。如果通过源码编译,需要依赖OpenSSL。Python版本需要为3.7+.

      通过pip安装,执行:

pip install cryptography

      以下是对称加密AES测试code:

      关于OpenSSL AES GCM的介绍可以参考:https://blog.csdn.net/fengbingchun/article/details/106113185

import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modesdef aes_gcm_encrypt(plain_text, key, iv, aad):# Construct an AES-GCM Cipher object with the given key and ivencryptor = Cipher(algorithms.AES(key), modes.GCM(iv),).encryptor()# associated_data will be authenticated but not encrypted, it must also be passed in on decryptionencryptor.authenticate_additional_data(aad)# Encrypt the plaintext and get the associated ciphertext. GCM does not require paddingcipher_text = encryptor.update(plain_text) + encryptor.finalize()return (cipher_text, encryptor.tag)def aes_gcm_decrypt(cipher_test, key, iv, aad, tag):# Construct a Cipher object, with the key, iv, and additionally the GCM tag used for authenticating the messagedecryptor = Cipher(algorithms.AES(key), modes.GCM(iv, tag),).decryptor()# We put associated_data back in or the tag will fail to verify when we finalize the decryptordecryptor.authenticate_additional_data(aad)# Decryption gets us the authenticated plaintext. If the tag does not match an InvalidTag exception will be raisedreturn decryptor.update(cipher_test) + decryptor.finalize()if __name__ == "__main__":# reference: https://cryptography.io/en/latest/hazmat/primitives/symmetric-encryption/plain_test = b"https://github.com/fengbingchun"key = os.urandom(32) # bytes, secret key: either 128, 192, or 256 bits longiv = os.urandom(12) # bytes, initialisation vectoraad = os.urandom(16) # authenticated encryption with additional dataprint("key: {}\niv: {}\naad: {}\n".format(key, iv, aad))cipher_text, tag = aes_gcm_encrypt(plain_test, key, iv, aad)print("cipher text: {}\ntag: {}\n".format(cipher_text, tag))plain_test2 = aes_gcm_decrypt(cipher_text, key, iv, aad, tag)print("before encryption, plaintext:{}\nafter  decryption, plaintext:{}".format(plain_test, plain_test2))if plain_test != plain_test2:print("Error: the decrypted content does not match the original plaintext")raiseprint("test finish")

      执行结果如下图所示:

      以下是非对称加密RSA测试code:
      关于OpenSSL RSA的介绍可以参考:https://blog.csdn.net/fengbingchun/article/details/43638013

      通过openssl执行文件生成rsa公钥-私钥对文件rsa_private.pem,密钥对长度为3072,执行如下命令:

openssl.exe genrsa -out rsa_private.pem 3072
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import serialization, hashesdef rsa_public_key_encrypt(plain_text, public_key):return public_key.encrypt(plain_text,padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),algorithm=hashes.SHA256(),label=None))def rsa_private_key_decrypt(cipher_test, private_key):return private_key.decrypt(cipher_test,padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),algorithm=hashes.SHA256(),label=None))if __name__ == "__main__":# reference: https://cryptography.io/en/latest/hazmat/primitives/asymmetric/rsa/plain_test = b"https://blog.csdn.net/fengbingchun/"with open("test_data/rsa_private.pem", "rb") as key_file:private_key = serialization.load_pem_private_key(key_file.read(), password=None,)pem = private_key.private_bytes(encoding=serialization.Encoding.PEM,format=serialization.PrivateFormat.TraditionalOpenSSL,encryption_algorithm=serialization.NoEncryption())#print("private key: {}\n".format(pem.splitlines()))public_key = private_key.public_key()pem = public_key.public_bytes(encoding=serialization.Encoding.PEM,format=serialization.PublicFormat.SubjectPublicKeyInfo)#print("public key: {}\n".format(pem.splitlines()))cipher_text = rsa_public_key_encrypt(plain_test, public_key)print("cipher text:{}\n".format(cipher_text))plain_test2 = rsa_private_key_decrypt(cipher_text, private_key)print("before encryption, plaintext:{}\nafter  decryption, plaintext:{}".format(plain_test, plain_test2))if plain_test != plain_test2:print("Error: the decrypted content does not match the original plaintext")raiseprint("test finish")

      执行结果如下图所示:

      GitHub:https://github.com/fengbingchun/Python_Test

这篇关于Python的cryptography库介绍的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/579900

相关文章

Python实现终端清屏的几种方式详解

《Python实现终端清屏的几种方式详解》在使用Python进行终端交互式编程时,我们经常需要清空当前终端屏幕的内容,本文为大家整理了几种常见的实现方法,有需要的小伙伴可以参考下... 目录方法一:使用 `os` 模块调用系统命令方法二:使用 `subprocess` 模块执行命令方法三:打印多个换行符模拟

Python实现MQTT通信的示例代码

《Python实现MQTT通信的示例代码》本文主要介绍了Python实现MQTT通信的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 安装paho-mqtt库‌2. 搭建MQTT代理服务器(Broker)‌‌3. pytho

基于Python开发一个图像水印批量添加工具

《基于Python开发一个图像水印批量添加工具》在当今数字化内容爆炸式增长的时代,图像版权保护已成为创作者和企业的核心需求,本方案将详细介绍一个基于PythonPIL库的工业级图像水印解决方案,有需要... 目录一、系统架构设计1.1 整体处理流程1.2 类结构设计(扩展版本)二、核心算法深入解析2.1 自

从入门到进阶讲解Python自动化Playwright实战指南

《从入门到进阶讲解Python自动化Playwright实战指南》Playwright是针对Python语言的纯自动化工具,它可以通过单个API自动执行Chromium,Firefox和WebKit... 目录Playwright 简介核心优势安装步骤观点与案例结合Playwright 核心功能从零开始学习

Python 字典 (Dictionary)使用详解

《Python字典(Dictionary)使用详解》字典是python中最重要,最常用的数据结构之一,它提供了高效的键值对存储和查找能力,:本文主要介绍Python字典(Dictionary)... 目录字典1.基本特性2.创建字典3.访问元素4.修改字典5.删除元素6.字典遍历7.字典的高级特性默认字典

Python自动化批量重命名与整理文件系统

《Python自动化批量重命名与整理文件系统》这篇文章主要为大家详细介绍了如何使用Python实现一个强大的文件批量重命名与整理工具,帮助开发者自动化这一繁琐过程,有需要的小伙伴可以了解下... 目录简介环境准备项目功能概述代码详细解析1. 导入必要的库2. 配置参数设置3. 创建日志系统4. 安全文件名处

使用Python构建一个高效的日志处理系统

《使用Python构建一个高效的日志处理系统》这篇文章主要为大家详细讲解了如何使用Python开发一个专业的日志分析工具,能够自动化处理、分析和可视化各类日志文件,大幅提升运维效率,需要的可以了解下... 目录环境准备工具功能概述完整代码实现代码深度解析1. 类设计与初始化2. 日志解析核心逻辑3. 文件处

python生成随机唯一id的几种实现方法

《python生成随机唯一id的几种实现方法》在Python中生成随机唯一ID有多种方法,根据不同的需求场景可以选择最适合的方案,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习... 目录方法 1:使用 UUID 模块(推荐)方法 2:使用 Secrets 模块(安全敏感场景)方法

使用Python删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数