[[Python]] 加密工具包,旧 [[pycrypto]] 替代品。
安装
pip install pycryptodome
使用
from Crypto.Cipher import AESfrom Crypto.Hash import HMAC, SHA256from 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)