Python学习笔记__12.6章 hmac

# 这是学习廖雪峰老师python教程的学习笔记

1、概览

如果salt是我们自己随机生成的,通常我们计算MD5时采用md5(message + salt)。这实际上就是Hmac算法:Keyed-Hashing for Message Authentication。它通过一个标准算法,在计算哈希的过程中,把key混入计算过程中

Hmac算法针对所有哈希算法都通用,无论是MD5还是SHA-1。采用Hmac替代我们自己的salt算法,可以使程序算法更标准化,也更安全。

hmac模块实现了标准的Hmac算法,它利用一个key对message计算“杂凑”后的hash,使用hmac算法比标准hash算法更安全,因为针对相同的message,不同的key会产生不同的hash

>>> import hmac

>>> message = b'Hello, world!'

>>> key = b'secret'

>>> h = hmac.new(key, message, digestmod='MD5')

>>> # 如果消息很长,可以多次调用h.update(msg)

>>> h.hexdigest()

'fa4ee7d173f2d97ee79022d1a7355bcf'

hmac输出的长度和原始哈希算法的长度一致。需要注意传入的key和message都是bytes类型,str类型需要首先编码为bytes

2、例子

将上一节的salt改为标准的hmac算法,验证用户口令:

# -*- coding: utf-8 -*-

import hmac, random

 

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)

 

db = {

    'michael': User('michael', '123456'),

    'bob': User('bob', 'abc999'),

    'alice': User('alice', 'alice2008')

}

 

def login(username, password):

    user = db[username]

    return user.password == hmac_md5(user.key, password)


猜你喜欢

转载自blog.51cto.com/12758568/2117095