Python 中的消息认证密钥散列


使用 Python 中的加密哈希函数进行消息认证可以通过 HMAC 机制实现。我们可以将 HMAC 与多个可迭代的哈希函数(如 MD5、SHA-1)结合一个共享密钥一起使用。

基本思想是通过生成实际数据与共享密钥组合的加密哈希来保护我们的数据。最终结果在不包含密钥的情况下发送,但生成的哈希值可用于检查传输或存储的消息。

语法

hmac.new(key, msg = None, digestmod = None)

返回一个生成新的 hmac 对象。

其中 -

  • Key – 这里的共享密钥。

  • Msg – 要散列的消息,这里是要散列的消息

  • Digestmod – HMAC 对象要使用的摘要名称或模块

HMAC 模块的方法和属性 -

  • hmac.update(message)

    用于使用给定消息更新 hmac 对象。如果多次调用此方法,消息将被追加。

  • hmac.digest()

    返回迄今为止传递给 update() 方法的字节的摘要。

  • hashlib.hexdigest()

    与 digest() 相同,只是摘要作为长度的两倍的字符串返回,仅包含十六进制数字。这可用于在电子邮件或其他非二进制环境中安全地交换值。

  • haslib.copy()

    返回 hmac 对象的副本(“克隆”)。

示例 1

使用默认的 MD5 散列算法创建散列。

 在线演示

#Import libraries
import hashlib
import hmac
#data
update_bytes = b'Lorem ipsum dolor sit amet, consectetur adipiscing elit. \
   Suspendisse tristique condimentum viverra. Nulla accumsan \
   orci risus, non congue lacus feugiat id.'
#secret key
password = b'402xy5#'
#Generate cryptographic hash using md5
my_hmac = hmac.new(update_bytes, password, hashlib.md5)
print("The first digest: " + str(my_hmac.digest()))
print("The Canonical Name: " + my_hmac.name)
print("Block size: " + str (my_hmac.block_size) + "bytes")
print("Digest size: " + str(my_hmac.digest_size) + "bytes")
#Create a copy of the hmac object
my_hmac_cpy = my_hmac.copy()
print("The Copied digest: " + str(my_hmac_cpy.digest()))

输出

The first digest: b'H\xcc.nf\xdd\x8bC\x8di\x0cC\xb8\xe9l\xa8'
The Canonical Name: hmac-md5
Block size: 64bytes
Digest size: 16bytes
The Copied digest: b'H\xcc.nf\xdd\x8bC\x8di\x0cC\xb8\xe9l\xa8'

由于 SHA1 比 MD5 算法更安全,如果您考虑使用 SHA1 算法运行上述程序。只需在此行中修改算法名称,

my_hmac = hmac.new(update_bytes, password,hashlib.sha1)
我们的结果将类似于

第一个摘要:b'\xc3T\xe7[\xc8\xa3O/$\xbd`A\xad\x07d\xe8\xae\xa2!\xb4'

The Canonical Name: hmac-sha1
Block size: 64bytes
Digest size: 20bytes
The Copied digest: b'\xc3T\xe7[\xc8\xa3O/$\xbd`A\xad\x07d\xe8\xae\xa2!\xb4'

应用

HMAC 身份验证机制可用于任何重视安全性的场所,例如公共网络服务。例如,在公共网络中,我们通过管道或套接字发送重要的文件/数据,该文件/数据应先进行签名,然后在使用数据之前测试签名。

更新于:2019-07-30

746 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.