# -*- coding:utf-8 -*-
# 这里使用pycryptodemo库
# 安装方法 pip install pycryptodemo
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
import io
import sys
import binascii
import base64
import random
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8')
import base64
from Crypto.Cipher import AES
from urllib import parse
AES_SECRET_KEY = '1234567890123456' #此处16|24|32个字符
IV = "1234567890123456"
# padding算法
BS = len(AES_SECRET_KEY)
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s: s[0:-ord(s[-1:])]
class AES_ENCRYPT(object):
def __init__(self):
self.key = AES_SECRET_KEY
self.mode = AES.MODE_CBC
#加密函数
def encrypt(self, text):
cryptor = AES.new(self.key.encode("utf8"), self.mode, IV.encode("utf8"))
self.ciphertext = cryptor.encrypt(bytes(pad(text), encoding="utf8"))
# 加密得到的字符串转16进制
return binascii.hexlify(self.ciphertext)
#解密函数
def decrypt(self, text):
# 十六进制转二进制
decode = binascii.unhexlify(text)
cryptor = AES.new(self.key.encode("utf8"), self.mode, IV.encode("utf8"))
plain_text = cryptor.decrypt(decode)
return unpad(plain_text)
if __name__ == '__main__':
aes_encrypt = AES_ENCRYPT()
my_email = "{'a':b,'deviceName':dashd123}"
e = aes_encrypt.encrypt(my_email)
d = aes_encrypt.decrypt(e)
print(my_email)
print(e)
print(d)
python AES加解密CBC
最新推荐文章于 2024-03-04 12:37:33 发布