from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
# 生成一个随机的16字节密钥
key = get_random_bytes(16)
# 创建AES加密器对象,使用CBC模式
cipher = AES.new(key, AES.MODE_CBC)
# 要加密的明文
plaintext = b'This is a secret message'
# 使用PKCS7填充方式对明文进行填充
padded_plaintext = pad(plaintext, AES.block_size)
# 加密过程
ciphertext = cipher.encrypt(padded_plaintext)
# 打印密文和初始化向量(IV)
print("Ciphertext:", ciphertext)
print("IV:", cipher.iv)
# 解密过程
decipher = AES.new(key, AES.MODE_CBC, cipher.iv)
unpadded_decrypted_text = unpad(decipher.decrypt(ciphertext), AES.block_size)
# 打印解密后的明文
print("Decrypted text:", unpadded_decrypted_text.decode())
Crypto.Cipher 导入 AES 模块,从 Crypto.Random 导入 get_random_bytes 用于生成随机密钥,从 Crypto.Util.Padding 导入 pad 和 unpad 用于填充和去除填充。get_random_bytes(16) 生成一个16字节(128位)的随机密钥。AES.new 方法创建一个 AES 加密器对象,指定密钥和模式为 CBC(Cipher Block Chaining)。encrypt 方法对填充后的明文进行加密,得到密文。如果需要进一步的帮助或有其他问题,请告诉我!
上一篇:python ==
下一篇:int函数python
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站