pycryptodome

 

2024-09-23

Python 加密工具包,旧 pycrypto 替代品。

安装

Terminal window
1
pip install pycryptodome

使用

1
from Crypto.Cipher import AES
2
from Crypto.Hash import HMAC, SHA256
3
from Crypto.Random import get_random_bytes
4
5
data = 'secret data to transmit'.encode()
6
7
aes_key = get_random_bytes(16)
8
hmac_key = get_random_bytes(16)
9
10
cipher = AES.new(aes_key, AES.MODE_CTR)
11
ciphertext = cipher.encrypt(data)
12
13
hmac = HMAC.new(hmac_key, digestmod=SHA256)
14
tag = hmac.update(cipher.nonce + ciphertext).digest()
15
16
with open("encrypted.bin", "wb") as f:
17
f.write(tag)
18
f.write(cipher.nonce)
19
f.write(ciphertext)

参考