2 min read

Python Hashlib Module

The hashlib module implements a common interface to many different secure hash and message digest algorithms. Included are the FIPS secure hash algorithms SHA1, SHA224, SHA256, SHA384, and SHA512 (defined in FIPS 180-2) as well as RSA’s MD5 algorithm (defined in Internet RFC 1321).

Importing the Module

import hashlib

Available Algorithms

You can check which algorithms are guaranteed to be supported by the module on all platforms, and which are available in the running Python interpreter.

import hashlib

print(hashlib.algorithms_guaranteed)
print(hashlib.algorithms_available)

Creating Hash Objects

To create a hash of a byte string, you can use the constructor functions like sha256(), md5(), etc.

import hashlib

# Create a SHA-256 hash object
m = hashlib.sha256()

Updating the Hash

You can update the hash object with bytes-like objects using the update() method. Repeated calls are equivalent to a single call with the concatenation of all the arguments.

m.update(b"Hello")
m.update(b" World")

Getting the Digest

digest()

Returns the digest of the data passed to the update() method so far. This is a bytes object of size digest_size.

print(m.digest())

hexdigest()

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

print(m.hexdigest())

Concise Usage

You can also pass the data directly to the constructor.

import hashlib

print(hashlib.sha256(b"Hello World").hexdigest())

Using new()

A generic constructor new(name, data=b'') is also available.

h = hashlib.new('sha256')
h.update(b"Nobody inspects")
h.update(b" the spammish repetition")
print(h.hexdigest())

programming/python/python