Python學習筆記__12.6章 hmac

來源:互聯網
上載者:User

標籤:程式設計語言   Python   

# 這是學習廖雪峰老師python教程的學習筆記

1、概覽

如果salt是我們自己隨機產生的,通常我們計算MD5時採用md5(message + salt)。這實際上就是Hmac演算法:Keyed-Hashing for Message Authentication。它通過一個標準演算法,在計算雜湊的過程中,把key混入計算過程中。

Hmac演算法針對所有雜湊演算法都通用,無論是MD5還是SHA-1。採用Hmac替代我們自己的salt演算法,可以使程式演算法更標準化,也更安全。

hmac模組實現了標準的Hmac演算法,它利用一個key對message計算“雜湊”後的hash,使用hmac演算法比標準hash演算法更安全,因為針對相同的message,不同的key會產生不同的hash

>>> import hmac

>>> message = b'Hello, world!'

>>> key = b'secret'

>>> h = hmac.new(key, message, digestmod='MD5')

>>> # 如果訊息很長,可以多次調用h.update(msg)

>>> h.hexdigest()

'fa4ee7d173f2d97ee79022d1a7355bcf'

hmac輸出的長度和原始雜湊演算法的長度一致。需要注意傳入的key和message都是bytes類型,str類型需要首先編碼為bytes。

2、例子

將上一節的salt改為標準的hmac演算法,驗證使用者口令:

# -*- 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(48, 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學習筆記__12.6章 hmac

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.