Python加解密库——pycrypto(pycryptodome)

article/2025/8/14 12:55:16

文章目录

  • 简介
  • 安装
    • 方法一:Visual Studio
    • 方法二:pycryptodome(推荐)
  • 初试
  • 公钥
  • 加解密
    • 对称加密
    • 非对称加密
  • 数字签名
  • 哈希函数
  • 安全通信
  • 加密IO
  • 封装
  • 遇到的坑
  • 参考文献

简介

pycrypto 实现了哈希函数(如 SHA256)和加密算法(如 AES、DES、RSA)。

注意!pycrypto 已很久未维护,有安全漏洞。

建议使用 pycryptodome 替代 pycrypto,它是后者的一个分支,一直在维护。




安装

以下方法均可,推荐方法二



方法一:Visual Studio

Windows 需要安装 Visual Studio 2015 或以上版本,本人是 Visual Studio 2017,安装方法大同小异。

cd C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Auxiliary\Build
vcvars64.bat
set CL=-FI"C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\include\stdint.h"
pip install pycrypto



方法二:pycryptodome(推荐)

也可以用 pycryptodome 替代 pycrypto,它是后者的一个分支,一直在维护。

pip uninstall pycrypto
pip install pycryptodome




初试

SHA256 计算散列值(哈希值)

from Crypto.Hash import SHA256hash = SHA256.new()
hash.update('message'.encode())
print(hash.digest())
# b'\xabS\n\x13\xe4Y\x14\x98+y\xf9\xb7\xe3\xfb\xa9\x94\xcf\xd1\xf3\xfb"\xf7\x1c\xea\x1a\xfb\xf0+F\x0cm\x1d'




公钥

公钥系统下,发送方和接收方使用不同密钥——公钥或私钥。

场景发送方接收方
加解密公钥私钥
数字签名私钥公钥
from Crypto.PublicKey import RSAkey_pair = RSA.generate(4096)  # 生成密钥对
open('public.pem', 'wb').write(key_pair.public_key().export_key('PEM'))  # 导出公钥
open('private.pem', 'wb').write(key_pair.export_key('PEM'))  # 导出私钥




加解密

三种加密方式:

  1. 对称加密:参与方使用相同密钥进行加解密,速度快,适合处理大量数据。如 AES。
  2. 非对称加密:发送方使用公钥加密,接收方使用私钥解密,速度慢。如 RSA。
  3. 混合加密:将上述加密进行组合,优点兼具,非对称加密用于保护有效时间短的对称密钥,对称加密用于加密实际数据。



对称加密

两种对称加密方式:

  1. 流加密:一次加密一个字节数据。如 ChaCha20、XChaCha20 和 Salsa20
  2. 分组密码:对固定数量的数据进行加密。如 AES,一次加密 16 个字节。

Salsa20 加密

from Crypto.Cipher import Salsa20# 加密方
plaintext = b'Hello World!'  # 明文
key = b'0123456789012345'  # 密钥
cipher = Salsa20.new(key=key)
msg = cipher.nonce + cipher.encrypt(plaintext)  # 消息=随机数+密文# 解密方
key = b'0123456789012345'  # 密钥
msg_nonce = msg[:8]
ciphertext = msg[8:]
cipher = Salsa20.new(key=key, nonce=msg_nonce)
plaintext = cipher.decrypt(ciphertext)
print(plaintext)
# b'Hello World!'

AES 加密

from Crypto.Cipher import AES# 加密方
plaintext = b'Hello World!'  # 明文
key = b'0123456789012345'  # 密钥
cipher = AES.new(key, AES.MODE_EAX)
nonce = cipher.nonce
ciphertext, tag = cipher.encrypt_and_digest(plaintext)# 解密方
key = b'0123456789012345'  # 密钥
cipher = AES.new(key, AES.MODE_EAX, nonce=nonce)
plaintext = cipher.decrypt(ciphertext)
try:cipher.verify(tag)  # 验证真实性print(plaintext)
except ValueError:print('密钥不正确或消息被破坏')



非对称加密

RSA 加密

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP# 生成公私密钥
key_pair = RSA.generate(1024)
open('public.pem', 'wb').write(key_pair.public_key().export_key('PEM'))
open('private.pem', 'wb').write(key_pair.export_key('PEM'))# 加密方
plaintext = b'Hello World!'
public_key = RSA.importKey(open('public.pem').read())
cipher = PKCS1_OAEP.new(public_key)
ciphertext = cipher.encrypt(plaintext)# 解密方
private_key = RSA.importKey(open('private.pem').read())
cipher = PKCS1_OAEP.new(private_key)
plaintext = cipher.decrypt(ciphertext)
print(plaintext)

