Python's own HMAC module implements the standard HMAC algorithm
We first need to prepare the original message to be computed, a random key, a hash algorithm, where MD5 is used, and the code for the HMAC is as follows:
Import= b'HelloWorld'= b'secret' = hmac.new (key,message,digestmod='MD5')print( H.hexdigest ())
It can be seen that using HMAC is very similar to the normal hash algorithm. The length of the HMAC output is the same as the length of the original hash algorithm. Note that the key and message passed in are both bytes
types, and the str
type needs to be encoded first bytes
.
defHmac_md5 (Key, s):returnHmac.new (Key.encode ('Utf-8'), S.encode ('Utf-8'),'MD5'). Hexdigest ()classUser (object):def __init__(self, username, password): Self.username=username Self.key="'. Join ([Chr (Random.randint (48, 122)) forIinchRange (20)]) Self.password= HMAC_MD5 (self.key, password)
The HMAC module that comes with Python