PyCryptodome QuickStart

本文通过Python示例代码介绍了使用PyCryptodome库进行对称加密(AES)和非对称加密(RSA)的方法,包括密钥生成、加密解密过程及数字签名验证。


文档: https://www.pycryptodome.org/,本文代码大多参考Examples示例章节。

Github: https://github.com/Legrandin/pycryptodome

安装后,py源码位于python目录\Lib\site-packages\Crypto。但想学习算法实现的话还是需要去github src目录查看c源码,本地只有编译好的pyd,并且在py里用load\_pycryptodome\_raw\_lib加载。

Pycrypto、crypto这两个py库其实是同一个东西,其中crypto在python上面的名字是pycrypto,已经停止更新了;pycryptodome库则兼容PyCrypto库,用它就完了。其实查看\Lib\site-packages\pycryptodome-3.14.1.dist-info\top_level.txt,所用的包名仍然是Crypto。

1. 文档解读

重点看API部分,了解一下库的目录。

Package Description
Crypto.Cipher Modules for protecting confidentiality that is, for encrypting and decrypting data (example: AES).
Crypto.Signature Modules for assuring authenticity, that is, for creating and verifying digital signatures of messages (example: PKCS#1 v1.5).
Crypto.Hash Modules for creating cryptographic digests (example: SHA-256).
Crypto.PublicKey Modules for generating, exporting or importing public keys (example: RSA or ECC).
Crypto.Protocol Modules for faciliting secure communications between parties, in most cases by leveraging cryptograpic primitives from other modules (example: Shamir’s Secret Sharing scheme).
Crypto.IO Modules for dealing with encodings commonly used for cryptographic data (example: PEM).
Crypto.Random Modules for generating random data.
Crypto.Util General purpose routines (example: XOR for byte strings).

2. Demo

对称加密

基于官方AES-CBC示例修改的demo,官方示例使用了base64编码,这里去掉:

import json
# from base64 import b64encode, b64decode
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
from binascii import b2a_hex, a2b_hex

# encrypt
data = b"secret"
key = get_random_bytes(16)
cipher = AES.new(key, AES
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值