实际场景下,密钥长度应使用 3072 或 4096 位




数字签名

用于保证完整性和不可抵赖性。

PKCS#1 RSA 签名

from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
from Crypto.Signature import pkcs1_15# 生成公私密钥
key_pair = RSA.generate(1024)
open('public.pem', 'wb').write(key_pair.public_key().export_key('PEM'))
open('private.pem', 'wb').write(key_pair.export_key('PEM'))# 发送方
plaintext = b'Hello World!'
private_key = RSA.importKey(open('private.pem').read())
signer = pkcs1_15.new(private_key)
hash = SHA256.new(plaintext)
signature = signer.sign(hash)# 接收方
plaintexts = [b'Hello World!', b'abc']
public_key = RSA.importKey(open('public.pem').read())
signer = pkcs1_15.new(public_key)
for plaintext in plaintexts:hash = SHA256.new(plaintext)try:signer.verify(hash, signature)print('合法')except:print('非法')

推荐阅读:什么是数字签名?




哈希函数

用于信息摘要。

将任意二进制字符串作为输入,并产生类似随机的固定长度的输出,即摘要或哈希值。

SHA256 计算散列值(哈希值)

from Crypto.Hash import SHA256hash = SHA256.new()
hash.update('message'.encode())
print(hash.digest())
# b'\xabS\n\x13\xe4Y\x14\x98+y\xf9\xb7\xe3\xfb\xa9\x94\xcf\xd1\xf3\xfb"\xf7\x1c\xea\x1a\xfb\xf0+F\x0cm\x1d'




安全通信

PBKDF2 进行口令保护

from Crypto.Hash import SHA512
from Crypto.Protocol.KDF import PBKDF2
from Crypto.Random import get_random_bytespassword = '123456'  # 口令
salt = get_random_bytes(16)  # 加盐
keys = PBKDF2(password, salt, 64, count=1000000, hmac_hash_module=SHA512)
key1 = keys[:32]
key2 = keys[32:]

推荐阅读:PBKDF2函数,比「Hash加盐」更好的口令保护方案




加密IO




封装




遇到的坑




参考文献

  1. pycrypto GitHub
  2. PyCryptodome GitHub
  3. PyCryptodome Documentation
  4. python 3.6.5 在windows下安装PyCrypto
  5. windows下python3.9安装pycrypto成功总结
  6. Installing pycrypto on windows (popular solution not working)
  7. How do I install PyCrypto on Windows?
  8. RSA Encrypt / Decrypt
  9. 什么是数字签名?
  10. PBKDF2函数,比「Hash加盐」更好的口令保护方案

http://chatgpt.dhexx.cn/article/IyuDQM21.shtml

相关文章

自制Python小工具(1)——Gadgets 0.1

文章目录 1. 前言2. Gadgets 0.1介绍2.1 使用过程概述 3. Gadgets 0.1功能实现3.1 创建文件3.2 功能编程3.2.1 安装3.2.2 导库3.2.3 定义函数并实现功能 3.3 主程序3.3.1 向用户问好并提供指示3.3.2 填入功能 3.4 装饰加载 4. 源码展示4.1 extract_music.py4.2 loading.py4.3 G…

Windows下安装pycocotools(本人亲测,可以解决)

Windows下安装pycocotools 1. 下载pycocotools的源码2. 安装python对应的VC3. 进行pycocotools的编译4. 测试安装是否成功 参考博客:原博客 由于windows下是不能直接使用conda install 或者pip install pycocotools,唉,不像linux系统&#x…

学习 PySOT(2)(PySOT-toolkit、对比、画图)

文章目录 前言一、pysot-toolkit准备工作1.所需环境要求2.文件配置3.运行配置(对比算法) 二、安装latex软件(win10系统)1.安装MiKTeX2.安装TexMaker3.配置TexMaker4.配置MiKTeX 三、运行eval.py画图1. 修改eval.py参数,运行2. 常见问题解决 前…

redis-exporter监控

文章目录 启动redis-export服务启动prometheus服务启动granfana服务测试报警 使用redis-exporter监控redis服务,并且使用prometheus收集数据,使用grafana展示数据。 监控报警利用alertmanager插件,报警信息发送钉钉消息。所使用的安装包可以 …

Zabbix实现对Redis的监控

