如何在Python中使用hmac模块

发布时间:2021-03-18 16:28:44 作者:Leah
来源:亿速云 阅读:354

这篇文章将为大家详细讲解有关如何在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. Donec
egestas, enim et consectetuer ullamcorper, lectus ligula rutrum leo, a
elementum elit tortor eu quam. Duis tincidunt nisi ut ante. Nulla
facilisi. Sed tristique eros eu libero. Pellentesque vel arcu. Vivamus
purus orci, iaculis ac, suscipit sit amet, pulvinar eu,
lacus. Praesent placerat tortor sed nisl. Nunc blandit diam egestas
dui. Pellentesque habitant morbi tristique senectus et netus et
malesuada fames ac turpis egestas. Aliquam viverra fringilla
leo. Nulla feugiat augue eleifend nulla. Vivamus mauris. Vivamus sed
mauris in nibh placerat egestas. Suspendisse potenti. Mauris massa. Ut
eget velit auctor tortor blandit sollicitudin. Suspendisse imperdiet
justo.

运行效果

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

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

hmac_sha1.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import hmac

digest_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 hmac
import base64
import hashlib

with 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() # 默认内容是字节类型,所以需要base64
print(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 hashlib
import hmac
import io
import pickle

def 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中使用hmac模块就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. python 摘要:hmac
  2. xml模块/configparser模块/hashlib模块/hmac模块

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python hmac

上一篇:怎么在Python项目中使用hashlib模块

下一篇:怎么在python中安装tkinter模块

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》