Python Package

pycryptodome

2024-09-23

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

安装

Terminal window
pip install pycryptodome

使用

from Crypto.Cipher import AES
from Crypto.Hash import HMAC, SHA256
from Crypto.Random import get_random_bytes
data = 'secret data to transmit'.encode()
aes_key = get_random_bytes(16)
hmac_key = get_random_bytes(16)
cipher = AES.new(aes_key, AES.MODE_CTR)
ciphertext = cipher.encrypt(data)
hmac = HMAC.new(hmac_key, digestmod=SHA256)
tag = hmac.update(cipher.nonce + ciphertext).digest()
with open("encrypted.bin", "wb") as f:
f.write(tag)
f.write(cipher.nonce)
f.write(ciphertext)

参考