先安装包
pip install pycrypto==2.6.1
加解密类
# coding=utf-8
from Crypto.Cipher import AES
class ASEUtil(object):
"""
ase加解密工具类
"""
@staticmethod
def encrypt(key, text):
"""
解密
"""
bs = AES.block_size
def pad(s): return s + (bs - len(s) % bs) * chr(bs - len(s) % bs)
cipher = AES.new(key, AES.MODE_ECB) # ECB模式
return cipher.encrypt(pad(text)).encode("hex")
@staticmethod
def decrypted(key, cipher_text):
"""
解密
"""
cipher = AES.new(key, AES.MODE_ECB) # ECB模式
def un_pad(s): return s[0:-ord(s[-1])]
return un_pad(cipher.decrypt(cipher_text.decode("hex")))
if __name__ == '__main__':
encrypt = ASEUtil.encrypt('hhhhhhhhhhhhhhhh', '{"abc":"abc"}')
decrypted = ASEUtil.decrypted('hhhhhhhhhhhhhhhh',encrypt)
print(decrypted)
该代码仅支持python2,注意,key只能为16位或者16位的倍数,否则报错
ValueError: Incorrect AES key length (15 bytes)