Python的hashlib模組學習

來源:互聯網
上載者:User

標籤:hashlib

python的hashlib模組提供一些常用的加密功能


例如擷取字串‘Nobody inspects the spammish repetition‘的MD5校正值

In [48]: import hashlibIn [49]: m=hashlib.md5()In [50]: m.update(‘Nobody inspects‘)In [51]: m.update(‘the spammish repetition‘)In [52]: m.digest()Out[52]: ‘%\x8d3\xf9,:k\xe0?\xbb0+\xc4K\x94S‘In [53]: m.digest_sizeOut[53]: 16In [54]: m.block_sizeOut[54]: 64In [55]: m.hexdigest()Out[55]: ‘258d33f92c3a6be03fbb302bc44b9453‘In [56]: m.digest_sizeOut[56]: 16In [57]: m.block_sizeOut[57]: 64



這裡定義一個HASH對象m,使用hashlib模組提供的md5()函數,還可以是

md5(), sha1(), sha224(), sha256(), sha384(), and sha512()

也可以根據作業系統提供的HASH演算法,使用new()選擇OpenSSL庫提供的密碼編譯演算法

sha384和sha512在32位系統上使用會比較慢


update(arg)  更新HASH對象,重複使用update(arg)等價於一次更新多個字串的組合

         m.update(a)和m.update(b)等價於m.update(a+b)



digest()   返回加密後的字串

hexdigest()  返回加密碼後的16進位字串


digest_size  是加密後的雜湊值位元組

block_size  資料區塊大小





案例:

def getMd5(strFile):    fh=open(strFile,"rb")    m=md5()    strRead=""    while True:          strRead=fh.read()          if not strRead:             break          m.update(strRead)    strMd5=m.hexdigest()    if fh:       fh.close()    return strMd5print getMd5(__file__)









參考文章:

https://docs.python.org/2.6/library/hashlib.html


本文出自 “Linux SA John” 部落格,請務必保留此出處http://john88wang.blog.51cto.com/2165294/1668757

Python的hashlib模組學習

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.