Python hashlib: How to use sha256 and hexdigest

You can get the hash of a string by importing hashlib in Python.

import hashlib

a = 'ABC'

h = hashlib.sha256(a.encode()).hexdigest()

print(h)
# b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78

The hashlib module has md5(), sha256(), sha512() and stuff like that.

The string must be encoded

The argument of sha256() must be encoded. Python raises the TypeError if a string is directly assigned.

import hashlib

a = 'ABC'

h = hashlib.sha256(a).hexdigest()

# TypeError: Unicode-objects must be encoded before hashing

The sha256() returns a HASH object, not a string

The sha256() returns a HASH object.

import hashlib

a = 'ABC'
h = hashlib.sha256(a.encode())

print(h)  # <sha256 HASH object @ 0x1090b03b0>
print(type(h))  # <class '_hashlib.HASH'>

So if you want to get the hash as a string, use the hexdigest().

import hashlib

a = 'ABC'

h = hashlib.sha256(a.encode()).hexdigest()

print(h)
# b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78

The prefix b substitutes the encode().

import hashlib

a = 'ABC'

h = hashlib.sha256(b'ABC').hexdigest()

print(h)
# b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78

A value with prefix b is a bytes object.

x = b'ABC'

print(x)  # b'ABC'
print(type(x))  # <class 'bytes'>

The sha256() takes a bytes object.

import hashlib

x = b'ABC'

y = hashlib.sha256(x).hexdigest()

print(y)
# b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78

hashlib.new()

import hashlib

s = 'ABC'

h1 = hashlib.new('sha256', s.encode()).hexdigest()
h2 = hashlib.sha256(s.encode()).hexdigest()

print(h1)  # b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78
print(h2)  # b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78

The new() takes the algorithm name such as sha256 and encoded value. It returns the HASH object that can be expressed as a string by using hexdigest(). The new() and sha256() are basically the same function. The function wrapping the new() is like this.

import hashlib


def h(algorithm, text):
    return hashlib.new(algorithm, text.encode()).hexdigest()


print(h('sha256', 'ABC'))  # b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78
print(h('sha512', 'ABC'))
# 397118fdac8d83ad98813c50759c85b8c47565d8268bf10da483153b747a74743a58a90e85aa9f705ce6984ffc128db567489817e4092d050d8a1cc596ddc119

Python String

Python Tutorial