python-AES加密和解密

发布时间 2023-05-10 00:09:04作者: ERROR404Notfound
from Crypto.Cipher import AES
import base64
#  秘钥
key = 'aes_secret'


#  秘钥必须是16位字节或者24位字节或者32位字节(因为python3的字符串是unicode编码,需要 encode才可以转换成字节型数据
def add_32(s):
    while len(s) % 16 != 0:
        s += '\0'  # \0的长度为1,用来填补字符串长度不足
    return str.encode(s)

print(add_32(key))  # b'aes_secret\x00\x00\x00\x00\x00\x00'  此时每个'\x00\'算一个字节长度

"""
#电码本模式(Electronic Codebook Book (ECB))

#密码分组链接模式(Cipher Block Chaining (CBC))

#计算器模式(Counter (CTR))

#密码反馈模式(Cipher FeedBack (CFB))

#输出反馈模式(Output FeedBack (OFB))
"""
# 创建一个aes对象
aes = AES.new(add_32(key),AES.MODE_ECB)
print(aes)  # <Crypto.Cipher._mode_ecb.EcbMode object at 0x000002DCFE6DB668>

text = 'hello world'

while len(text.encode('utf-8')) % 16 != 0: # 如果text不足16位的倍数就用空格补足为16位

    text += '\0'

text=text.encode(encoding="utf-8")  # 将text用utf4-8编码
en_text = aes.encrypt(text)
# 加密明文
print(en_text)  # b'u<$\xcdc\xf6w\x8d\x08\x1d\xd6\xe0\x00J-\x97'
# 将返回的字节型数据转进行base64编码
en_text = base64.encodebytes(en_text)
print(en_text)  # b'dTwkzWP2d40IHdbgAEotlw==\n'
# 转换成python中的字符串类型
en_text = en_text.decode('utf8')
print(en_text)  # dTwkzWP2d40IHdbgAEotlw==

#  解密过程
model = AES.MODE_ECB #定义模式
# 创建一个aes对象
aes = AES.new(add_32(key),model) 
# 需要解密的文本
text=en_text.encode(encoding='utf-8')
#  base64解码成字节流
ecrypted_base64 = base64.decodebytes(text)
# 解密
str=aes.decrypt(ecrypted_base64)

str=str.decode()

print(str)  # hello world