H_On个人小站

个人站

这都被你发现了【惊
奖励你一朵小红花~


记录使用 Python 实现 AES-128-CBC 算法

目录

前言

搞微信小程序的登录,后端要解密一下这个。参考这篇文章

安装 Crypto 库

参考这篇文章

pip install pycryptodome

如果安装反应速度太慢,可以用这种方法临时换源:

pip install pycryptodome -i http://mirrors.aliyun.com/pypi/simple --trusted-host mirrors.aliyun.com

测试代码

#coding=utf8

from Crypto.Cipher import AES
from Crypto.Util.Padding import pad,unpad
import base64
import hashlib

class PrpCrypt(object):
    def __init__(self, key):
        self.key = key
        self.mode = AES.MODE_CBC
        self.iv = ""

    def md5sum(self,tmp):
        m = hashlib.md5()
        m.update(tmp.encode("utf8")) 
        return m.hexdigest()   

    def setKEYandIV(self):
        tmp = self.md5sum(self.key)
        self.iv = tmp[0:16].encode("utf8")
        self.key = self.key.encode("utf8")

    def encrypt(self, text):
        data = pad(text.encode('utf8'),16)
        cipher = AES.new(self.key, self.mode, self.iv)
        encryptedbytes = cipher.encrypt(data)
        encodestrs = base64.b64encode(encryptedbytes)
        enctext = encodestrs.decode('utf8')
        return enctext

    def decrypt(self, text):
        cryptor = AES.new(self.key, self.mode, self.iv)
        encodebytes = base64.decodebytes(text)
        #需要注意进行base64解码字符串
        plain_text = cryptor.decrypt(encodebytes)
        plain_text = unpad(plain_text,16)
        return plain_text.decode("utf8")

tmp = b'xxxxxxxxxxxxxxxxx'  #自己加密完的数据

key = "xxxxx"  #自己定义

obj = PrpCrypt(key)
obj.setKEYandIV()
tmp2 = obj.decrypt(tmp)
print(tmp2)

obj2 = PrpCrypt(key)
obj2.setKEYandIV()
tmp3 = obj2.encrypt(tmp2)
print(tmp3)