Python自帶的hmac模塊實現了標准的Hmac算法
我們首先需要准備待計算的原始消息message,隨機key,哈希算法,這里采用MD5,使用hmac的代碼如下:
import hmac message = b'Hello world' key = b'secret' h = hmac.new(key,message,digestmod='MD5') print(h.hexdigest())
可見使用hmac和普通hash算法非常類似。hmac輸出的長度和原始哈希算法的長度一致。需要注意傳入的key和message都是bytes
類型,str
類型需要首先編碼為bytes
。
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)