加解密封装 发表于 2024-03-18 | 分类于 框架封装 字数统计: 313 字 | 阅读时长 ≈ 1 分钟 加密、解密封装。包含AES加解密和MD5加密 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980import base64import hashlibfrom Crypto.Cipher import AES as _AESfrom cryptography.hazmat.primitives import padding# 密钥AES_KEY = base64.b64decode("bG9uZ2dlPTY2NmxvdmUhIQ==").decode() # 请修改 一定是 16位的字符串# 偏移量AES_IV = base64.b64decode("bG9uZ2dlPTg4OGxvdmUhIQ==").decode()# 加盐AES_SALT = base64.b64decode("bG9uZ2dlPTk5OWxvdmUhIQ==").decode()# 处理AES加密和解密,(AES+CBC+pkcs7padding)class AESCrypt(): def __init__(self): self.IV = AES_IV.encode("utf-8") self.KEY = AES_KEY.encode("utf-8") self.SALT = AES_SALT.encode("utf-8") def pkcs7_padding(self, data, block_size=128): """ 密码必须满足8的倍数所以需要补位,PKCS7Padding用'\n'补位 :param data: :param block_size: :return: """ if not isinstance(data, bytes): data = data.encode('utf-8') padder = padding.PKCS7(block_size).padder() return padder.update(data) + padder.finalize() def generateKey(self): """ key加盐 :return: """ return hashlib.pbkdf2_hmac(hash_name="sha1", password=self.KEY, salt=self.SALT, iterations=1, dklen=16) def aes_encrypt(self, password: str): """ aes加密 :param password: :return: """ key = self.generateKey() padded_data = self.pkcs7_padding(password) cipher = _AES.new(key, _AES.MODE_CBC, self.IV) return base64.b64encode(cipher.encrypt(padded_data)).decode() def aes_decrypt(self, content: str): """ aes解密 :param content: :return: """ key = self.generateKey() cipher = _AES.new(key, _AES.MODE_CBC, self.IV) content = base64.b64decode(content) return (cipher.decrypt(content).decode('utf-8')).replace('\n', '')# 处理md5加密,未加盐class MD5Crypt(): def md5_encrypt(self, content): # 创建对象 md = hashlib.md5(content.encode('utf-8')) return md.hexdigest()if __name__ == '__main__': ace = AESCrypt() md5 = MD5Crypt() enc_data = ace.aes_encrypt("123456") print("加密:>>>>>{}".format(enc_data)) dec_data = ace.aes_decrypt(enc_data) print("解码:>>>>>{}".format(dec_data)) c = md5.md5_encrypt("123456") print(c) ------------- End -------------