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基础语法中defaultdict的使用小结

《Python基础语法中defaultdict的使用小结》Python的defaultdict是collections模块中提供的一种特殊的字典类型,它与普通的字典(dict)有着相似的功能,本文主要... 目录示例1示例2python的defaultdict是collections模块中提供的一种特殊的字

利用Python快速搭建Markdown笔记发布系统

《利用Python快速搭建Markdown笔记发布系统》这篇文章主要为大家详细介绍了使用Python生态的成熟工具,在30分钟内搭建一个支持Markdown渲染、分类标签、全文搜索的私有化知识发布系统... 目录引言:为什么要自建知识博客一、技术选型:极简主义开发栈二、系统架构设计三、核心代码实现(分步解析

基于Python实现高效PPT转图片工具

《基于Python实现高效PPT转图片工具》在日常工作中,PPT是我们常用的演示工具,但有时候我们需要将PPT的内容提取为图片格式以便于展示或保存,所以本文将用Python实现PPT转PNG工具,希望... 目录1. 概述2. 功能使用2.1 安装依赖2.2 使用步骤2.3 代码实现2.4 GUI界面3.效

Python获取C++中返回的char*字段的两种思路

《Python获取C++中返回的char*字段的两种思路》有时候需要获取C++函数中返回来的不定长的char*字符串,本文小编为大家找到了两种解决问题的思路,感兴趣的小伙伴可以跟随小编一起学习一下... 有时候需要获取C++函数中返回来的不定长的char*字符串,目前我找到两种解决问题的思路,具体实现如下:

python连接本地SQL server详细图文教程

《python连接本地SQLserver详细图文教程》在数据分析领域,经常需要从数据库中获取数据进行分析和处理,下面:本文主要介绍python连接本地SQLserver的相关资料,文中通过代码... 目录一.设置本地账号1.新建用户2.开启双重验证3,开启TCP/IP本地服务二js.python连接实例1.

基于Python和MoviePy实现照片管理和视频合成工具

《基于Python和MoviePy实现照片管理和视频合成工具》在这篇博客中,我们将详细剖析一个基于Python的图形界面应用程序,该程序使用wxPython构建用户界面,并结合MoviePy、Pill... 目录引言项目概述代码结构分析1. 导入和依赖2. 主类:PhotoManager初始化方法:__in

Python从零打造高安全密码管理器

《Python从零打造高安全密码管理器》在数字化时代,每人平均需要管理近百个账号密码,本文将带大家深入剖析一个基于Python的高安全性密码管理器实现方案,感兴趣的小伙伴可以参考一下... 目录一、前言:为什么我们需要专属密码管理器二、系统架构设计2.1 安全加密体系2.2 密码强度策略三、核心功能实现详解

Python Faker库基本用法详解

《PythonFaker库基本用法详解》Faker是一个非常强大的库,适用于生成各种类型的伪随机数据,可以帮助开发者在测试、数据生成、或其他需要随机数据的场景中提高效率,本文给大家介绍PythonF... 目录安装基本用法主要功能示例代码语言和地区生成多条假数据自定义字段小结Faker 是一个 python

Python实现AVIF图片与其他图片格式间的批量转换

《Python实现AVIF图片与其他图片格式间的批量转换》这篇文章主要为大家详细介绍了如何使用Pillow库实现AVIF与其他格式的相互转换,即将AVIF转换为常见的格式,比如JPG或PNG,需要的小... 目录环境配置1.将单个 AVIF 图片转换为 JPG 和 PNG2.批量转换目录下所有 AVIF 图

Python通过模块化开发优化代码的技巧分享

《Python通过模块化开发优化代码的技巧分享》模块化开发就是把代码拆成一个个“零件”,该封装封装,该拆分拆分,下面小编就来和大家简单聊聊python如何用模块化开发进行代码优化吧... 目录什么是模块化开发如何拆分代码改进版:拆分成模块让模块更强大:使用 __init__.py你一定会遇到的问题模www.