Zabbix实现对Redis的监控 环境准备 五台机器: zabbix_agent 5.0 被动模式(已安装) Zabbix_java_gateway 5.0 (已安装) 10.0.0.7 MariaDB-10.4.22(已安装) zabbix_server 5.0(已安…

zabbix配置redis监控

1 redis监控需要用到zabbix_agent2的版本,该版本涵盖了zabbix_agent1的全部功能。安装zabbix_agent2 yum install zabbix-agent2-5.0.13-1.el7.x86_64 -y 2 配置zabbix_agent2.conf的脚本,将redis的相关信息配置。vi /etc/zabbix/zabbix_agent2.conf …

【中间件】Redis监控以及指标

一、监控指标 1.1、性能指标:Performance Name Description latency Redis响应一个请求的时间 instantaneous_ops_per_sec 平均每秒处理请求总数 hi rate(calculated) 缓存命中率(计算出来的 1.2、内存指标: Memory Name Description used_m…

Redis监控和预警

1.摘要 本人从事Java Web开发,在项目开发中会用到很多中间件,本文主要介绍Redis监控的一点心得和使用,公司DBA也有相应的监控,但是我们的业务比较重要,想做一个备份监控,对Redis监控需要做监控和预警&#…

如何完善Redis监控告警?

本文字数:3940字 预计阅读时间:20分钟 一、背景二、监控指标分类三、监控指标说明四、总结 一、背景 Redis监控告警实践是基于开发CacheCloud云平台过程中不断实践和总结出来,随着Redis实例规模不断变大,会遇到各种各样的问题&…

redis集群监控

通过Prometheus监控redis集群 一、promethus安装 下载地址: https://github.com/prometheus/prometheus/releases 1、下载 wget https://github.com/prometheus/prometheus/releases/download/v2.32.1/prometheus-2.32.1.linux-amd64.tar.gz 2、安装、配置 ta…

Linux安装Redis监控工具RedisInsight

文章目录 1.简介2.安装RedisInsight2.1下载RedisInsight2.2配置RedisInsight2.3运行RedisInsight 3.使用RedisInsight3.1添加Redis3.1.1添加单机Redis 3.2自动发现Redis3.3以编程方式添加Redis3.4性能指标3.5集群管理3.6命令行3.7内存分析3.7.1在实例上运行内存分析3.7.2内存概…

RedisInsight:Redis监控工具部署(linux)

RedisInsight 部署流程 简介一、下载二、安装1.准备工作2.配置及介绍3.运行4.访问 总结 简介 RedisInsight提供以下功能: 易于使用基于浏览器的界面来搜索键、查看和编辑数据唯一支持Redis集群的GUI工具支持基于SSL/TLS的连接运行内存分析 一、下载 下载地址: R…

redis监控工具

redis-monitor 项目github地址:https://github.com/NetEaseGame/redis-monitor (看作者名称,应该是华科的) # 安装 pip install redis-monitor#初始化redis-monitor init#启动 nohup redis-monitor start > redis-monitor.l…

Redis性能监控

redis_exporter prometheus grafana监控Redis服务指标 1.redis_exporter2.prometheus3.grafana 本文使用 redis_exporter prometheus grafana 实现对Redis服务进行监控,原因:成本低,人工干预少,直接下载对应的组件,只需添加配置即可互相通信,可视化指标也比较全面。 下面是在…

性能测试:Redis性能监控(redis-stat工具)

redis 监控 redis 监控一共有两种方式,一种是通过info命令,还有一种是使用redis-stat工具。两者其实本质是一样的,不过一个是命令行的模式下查看监控数据,而另外一种是图形化页面查看。但是实际上,我们性能测试主要更…

Redis监控利器---Redis State

强烈推荐一个大神的人工智能的教程:http://www.captainai.net/zhanghan 【前言】 在之前的博文《Redis百万级别数据迁移》中分享我们系统为降低服务器成本,从亚马逊云迁至阿里云的一次生产迁移过程中Redis部分迁移;去年迁移Redis时数据量500…

【Redis监控】

方法1:redis-stat 下载地址:https://github.com/junegunn/redis-stat 可以直接下载安装jar包 Usage usage: redis-stat [HOST[:PORT][/PASS] ...] [INTERVAL [COUNT]] -a, --authPASSWORD Password -v, --verbose …

redis监控

上篇我们将redis安装好了,但是自己搭建的服务监控起来比较麻烦,我们每次都需要跑到redis-cli使用info命令查看redis的状态。 所以我们需要一个可视化的redis监控工具,这里我们为了方便使用docker进行安装,毕竟依赖这个东西是要搞…

性能测试之Redis和Nginx 性能监控

redis 监控 redis 监控一共有两种方式,一种是通过info命令,还有一种是使用redis-stat工具。两者其实本质是一样的,不过一个是命令行的模式下查看监控数据,而另外一种是图形化页面查看。但是实际上,我们性能测试主要更…

redis基础监控

redis监控 redis server 监控: redis存活判断:ping判断,如果指定时间返回PONG表示存活,否则redis不能响应请求,可能阻塞或死亡 机器端口检查:nc 判断端口是否正常。 连接数:connected_clients …