import json
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
from base64 import b64encode, b64decode
# 加密与解密所使用的密钥,长度必须是16的倍数
# 随机生成密钥
key = b64encode(get_random_bytes(16)).decode('utf-8')
#key = pad("ThisIs SecretKey2".encode('utf-8'), AES.block_size)
# 要加密的明文数据,长度必须是16的倍数
data = pad("Hello, World123!2".encode('utf-8'), AES.block_size)
# IV参数,长度必须是16, 如果不指定iv则会随机生成
#iv = 'This is an IV456'.encode('utf-8')
# 数据加密
cipher1 = AES.new(b64decode(key), AES.MODE_CBC)
cipher_data = cipher1.encrypt(data)
iv = b64encode(cipher1.iv).decode('utf-8')
ct = b64encode(cipher_data).decode('utf-8')
result = json.dumps({'key':key, 'iv':iv, 'ciphertext':ct})
print(result)
# 数据解密
b64 = json.loads(result)
key = b64decode(b64['key'])
iv = b64decode(b64['iv'])
ct = b64decode(b64['ciphertext'])
cipher2 = AES.new(key, AES.MODE_CBC, iv)
# 解密后的明文数据
pt = unpad(cipher2.decrypt(ct), AES.block_size)
print('The message was: ', pt.decode('utf-8'))
# {"key": "Xj52movZaYmw3YI8lFjeiA==", "iv": "wssYy7cavdYzpN89ZzaVOQ==", "ciphertext": "R/7dokPvS312p/JTRly1PSkOVlsfJYfkb+nJIrtXw4I="}
# The message was: Hello, World123!2
以上代码中,如果不在加密前对明文以及密钥pad,则如果长度不是16的倍数会报错。通过pad会将明文及密钥长度填充至16的倍数,通过unpad会将pad填充的内容去掉,恢复至原来的长度。
参考:
https://www.cnblogs.com/yyds/p/7072492.html
https://pycryptodome.readthedocs.io/en/latest/src/util/util.html
https://pycryptodome.readthedocs.io/en/latest/src/cipher/classic.html#cbc-mode
https://blog.csdn.net/bandaoyu/article/details/105552003