Python用摘要算法生成token及檢驗(yàn)token的示例代碼
# 基礎(chǔ)版,不依賴環(huán)境
import time
import base64
import hashlib
class Token_hander():
def __init__(self,out_time):
self.out_time = out_time
self.time = self.timer
pass
def timer(self):
return time.time()
def hax(self,str):
"""
摘要算法加密
:param str: 待加密字符串
:return: 加密后的字符串
"""
if not isinstance(str,bytes): # 如果傳入不是bytes類型,則轉(zhuǎn)為bytes類型
try:
str = bytes(str,encoding="utf8")
except BaseException as ex:
raise ValueError("'%s'不可被轉(zhuǎn)換為bytes類型"%str)
md5 = hashlib.md5()
md5.update("天王蓋地虎erafe23".encode(encoding='utf-8'))
md5.update(str)
md5.update("992ksd上山打老虎da".encode(encoding='utf-8'))
return md5.hexdigest()
def build_token(self,message):
"""
hax_message: 待加密字符串內(nèi)容 格式: '當(dāng)前時(shí)間戳:message:過期時(shí)間戳'
:param message: 需要生成token的字符串
:param time: 過期時(shí)間
:return: token
"""
hax_message = "%s:%s:%s"%(str(self.time()),message,
str(float(self.time())+float(self.out_time)))
hax_res = self.hax(hax_message)
token = base64.urlsafe_b64encode(("%s:%s"%(hax_message,hax_res)).encode(encoding='utf-8'))
return token.decode("utf-8")
def check_token(self,token):
"""
:param token: 待檢驗(yàn)的token
:return: False or new token
"""
try:
hax_res = base64.urlsafe_b64decode(token.encode("utf8")).decode("utf-8")
message_list = hax_res.split(":")
md5 = message_list.pop(-1)
message = ':'.join(message_list)
if md5 != self.hax(message):
# 加密內(nèi)容如果與加密后的結(jié)果不符即token不合法
return False
else:
if self.time() - float(message_list.pop(-1)) >0:
# 超時(shí)返回False
return False
else:
# token驗(yàn)證成功返回新的token
return self.build_token(message_list.pop(-1))
except BaseException as ex:
# 有異常表明驗(yàn)證失敗或者傳入?yún)?shù)不合法
return False
# 測試
if __name__ == '__main__':
token_hand = Token_hander(5)
token = token_hand.build_token(b'dxxx')
print(token_hand.check_token(token))
time.sleep(5)
print(token_hand.check_token(token))
# 封裝成Django源碼版
# 依賴Django運(yùn)行環(huán)境,不可單獨(dú)測試,需運(yùn)行Django環(huán)境,
# 需要在settings配置文件中配置 OUT_TIME = 時(shí)間 ,以秒為單位
import os
import time
import base64
import hashlib
import importlib
ENVIRONMENT_VARIABLE = "DJANGO_SETTINGS_MODULE"
class Token_hander():
def __init__(self):
self.out_time = self.getOutTime()
self.time = self.timer
pass
def timer(self):
return time.time()
def getOutTime(self):
module = importlib.import_module(os.environ.get(ENVIRONMENT_VARIABLE))
return getattr(module, "OUT_TIME",60) # 在settings配置文件中找 OUT_TIME 變量,如果沒有,默認(rèn)60秒
def hax(self,str):
"""
摘要算法加密
:param str: 待加密字符串
:return: 加密后的字符串
"""
if not isinstance(str,bytes): # 如果傳入不是bytes類型,則轉(zhuǎn)為bytes類型
try:
str = bytes(str,encoding="utf8")
except BaseException as ex:
raise ValueError("'%s'不可被轉(zhuǎn)換為bytes類型"%str)
md5 = hashlib.md5()
md5.update("天王蓋地虎erafe23".encode(encoding='utf-8'))
md5.update(str)
md5.update("992ksd上山打老虎da".encode(encoding='utf-8'))
return md5.hexdigest()
def build_token(self,message):
"""
hax_message: 待加密字符串內(nèi)容 格式: '當(dāng)前時(shí)間戳:message:過期時(shí)間戳'
:param message: 需要生成token的字符串
:param time: 過期時(shí)間
:return: token
"""
hax_message = "%s:%s:%s"%(str(self.time()),message,
str(float(self.time())+float(self.out_time)))
hax_res = self.hax(hax_message)
token = base64.urlsafe_b64encode(("%s:%s"%(hax_message,hax_res)).encode(encoding='utf-8'))
return token.decode("utf-8")
def check_token(self,token):
"""
:param token: 待檢驗(yàn)的token
:return: False or new token
"""
try:
hax_res = base64.urlsafe_b64decode(token.encode("utf8")).decode("utf-8")
message_list = hax_res.split(":")
md5 = message_list.pop(-1)
message = ':'.join(message_list)
if md5 != self.hax(message):
# 加密內(nèi)容如果與加密后的結(jié)果不符即token不合法
return False
else:
if self.time() - float(message_list.pop(-1)) >0:
# 超時(shí)返回False
return False
else:
# token驗(yàn)證成功返回新的token
return self.build_token(message_list.pop(-1))
except BaseException as ex:
# 有異常表明驗(yàn)證失敗或者傳入?yún)?shù)不合法
return False
# 封裝成Django模塊,也依賴Django運(yùn)行環(huán)境
# 需要在settings配置文件中配置 OUT_TIME = 時(shí)間 , 秒為單位
import time
import base64
import hashlib
from django.conf import settings
class Token_hander():
def __init__(self):
self.out_time = self.getOutTime()
self.time = self.timer
pass
def timer(self):
return time.time()
def getOutTime(self):
try:
return settings.__getattr__("OUT_time") # 在導(dǎo)入的settings中找 OUT_TIME 變量
except BaseException:
return 60 # 找不到默認(rèn)60 也可以設(shè)置直接拋異常
def hax(self,str):
"""
摘要算法加密
:param str: 待加密字符串
:return: 加密后的字符串
"""
if not isinstance(str,bytes): # 如果傳入不是bytes類型,則轉(zhuǎn)為bytes類型
try:
str = bytes(str,encoding="utf8")
except BaseException as ex:
raise ValueError("'%s'不可被轉(zhuǎn)換為bytes類型"%str)
md5 = hashlib.md5()
md5.update("天王蓋地虎erafe23".encode(encoding='utf-8'))
md5.update(str)
md5.update("992ksd上山打老虎da".encode(encoding='utf-8'))
return md5.hexdigest()
def build_token(self,message):
"""
hax_message: 待加密字符串內(nèi)容 格式: '當(dāng)前時(shí)間戳:message:過期時(shí)間戳'
:param message: 需要生成token的字符串
:param time: 過期時(shí)間
:return: token
"""
hax_message = "%s:%s:%s"%(str(self.time()),message,
str(float(self.time())+float(self.out_time)))
hax_res = self.hax(hax_message)
token = base64.urlsafe_b64encode(("%s:%s"%(hax_message,hax_res)).encode(encoding='utf-8'))
return token.decode("utf-8")
def check_token(self,token):
"""
:param token: 待檢驗(yàn)的token
:return: False or new token
"""
try:
hax_res = base64.urlsafe_b64decode(token.encode("utf8")).decode("utf-8")
message_list = hax_res.split(":")
md5 = message_list.pop(-1)
message = ':'.join(message_list)
if md5 != self.hax(message):
# 加密內(nèi)容如果與加密后的結(jié)果不符即token不合法
return False
else:
if self.time() - float(message_list.pop(-1)) >0:
# 超時(shí)返回False
return False
else:
# token驗(yàn)證成功返回新的token
return self.build_token(message_list.pop(-1))
except BaseException as ex:
# 有異常表明驗(yàn)證失敗或者傳入?yún)?shù)不合法
return False
以上就是Python用摘要算法生成token及檢驗(yàn)token的示例代碼的詳細(xì)內(nèi)容,更多關(guān)于Python用摘要算法生成token的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
pytorch 把MNIST數(shù)據(jù)集轉(zhuǎn)換成圖片和txt的方法
這篇文章主要介紹了pytorch 把MNIST數(shù)據(jù)集轉(zhuǎn)換成圖片和txt的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-05-05
Python根據(jù)已知鄰接矩陣?yán)L制無向圖操作示例
這篇文章主要介紹了Python根據(jù)已知鄰接矩陣?yán)L制無向圖操作,涉及Python使用networkx、matplotlib進(jìn)行數(shù)值運(yùn)算與圖形繪制相關(guān)操作技巧,需要的朋友可以參考下2018-06-06
使用python實(shí)現(xiàn)名片管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了使用python實(shí)現(xiàn)名片管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-06-06
關(guān)于SSD目標(biāo)檢測模型的人臉口罩識別
這篇文章主要介紹了關(guān)于SSD目標(biāo)檢測模型的人臉口罩識別問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11
Python 3 實(shí)現(xiàn)定義跨模塊的全局變量和使用教程
這篇文章主要介紹了Python 3 實(shí)現(xiàn)定義跨模塊的全局變量和使用,本文通過實(shí)例代碼相結(jié)合的形式給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-07-07
Windows10+anacond+GPU+pytorch安裝詳細(xì)過程
這篇文章主要介紹了Windows10+anacond+GPU+pytorch安裝詳細(xì)過程,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-03-03
Python中operator模塊的操作符使用示例總結(jié)
operator模塊中包含了Python的各種內(nèi)置操作符,諸如邏輯、比較、計(jì)算等,這里我們針對一些常用的操作符來作一個(gè)Python中operator模塊的操作符使用示例總結(jié):2016-06-06
Windows系統(tǒng)下安裝tensorflow的配置步驟
這篇文章主要介紹了Windows系統(tǒng)下安裝tensorflow,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-07-07
Python使用matplotlib繪制Logistic曲線操作示例
這篇文章主要介紹了Python使用matplotlib繪制Logistic曲線操作,結(jié)合實(shí)例形式詳細(xì)分析了Python基于matplotlib庫繪制Logistic曲線相關(guān)步驟與實(shí)現(xiàn)技巧,需要的朋友可以參考下2019-11-11

