For cryptographic related operations, the 3.x replaces the MD5 module and the SHA module, mainly providing SHA1, SHA224, SHA256, SHA384, SHA512, MD5 algorithm
| 1234567891011121314 |
importhashlibm=hashlib.md5()# m=hashlib.sha256()m.update(‘hello‘.encode(‘utf8‘))print(m.hexdigest()) #5d41402abc4b2a76b9719d911017c592m.update(‘alvin‘.encode(‘utf8‘))print(m.hexdigest()) #92a7e713c30abbb0319fa07da2a5c4afm2=hashlib.md5()m2.update(‘helloalvin‘.encode(‘utf8‘))print(m2.hexdigest()) #92a7e713c30abbb0319fa07da2a5c4af |
Although the above encryption algorithm is still very strong, but the time has the flaw, namely: through the collision library can reverse the solution. Therefore, it is necessary to add a custom key to the encryption algorithm to do encryption.
| 1234567 |
importhashlib# ######## 256 ########hash= hashlib.sha256(‘898oaFs09f‘.encode(‘utf8‘))hash.update(‘alvin‘.encode(‘utf8‘))print(hash.hexdigest())#e79e68f070cdedcfe63eaf1a2e92c83b4cfb1b5c6bc452d214c1b7e77cdfd1c7 |
Python also has an HMAC module that internally creates key and content for us to process and then encrypt:
| 1234 |
importhmach = hmac.new(‘alvin‘.encode(‘utf8‘))h.update(‘hello‘.encode(‘utf8‘))print(h.hexdigest())#320df9832eab4c038b6c1d7ed73a5940 |
Python hashlib Module