一、安装pycryptodome库:
pip install pycryptodome
二、使用pycryptodome库:
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
import hashlib
# 派生密钥函数
def get_key(password):
hasher = hashlib.sha256() # 生成32字节
hasher.update(password)
return hasher.digest()
# 加密函数
def encrypt_AES_GCM(msg, password):
# 生成随机的nonce
nonce = get_random_bytes(12)
# 生成符合长度要求的密钥(密钥长度必须是16、24或者32字节)
key = get_key(password)
# 创建AES-GCM加密器
cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
# 加密消息
ciphertext, tag = cipher.encrypt_and_digest(msg.encode('utf-8'))
# 返回加密后的消息和nonce
return (ciphertext, nonce, tag)
# 解密函数
def decrypt_AES_GCM(ciphertext, nonce, tag, password):
# 生成符合长度要求的密钥
key = get_key(password)
# 创建AES-GCM解密器
cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
# 解密消息
plaintext = cipher.decrypt_and_verify(ciphertext, tag)
# 返回解密后的消息
return plaintext.decode('utf-8')
# 测试加密解密
password = b'secret_password_123'
msg = 'Hello, world!'
ciphertext, nonce, tag = encrypt_AES_GCM(msg, password)
plaintext = decrypt_AES_GCM(ciphertext, nonce, tag, password)
print(plaintext)
运行结果:
注意:在AES-GCM模式下,需要使用随机的nonce来保证加密的安全性。同时,需要使用tag来验证解密后的消息是否被篡改。