Python hashlib模組 (主要記錄md5加密)

來源:互聯網
上載者:User

python提供了一個進行hash加密的模組:hashlib

下面主要記錄下其中的md5加密方式

>>> import hashlib>>> m = hashlib.md5()>>> m.update("Nobody inspects")>>> m.update(" the spammish repetition")>>> m.digest()'\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9'>>> m.hexdigest()'bb649c83dd1ea5c9d9dec9a18df0ffe9'

對以上代碼的說明:

1.首先從python直接匯入hashlib模組

2.調用hashlib裡的md5()產生一個md5 hash對象

3.產生hash對象後,就可以用update方法對字串進行md5加密的更新處理

4.繼續調用update方法會在前面加密的基礎上更新加密

5.加密後的二進位結果

6.十六進位結果

如果只需對一條字串進行加密處理,也可以用一條語句的方式:

>>>print hashlib.new("md5", "Nobody inspects the spammish repetition").hexdigest()'bb649c83dd1ea5c9d9dec9a18df0ffe9'

引用官方文檔部分:

The following values are provided as constant attributes of the hash objects returned by the constructors:

hash.digest_size

The size of the resulting hash in bytes.

hash.block_size

The internal block size of the hash algorithm in bytes.

A hash object has the following methods:

hash.update(arg)

Update the hash object with the string arg. Repeated calls are equivalent to a single call with the concatenation of all the arguments: m.update(a); m.update(b) is equivalent to m.update(a+b).

hash.digest()

Return the digest of the strings passed to the update() method so far. This is a string of digest_size bytes which may contain non-ASCII characters, including null bytes.

hash.hexdigest()

Like digest() except the digest is returned as a string of double length, containing only hexadecimal digits. This may be used to exchange the value safely in email or other non-binary environments.

hash.copy()

Return a copy (“clone”) of the hash object. This can be used to efficiently compute the digests of strings that share a common initial substring.

相關文章

聯繫我們

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