CMS_Django_Backend/apps/api/common.py

126 lines
4.0 KiB
Python
Raw Normal View History

2024-11-03 22:00:42 +08:00
import re
class CaesarCypherClass:
"""
恺撒密码提供以恺撒密码方法进行加密及解密的方法加密方法使用CaesarEncode()函数解密方法使用CaesarDecode()函数
"""
def __init__(self, *args, **kwargs):
pass
@staticmethod
def caesar_encode(s):
"""
恺撒密码加密方法需要提供需要加密的明文
"""
s_encode = ''
for c in s:
if 'a' <= c <= 'z':
s_encode += chr(ord('a') + (ord(c) - ord('a') + 3) % 26)
elif 'A' <= c <= 'Z':
s_encode += chr(ord('A') + (ord(c) - ord('A') + 3) % 26)
elif 0x4E00 <= ord(c) <= 0x9FA5:
s_encode += chr(ord(c) + 3)
elif '0' <= c <= '9':
s_encode += chr(ord('0') + (ord(c) - ord('0') + 3) % 10)
else:
s_encode += c
return s_encode
@staticmethod
def caesar_decode(s):
"""
恺撒密码解密方法需要提供需要解密的密文
"""
s_decode = ''
for c in s:
if 'a' <= c <= 'z':
s_decode += chr(ord('a') + (ord(c) - ord('a') - 3) % 26)
elif 'A' <= c <= 'Z':
s_decode += chr(ord('A') + (ord(c) - ord('A') - 3) % 26)
elif 0x4E00 <= ord(c) <= 0x9FA5:
s_decode += chr(ord(c) - 3)
elif '0' <= c <= '9':
s_decode += chr(ord('0') + (ord(c) - ord('0') - 3) % 10)
else:
s_decode += c
return s_decode
class Base64CypherClass:
"""
Base64的加解密算法最简单的加密方式可加密短的文字小图片小文件图片文件大小不宜超过10M
"""
def __init__(self, *args, **kwargs):
"""
Base64类初始化函数
:param args:
:param kwargs:
"""
import importlib
self.base64 = importlib.import_module('base64')
self.os = importlib.import_module('os')
self.time = importlib.import_module('time')
self.re = importlib.import_module('re')
@staticmethod
def base64_encode_str(self, s):
"""
Base64字符串加密
:param self:
:param s: 要加密的字符串
:return: 加密后的字符串
"""
return self.base64.b64encode(s.encode('utf-8'))
@staticmethod
def base64_decode_str(self, s):
"""
Base64字符串解密解密前先判断是否为Base64加密方式
:param self:
:param s: 要解密的字符串
:return: 解密后的字符串
"""
try:
self.base64.b64decode(s)
return self.base64.b64decode(s).decode('utf-8')
except Exception as e:
return f"base64解密失败请确定加密方式是否正确。错误信息{e}"
@staticmethod
def base64_encode_pic(self, pic):
"""
Base64加密图片路径不存在则返回"图片路径不存在"
:param self:
:param pic: 要加密的图片路径
:return: 返回加密的base64字符
"""
if self.os.path.exists(pic):
with open(pic, 'rb') as f:
read_pic = open(pic, 'rb')
read_data = read_pic.read()
read_pic.close()
return self.base64.b64encode(read_data)
else:
return "图片路径不存在"
@staticmethod
def base64_decode_pic(self, pic_bs64):
"""
Base64解密图片
:param self:
:param pic_bs64:
:return: 返回图片路径
"""
pic_path = f"upload/temp/pic{int(self.time.time())}"
if self.os.path.exists(f"{pic_path}.jpg"):
self.os.remove(f"{pic_path}.jpg")
elif not self.os.path.exists("upload/temp/pic"):
self.os.path.mkdir("upload/temp/pic")
with open(f"{pic_path}.jpg", 'wb') as f:
f.write(self.base64.b64decode(pic_bs64))
return f"{pic_path}.jpg"