Secure hashes and message digests using Python (hashlib)

PythonServer Side ProgrammingProgramming

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[, 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 ='md5',b'hello')
>>> hash.hexdigest()
>>> import hashlib

Using individual named constructors

>>> msg = hashlib.sha256()
>>> msg.update(b'Simple is better than complex')
>>> msg.digest()
>>> msg.block_size
>>> msg.hexdigest()
>>> msg = hashlib.md5()
>>> msg.update(b'Simple is better than complex')
>>> msg.hexdigest()

A hash object has the following methods −

Update the hash object with the bytes-like object. m.update(a); m.update(b) is equivalent to m.update(a+b).
Return the digest of the data passed to the update() method so far.
A digest is returned as a string object of double length, containing only hexadecimal digits.
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 −

A set containing the names of the hash algorithms guaranteed to be supported by this module on all platforms.
A set containing the names of the hash algorithms that are available in the running Python interpreter.
The size of the resulting hash in bytes.
The internal block size of the hash algorithm in bytes.
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.
Published on 19-Mar-2019 06:42:46