Python hashlib and hmac modules, pythonhashlibhmac
The functions used for encryption in Python are located in hashlib and hmac modules. They are all built-in modules and can be used after direct import.
The hashlib module implements algorithms such as md5, sha1, shaloud, sha256, sha384, and sha512, which can be viewed through hashlib. algorithms_available.
The hmac module implements the hmac algorithm and requires a key for encryption.
Hashlib is used as follows:
# Import the hashlib Module
>>> Import hashlib
# Available python encryption functions
>>> Hashlib. algorithms_available
{'Sha384', 'dsa ', 'shashaobao', 'shashasha1', 'sha384', 'ripmd160', 'md5', 'whirlpool ', 'sha', 'md4', 'sha512', 'ecdsa-with-SHA1 ', 'dsawithsha', 'md5', 'sha256', 'dsa-Sha', 'sha1 ', 'ripmd160 ', 'sha', 'md4', 'sha256', 'dsaencryption ', 'sha512 '}
# Functions that python can use on all platforms, that is, relatively stable Functions
>>> Hashlib. algorithms_guaranteed
{'Md5', 'sha256 ', 'sha384', 'shaa1', 'shawei', 'sha512 '}
# Create an encryption function object
>>> M = hashlib. md5 ()
>>> M. update (B 'python isinteresting ')
>>> M. hexdigest ()
'F00243cac6d9aa2d320ed5603061483b'
>>> MySha1 = hashlib. sha1 ()
>>> MySha1.update (B 'python is interesting ')
>>> MySha1.hexdigest ()
'6ad9d2ccb5fe1d5324092bdac233b4ee49d71cb8'
# Use gb2312 encoding if you have any Chinese Characters
>>> MyMd5 = hashlib. md5 ('python is really fun '. encode ('gb2312 '))
>>> MyMd5.hexdigest ()
'6c0f33c5f4b96f1aa771bf432ba53002'
The hmac usage is as follows:
>>> Import hmac
>>> Myhmac = hmac. new (B 'mykey ')
>>> Myhmac. update (B 'mymessage ')
>>> Myhmac. hexdigest ()
'D8000030c4e62c6ef90d1bfe540212aaf'