import json
from Crypto.Cipher import DES3
key = "123fffg2vffsssss1112356F"#24位密钥
iv = "IV202404"#8位向量
class EncryptData():
def __init__(self):
self.key = key[:24] # 初始化密钥
self.iv = iv.encode('utf-8') # 初始化密钥
self.length = DES3.block_size # 初始化数据块大小
self.aes = DES3.new(self.key, DES3.MODE_CBC, self.iv) # 初始化AES,ECB模式的实例
# 截断函数,去除填充的字符
self.unpad = lambda date: date[0:-ord(date[-1])]
def pad(self, text):
"""
#填充函数,使被加密数据的字节码长度是block_size的整数倍
"""
count = len(text.encode('utf-8'))
add = self.length - (count % self.length)
entext = text + (chr(add) * add)
return entext
def encrypt(self, encrData): # 加密函数
res = self.aes.encrypt(self.pad(encrData).encode("utf8"))
msg = res.hex()
return msg
def decrypt(self, decrData): # 解密函数
res = bytes.fromhex(decrData)
msg = self.aes.decrypt(res).decode("utf8")
return self.unpad(msg)
if __name__ == "__main__":
data = {"username": "dahai"}
json_str = json.dumps(data)
res = EncryptData().encrypt(json_str)
print("加密结果", res)
print("解密结果", EncryptData().decrypt(res))
3DES加密算法及Python实现
于 2023-08-15 10:27:57 首次发布