常用的加密算法
常见的对称加密算法有 AES、DES、3DES 和 Itsdangerous ,md5 ,base64
Itsdangerous 加密和解密方法
2 from itsdangerous import TimedJSONWebSignatureSerializer as serializer 3 class ItsdangerouSecret: 4 # 初始化 5 def __init__(self,salt='123456789',expir=6): 6 self.salt = salt # 盐值 7 self.expir = expir # 过期时间 单位秒 8 9 # 加密 raw 是一个对象 10 def encry(self,raw): 11 try: 12 obj = serializer(self.salt, expires_in=self.expir) 13 res = obj.dumps(raw) 14 token = res.decode() 15 return token 16 except: 17 retrun '' 18 19 20 # 解密 raw是字符串 21 def decry(self,raw): 22 try: 23 obj = serializer(self.salt, expires_in=self.expir) 24 return obj.loads(raw) 25 except: 26 return ''
3DES 加密和解密
1 # pip install PyCryptodome 安装模块 2 from pyDes import des, ECB, PAD_PKCS5 3 import binascii 4 class DesSecret: 5 # 初始化 盐值需要在8个字节以上 6 def __init__(self,salt='12341234'): 7 self.salt = salt 8 9 # 加密 PAD_PKCS5 10 def encry(self,raw): 11 try: 12 k = des(self.salt, ECB, self.salt, pad=None, padmode=PAD_PKCS5) 13 en = k.encrypt(raw, padmode=PAD_PKCS5) 14 return binascii.b2a_hex(en).decode() 15 except: 16 return '' 17 18 # 解密 PAD_PKCS5 19 def decry(self,raw): 20 try: 21 k = des(self.salt, ECB, self.salt, pad=None, padmode=PAD_PKCS5) 22 de = k.decrypt(binascii.a2b_hex(raw), padmode=PAD_PKCS5) 23 return de.decode() 24 except: 25 return ''
base64 编码与解码
1 import base64 2 def b64_encode(raw): 3 return base64.b64encode(raw.encode()).decode() 4 5 def b64_decode(raw): 6 return base64.b64decode(raw).decode()
md5加密
1 def md5(raw): 2 import hashlib 3 md5 = hashlib.md5() 4 md5.update(raw.encode('utf8')) 5 retrun md5.hexdigest()