python实现AES加密
pip install pycryptodomex
需要安装pycryptodomex模块
aes加密
from Cryptodome.Cipher import AES from binascii import b2a_hex, a2b_hex from config import secret_key class AESEncrypts: def __init__(self): self.key = secret_key[0:16].encode("utf-8") self.BS = AES.block_size self.pad = lambda s: s + (self.BS - len(s) % self.BS) * chr(self.BS - len(s) % self.BS) self.un_pad = lambda s: s[0:-ord(s[-1])] def encrypt(self, clear_text): aes = AES.new(self.key, AES.MODE_CBC, self.key) return b2a_hex(aes.encrypt(self.pad(clear_text).encode('utf-8'))).decode("utf-8") def decrypt(self, cipher_text): aes = AES.new(self.key, AES.MODE_CBC, self.key) text = aes.decrypt(a2b_hex(cipher_text.encode("utf-8"))) return self.un_pad(text.decode("utf-8"))
des3 加密
BS = DES3.block_size keylen = BS * 3 pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS) pad_key = lambda s: (keylen - len(s) % keylen) * chr(keylen - len(s) % keylen) + s unpad = lambda s: s[0:-ord(s[-1])] def Encrypt(key, data): cipher = DES3.new(key=pad_key(key), mode=DES3.MODE_ECB) return base64.b64encode(cipher.encrypt(pad(data).encode("utf-8"))) def Decrypt(key, data): cipher = DES3.new(key=key, mode=DES3.MODE_ECB) return unpad(cipher.decrypt(base64.b64decode(data)))