A-A+
python 编写 AES256/ECB/PKCS7Padding 详细的加密解密脚本示例代码
【注意:此文章为博主原创文章!转载需注意,请带原文链接,至少也要是txt格式!】
闲来无事,训练训练OpenAI玩玩,越训练越智能,还真的是厉害。
# -*- coding:utf-8 -*-
# __author__ = shrimp
# __Blog__ = https://woj.app
# __Date__ = 2023/4/4
# __ver__ = python3
from Crypto.Cipher import AES
import base64
from urllib.parse import unquote
##这段代码实现了使用 AES 算法对明文进行加密和解密,并使用 Base64 编码对密文进行序列化。其中加密模式为 ECB(电子密码本模式),填充模式为 PKCS#7。
def aes_encrypt(plaintext: str, key: bytes) -> bytes:
# 将明文字符串转为bytes类型
plaintext = plaintext.encode('utf-8')
# 创建 AES 对象,使用 ECB 模式
cipher = AES.new(key, AES.MODE_ECB)
# 计算明文需要填充的字节数,使其长度为 AES.block_size 的整数倍
length = AES.block_size - (len(plaintext) % AES.block_size)
# 使用 bytes([length]) * length 将需要填充的字节填充进明文中
plaintext += bytes([length]) * length
# 使用 AES 对象加密明文
ciphertext = cipher.encrypt(plaintext)
# 返回加密后的密文,使用 Base64 编码
return base64.b64encode(ciphertext)
def aes_decrypt(ciphertext: str, key: bytes) -> bytes:
# 对密文进行 Base64 解码,将其转为 bytes 类型
ciphertext = base64.b64decode(unquote(ciphertext))
# 创建 AES 对象,使用 ECB 模式
cipher = AES.new(key, AES.MODE_ECB)
# 使用 AES 对象解密密文
plaintext = cipher.decrypt(ciphertext)
# 去除明文末尾的填充字节,得到最终的明文
return plaintext[:-plaintext[-1]]
# 测试代码
if __name__ == '__main__':
# key是固定值,长度为32字节,使用utf-8编码转为bytes类型
key = b'12345678123456123123'
data = 'nGGfqTY3oLBxKYKdHtbDtA=='
tel = "13555144144"
# 加密
ciphertext = aes_encrypt(tel, key)
print('加密后:', ciphertext)
# 解密
plaintext = aes_decrypt(data, key)
print('解密后:', plaintext)
布施恩德可便相知重
微信扫一扫打赏
支付宝扫一扫打赏