1. 程式人生 > >Python自帶的hmac模塊

Python自帶的hmac模塊

dom __init__ hash pre 代碼 world 使用 需要 標準

Python自帶的hmac模塊實現了標準的Hmac算法

我們首先需要準備待計算的原始消息message,隨機key,哈希算法,這裏采用MD5,使用hmac的代碼如下:

import hmac
message = bHello world
key = bsecret
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)

Python自帶的hmac模塊