Federal Information Processing Standard (FIPS) defines secure hash algorithms SHA1, SHA224, SHA256, SHA384, and SHA512. RSA The acronym made of the initials of the surnames of Rivest,Shamir, and Adleman, defines MD5 algorithm. Older algorithms were called message digests. The modern term is secure hash.
The hashlib module is used to implement following algorithms.
- md5
- sha1
- sha224
- sha256
- sha384
- sha512
hashlib.new(name[, data])
Is a generic constructor that takes the string name of the desired algorithm as its first parameter. It also exists to allow access to the above listed hashes as well as any other algorithms that your OpenSSL library may offer. The named constructors are much faster than new() and should be preferred.
>>> hash = hashlib.new('md5',b'hello') >>> hash.hexdigest() '5d41402abc4b2a76b9719d911017c592' >>> import hashlib
Using individual named constructors
>>> msg = hashlib.sha256() >>> msg.update(b'Simple is better than complex') >>> msg.digest() b'\xabz\xd8C(n\xb3\x8b\xf6\x0c\x0e\xf2\x81z\xd7\xf93\x835\xb2\xa1\x9cM\xb1S\x1f\xf7\xf9\x1av-F' >>> msg.block_size 64 >>> msg.hexdigest() 'ab7ad843286eb38bf60c0ef2817ad7f9338335b2a19c4db1531ff7f91a762d46' >>> msg = hashlib.md5() >>> msg.update(b'Simple is better than complex') >>> msg.hexdigest() 'fd34bb8fafd17f1a21d7bb6e38c8dc68'
A hash object has the following methods −
update() | Update the hash object with the bytes-like object. m.update(a); m.update(b) is equivalent to m.update(a+b). |
digest() | Return the digest of the data passed to the update() method so far. |
hexdigest() | A digest is returned as a string object of double length, containing only hexadecimal digits. |
copy() | Return a copy of the hash object. This can be used to compute the digests of data sharing a common initial substring. |
Hashlib provides the following attributes −
algorithms_guaranteed | A set containing the names of the hash algorithms guaranteed to be supported by this module on all platforms. |
algorithms_available | A set containing the names of the hash algorithms that are available in the running Python interpreter. |
digest_size | The size of the resulting hash in bytes. |
block_size | The internal block size of the hash algorithm in bytes. |
name | The canonical name of this hash, always lowercase and always suitable as a parameter to new() to create another hash of this type. |
The shake_128() and shake_256() algorithms provide variable length digests with length_in_bits//2 up to 128 or 256 bits of security.
BLAKE2 is a cryptographic hash function defined in RFC 7693 that comes in two flavors −
- BLAKE2b, optimized for 64-bit platforms and produces digests of any size between 1 and 64 bytes,
- BLAKE2s, optimized for 8- to 32-bit platforms and produces digests of any size between 1 and 32 bytes.