国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發(fā) > Python > 正文

Python hmac模塊使用實例解析

2024-09-09 19:03:26
字體:
來源:轉載
供稿:網(wǎng)友

這篇文章主要介紹了Python hmac模塊使用實例解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

hmac模塊的作用:

用于驗證信息的完整性。

1、hmac消息簽名(默認使用MD5加算法)

hmac_md5.py

#!/usr/bin/env python# -*- coding: utf-8 -*-import hmac#默認使用是md5算法digest_maker = hmac.new('secret-shared-key'.encode('utf-8'))with open('content.txt', 'rb') as f:  while True:    block = f.read(1024)    if not block:      break    digest_maker.update(block)digest = digest_maker.hexdigest()print(digest)

content.txt

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donecegestas, enim et consectetuer ullamcorper, lectus ligula rutrum leo, aelementum elit tortor eu quam. Duis tincidunt nisi ut ante. Nullafacilisi. Sed tristique eros eu libero. Pellentesque vel arcu. Vivamuspurus orci, iaculis ac, suscipit sit amet, pulvinar eu,lacus. Praesent placerat tortor sed nisl. Nunc blandit diam egestasdui. Pellentesque habitant morbi tristique senectus et netus etmalesuada fames ac turpis egestas. Aliquam viverra fringillaleo. Nulla feugiat augue eleifend nulla. Vivamus mauris. Vivamus sedmauris in nibh placerat egestas. Suspendisse potenti. Mauris massa. Uteget velit auctor tortor blandit sollicitudin. Suspendisse imperdietjusto.

運行效果

[root@ mnt]# python3 hmac_md5.py 79cbf5942e8f67be558bc28610c02117

2、hmac消息簽名摘要(使用SHA1加算法)

hmac_sha1.py

#!/usr/bin/env python# -*- coding: utf-8 -*-import hmacdigest_maker = hmac.new('secret-shared-key'.encode('utf-8'), b'', digestmod='sha1')# hmac.new(key,msg,digestmod)# key:加鹽的key,# msg:加密的內(nèi)容,# digestmod:加密的方式with open('hmac_sha1.py', 'rb') as f:  while True:    block = f.read(1024)    if not block:      break    digest_maker.update(block)digest = digest_maker.hexdigest()print(digest)

運行效果

[root@ mnt]# python3 hmac_sha1.py e5c012eac5fa76a274f77ee678e6cc98cad8fff9

3、hmac二進制消息簽名摘要(使用SHA1加算法)

hmac_base64.py

#!/usr/bin/env python# -*- coding: utf-8 -*-import hmacimport base64import hashlibwith open('test.py', 'rb') as f:  body = f.read()# 默認使用是md5算法digest_maker = hmac.new('secret-shared-key'.encode('utf-8'), body, hashlib.sha1)# hmac.new(key,msg,digestmod)# key:加鹽的key,# msg:加密的內(nèi)容,# digestmod:加密的方式digest = digest_maker.digest() # 默認內(nèi)容是字節(jié)類型,所以需要base64print(base64.encodebytes(digest)) #注意base64結果是以/n結束,所以Http頭部或其它傳輸時,需要去除/n

運行效果

[root@ mnt]# python3 hmac_base64.py b'Y9a4OMRqU4DB6Ks/hGfru+MNXAw=/n'

4、hmac摘要數(shù)據(jù)比較示例

hmac_pickle.py

#!/usr/bin/env python# -*- coding: utf-8 -*-import hashlibimport hmacimport ioimport pickledef make_digest(message):  "返消息摘要,加密碼后的結果"  hash = hmac.new(    'secret-shared-key'.encode('utf-8'),    message,    hashlib.sha1  )  return hash.hexdigest().encode('utf-8')class SimpleObject(object):  def __init__(self, name):    self.name = name  def __str__(self):    return self.name# 輸出緩沖區(qū)out_s = io.BytesIO()o = SimpleObject('digest matches')pickle_data = pickle.dumps(o) # 序列化digest = make_digest(pickle_data) # 使用sha1加密算法header = b'%s  %d/n' % (digest, len(pickle_data))print('提示:{}'.format(header))out_s.write(header) # 將消息頭寫入緩沖區(qū)out_s.write(pickle_data) # 將序列化內(nèi)容寫入緩沖區(qū)o = SimpleObject('digest does not matches')pickle_data = pickle.dumps(o)digest = make_digest(b'not the pickled data at all')header = b'%s  %d/n' % (digest, len(pickle_data))print('提示:{}'.format(header))out_s.write(header) # 將消息頭寫入緩沖區(qū)out_s.write(pickle_data) # 將序列化內(nèi)容寫入緩沖區(qū)out_s.flush() # 刷新緩沖區(qū)# 輸入緩沖區(qū)in_s = io.BytesIO(out_s.getvalue())while True:  first_line = in_s.readline()  if not first_line:    break  incoming_digest, incoming_length = first_line.split(b'  ')  incoming_length = int(incoming_length.decode('utf-8'))  print('讀取到:', incoming_digest, incoming_length)  incoming_pickled_data = in_s.read(incoming_length)  actual_digest = make_digest(incoming_pickled_data) # 實際的摘要  print('實際值:', actual_digest)  if hmac.compare_digest(actual_digest, incoming_digest): # 比較兩個摘要是否相等    obj = pickle.loads(incoming_pickled_data)    print('OK:', obj)  else:    print('數(shù)據(jù)不完整')
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 乐东| 锡林郭勒盟| 西宁市| 绍兴市| 义乌市| 玛纳斯县| 青州市| 兴城市| 北海市| 平果县| 淮滨县| 化隆| 宜黄县| 凤冈县| 济南市| 白朗县| 连南| 尖扎县| 本溪| 南江县| 永新县| 稷山县| 绵阳市| 太和县| 囊谦县| 利辛县| 茶陵县| 黑龙江省| 清镇市| 云阳县| 息烽县| 平邑县| 漯河市| 灌南县| 锡林浩特市| 新余市| 德钦县| 藁城市| 林口县| 凌云县| 舞钢市|