Python自帶的hmac模塊


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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM