文档: 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

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

1万+

被折叠的 条评论
为什么被折叠?



