hmac模块的使用(python)

  • new(key,msg=None,digestmod)方法

  1. 创建哈希对象
  2. key和digestmod参数必须指定,key和msg(需要加密的内容)均为bytes类型,digestmod指定加密算法,比如‘md5’,'sha1'等。
import hmac
h1 = hmac.new(b'hash',b'helloworld',digestmod='sha1') #创建哈希对象,一次性传入需要加密的内容,指定加密算法sha1

print(h1) #<hmac.HMAC at 0x7fe9fc961220>
  • 对象update(bytes)方法

  1. 如果文件较大,可以通过多次update()的方式传入内容,只要内容最后累加到一起相同,结果就不变.
h2 = hmac.new(b'hash',b'hello',digestmod='sha1') #创建h2对象时先传入部分内容

h2.update(b'world') #再传入剩下内容

h3 = hmac.new(b'hash',digestmod='sha1') #创建h3对象时,先不传入内容

h3.update(b'hello') #通过update的方式传入部分内容

h3.update(b'world')#再通过update的方式传入剩下部分内容

h1.hexdigest() #不同传入方式,但是传入的内容拼接起来都是b'helloworld',最后加密后的哈希值都一样
#'854276942fbdab217767515057a133474fb0fd83'

h2.hexdigest()
#'854276942fbdab217767515057a133474fb0fd83'

h3.hexdigest()
#'854276942fbdab217767515057a133474fb0fd83'
  • 简单示例

    import hmac
    message = b'Hello world'
    key = b'secret'
    h = hmac.new(key,message,digestmod='MD5')
    print(h.hexdigest())
    
    
    
    
    #封装
    def hmac_md5(key, s):
        return hmac.new(key.encode('utf-8'), s.encode('utf-8'), 'MD5').hexdigest()
    
    class User(object):
        def __init__(self, username, password):
            self.username = username
            self.key = ''.join([chr(random.randint(48, 122)) for i in range(20)])
            self.password = hmac_md5(self.key, password)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值