python AES CBC 加解密方式
AES CBC(Cipher Block Chaining)是一种加密模式,它使用AES算法对数据进行加密和解密。在AES CBC模式中,每个数据块都与前一个加密块进行异或运算,然后再进行AES加密。这样可以增加数据的安全性,因为每个加密块都依赖于前一个加密块的结果。
下面是使用Python进行AES CBC加密和解密的示例代码:
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
def encrypt(plain_text, key):
# 生成随机的初始向量(IV)
iv = get_random_bytes(AES.block_size)
# 创建AES加密器对象
cipher = AES.new(key, AES.MODE_CBC, iv)
# 对数据进行填充并进行加密
cipher_text = cipher.encrypt(pad(plain_text, AES.block_size))
# 返回加密后的数据和初始向量
return cipher_text, iv
def decrypt(cipher_text, iv, key):
# 创建AES解密器对象
cipher = AES.new(key, AES.MODE_CBC, iv)
# 对数据进行解密并去除填充
plain_text = unpad(cipher.decrypt(cipher_text), AES.block_size)
# 返回解密后的数据
return plain_text
# 测试
key = get_random_bytes(16) # 生成随机的16字节密钥
plain_text = b"Hello, AES CBC!"
# 加密
cipher_text, iv = encrypt(plain_text, key)
print("加密后的数据:", cipher_text)
# 解密
decrypted_text = decrypt(cipher_text, iv, key)
print("解密后的数据:", decrypted_text)
请注意,上述代码中使用了Crypto库来进行AES加密和解密操作。如果你的Python环境中没有安装Crypto库,可以通过pip install pycryptodome命令来安装。
此外,为了安全起见,请确保密钥的生成和存储方式符合你的加密需求。以上代码仅供参考,实际使用时请根据具体情况进行修改和增强
原文地址: http://www.cveoy.top/t/topic/icFO 著作权归作者所有。请勿转载和采集!