Python hashlib和hmac模組,pythonhashlibhmac

來源:互聯網
上載者:User

Python hashlib和hmac模組,pythonhashlibhmac

Python中的用於加密的函數位於hashlib,hmac模組中,都是內建模組,直接匯入即可使用

hashlib模組實現了md5,sha1,sha224,sha256,sha384,sha512等演算法,可以通過hashlib.algorithms_available查看

hmac模組實現了hmac演算法,需要一個key來進行加密


hashlib用法如下:
 
#匯入hashlib模組
>>> import hashlib
 
#python可用的加密函數
>>> hashlib.algorithms_available
{'sha384', 'DSA', 'SHA224', 'sha1','sha224', 'SHA384', 'ripemd160', 'MD5', 'whirlpool', 'SHA', 'MD4', 'SHA512','ecdsa-with-SHA1', 'dsaWithSHA', 'md5', 'sha256', 'DSA-SHA', 'SHA1', 'RIPEMD160','sha', 'md4', 'SHA256', 'dsaEncryption', 'sha512'}
 
#python在所有平台上都可以使用的函數,也就是比較穩定的函數
>>> hashlib.algorithms_guaranteed
{'md5', 'sha256', 'sha384', 'sha1','sha224', 'sha512'}
 
#建立一個加密函數對象
>>> m = hashlib.md5()
>>> m.update(b'python isinteresting')
>>> m.hexdigest()
'f00243cac6d9aa2d320ed5603061483b'

>>> mySha1 = hashlib.sha1()
>>> mySha1.update(b'python is interesting')
>>> mySha1.hexdigest()
'6ad9d2ccb5fe1d5324092bdac233b4ee49d71cb8'


#如果有中文的話,使用gb2312編碼
>>> myMd5 = hashlib.md5('python 真好玩'.encode('gb2312'))
>>> myMd5.hexdigest()
'6c0f33c5f4b96f1aa771bf432ba53002'


hmac用法如下:

>>> import hmac
>>> myhmac = hmac.new(b'mykey')
>>> myhmac.update(b'mymessage')
>>> myhmac.hexdigest()
'd811630c4e62c6ef90d1bfe540212aaf'




聯繫我們

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