# This is a learning note for the Liaoche teacher Python tutorial
1. Overview
If the salt is generated randomly by ourselves, we usually use MD5 (message + salt) when we calculate MD5. This is actually the HMAC algorithm : keyed-hashing for Message authentication. It uses a standard algorithm that, in the process of calculating the hash, mixes the key into the calculation process .
The HMAC algorithm is generic for all hashing algorithms, whether MD5 or SHA-1. Using HMAC instead of our own salt algorithm can make the program algorithm more standardized and more secure.
The HMAC module implements the standard HMAC algorithm, which uses a key to compute the hash of the message "hash", using the HMAC algorithm to be more secure than the standard hash algorithm, because different keys produce different hashes for the same message
>>> Import HMAC
>>> message = B ' Hello, world! '
>>> key = B ' secret '
>>> h = hmac.new(key, message, digestmod= ' MD5 ')
>>> # h.update (msg) can be called multiple times if the message is long
>>> H. hexdigest ()
' FA4EE7D173F2D97EE79022D1A7355BCF '
the length of the HMAC output is the same as the length of the original hash algorithm. Note that both the key and message passed in are bytes types, andthestr type needs to be encoded first as bytes.
2 , examples
Change the salt of the previous section to the standard HMAC algorithm and verify the user password:
#-*-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 (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)
Python Learning note __12.6 HMAC