首页 > 编程语言 > 详细

Python实现AES加密,解密有借鉴意义

时间:2020-10-02 16:54:25      阅读:28      评论:0      收藏:0      [点我收藏+]
import base64
from Crypto.Cipher import AES


# 密钥(key), 密斯偏移量(iv) CBC模式加密

def AES_Encrypt(key, data):
    vi = 0102030405060708
    pad = lambda s: s + (16 - len(s) % 16) * chr(16 - len(s) % 16)
    data = pad(data)
    # 字符串补位
    cipher = AES.new(key.encode(utf8), AES.MODE_CBC, vi.encode(utf8))
    encryptedbytes = cipher.encrypt(data.encode(utf8))
    # 加密后得到的是bytes类型的数据
    encodestrs = base64.b64encode(encryptedbytes)
    # 使用Base64进行编码,返回byte字符串
    enctext = encodestrs.decode(utf8)
    # 对byte字符串按utf-8进行解码
    return enctext


def AES_Decrypt(key, data):
    vi = 0102030405060708
    data = data.encode(utf8)
    encodebytes = base64.decodebytes(data)
    # 将加密数据转换位bytes类型数据
    cipher = AES.new(key.encode(utf8), AES.MODE_CBC, vi.encode(utf8))
    text_decrypted = cipher.decrypt(encodebytes)
    unpad = lambda s: s[0:-s[-1]]
    text_decrypted = unpad(text_decrypted)
    # 去补位
    text_decrypted = text_decrypted.decode(utf8)
    return text_decrypted


key = 0CoJUm6Qyw8W8jud #自己密钥
data = sdadsdsdsfd  #需要加密的内容
AES_Encrypt(key, data)
enctext = AES_Encrypt(key, data)
print(enctext)
text_decrypted = AES_Decrypt(key, enctext)
print(text_decrypted)

 

Python实现AES加密,解密有借鉴意义

原文:https://www.cnblogs.com/aotumandaren/p/13761816.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!