侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Python hmac模块使用实例解析

Python  /  管理员 发布于 7年前   206

这篇文章主要介绍了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:加密的内容,# 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:加密的内容,# digestmod:加密的方式digest = digest_maker.digest() # 默认内容是字节类型,所以需要base64print(base64.encodebytes(digest)) #注意base64结果是以\n结束,所以Http头部或其它传输时,需要去除\n

运行效果

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

4、hmac摘要数据比较示例

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# 输出缓冲区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) # 将消息头写入缓冲区out_s.write(pickle_data) # 将序列化内容写入缓冲区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) # 将消息头写入缓冲区out_s.write(pickle_data) # 将序列化内容写入缓冲区out_s.flush() # 刷新缓冲区# 输入缓冲区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('数据不完整')

运行效果

[root@ mnt]# python3 hmac_pickle.py 提示:b'00e080735a8de379e19fe2aa731c92fc9253a6e2  69\n'提示:b'1d147690f94ea374f6f8c3767bd5a5f9a8989a53  78\n'读取到: b'00e080735a8de379e19fe2aa731c92fc9253a6e2' 69实际值: b'00e080735a8de379e19fe2aa731c92fc9253a6e2'OK: digest matches读取到: b'1d147690f94ea374f6f8c3767bd5a5f9a8989a53' 78实际值: b'4dcaad9b05bbb67b571a64defa52e8960a27c45d'数据不完整

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    Python concurrent.futures模块使用实例
    下一条:
    Python hashlib模块实例使用详解
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客