个性化阅读
专注于IT技术分析

Python hmac –消息身份验证的键哈希介绍

HMAC是使用密码哈希函数进行消息身份验证的机制。 HMAC可以与任何秘密的加密哈希函数(例如MD5, SHA-1)结合使用, 并与秘密共享密钥结合使用。

该模块实现了HMAC算法。基本思想是生成与共享密钥组合的实际数据的加密哈希。然后, 可以将所得的哈希用于检查传输或存储的消息以确定信任级别, 而无需传输密钥。

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

返回一个新的hmac对象。键是提供密钥的字节或字节数组对象。如果味精存在时, 将进行方法调用update(msg)。摘要模式是要使用的HMAC对象的摘要名称, 摘要构造函数或模块。它支持适用于hashlib.new()的任何名称。

HMAC对象具有以下方法:

  1. HMAC.update(msg):此方法使用msg更新hmac对象。重复调用等效于将所有参数串联在一起的单个调用:m.update(a); m.update(b)等同于m.update(a + b)。
  2. HMAC.digest():此方法返回到目前为止传递给update()方法的字节的摘要。该字节对象的长度与提供给构造函数的摘要的digest_size相同。
  3. HMAC.hexdigest():此方法类似于digest()方法, 不同之处在于摘要以字符串形式返回, 该字符串的长度是仅包含十六进制数字的长度的两倍。
  4. HMAC.copy():此方法返回hmac对象的副本或克隆。这可用于有效地计算共享公共初始子字符串的字符串的摘要。

哈希对象具有以下属性:

  • HMAC.digest_size:生成的HMAC摘要的大小(以字节为单位)。
  • HMAC.block_size:哈希算法的内部块大小(以字节为单位)。
  • HMAC。名称:此HMAC的规范名称。例如hmac-sha1。

例子:

# Python 3 code to demonstrate the working of hmac module.
  
import hmac
import hashlib
  
# creating new hmac object using sha1 hash algorithm
digest_maker = hmac.new(b 'secret-key' , b 'msg' , hashlib.sha1)
  
# print the Hexdigest of the bytes passed to update
print ( "Hexdigest: " + digest_maker.hexdigest())
  
# call update to update msg
digest_maker.update(b 'another msg' )
  
# print the Hexdigest of the bytes passed to update
print ( "Hexdigest after update: " + digest_maker.hexdigest())
  
print ( "Digest size: " + str (digest_maker.digest_size) + " bytes" )
print ( "Block size: " + str (digest_maker.block_size) + " bytes" )
print ( "Canonical name: " + digest_maker.name)
  
# print the digest of the bytes passed to update
print ( "Digest: " , end = " " )
print (digest_maker.digest())
  
# create a copy of the hmac object
digest_clone = digest_maker.copy()
print ( "Hexdigest of clone: " + digest_clone.hexdigest())

输出如下:

Hexdigest: df2ae7cdb5c849001e33ee29eb1c51ba2cafbaa7
Hexdigest after update: 3923273eb3aa9328478eb5aabf2d96e185256b4b
Digest size: 20 bytes
Block size: 64 bytes
Canonical name: hmac-sha1
Digest:  b"9#'>\xb3\xaa\x93(G\x8e\xb5\xaa\xbf-\x96\xe1\x85%kK"
Hexdigest of clone: 3923273eb3aa9328478eb5aabf2d96e185256b4b

如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。

赞(0)
未经允许不得转载:srcmini » Python hmac –消息身份验证的键哈希介绍

评论 抢沙发

评论前必须登录!