SHA256 is a popular and secure hashing algorithm used by a lot of different applications. Python provides the hashlib
module for hash-related functions and structures. The SHA256 is provided via the hashlib module which is provided by default and there is no need for installation.
Calculate SHA256 For Text Data
SHA256 can be calculated to text data easily by using the hashlib module sha256()
method. The text data is provided as a parameter to the sha356() method. This method generates a result where the hexdigest()
method of the result can be used to print the SHA265 in hexadecimal format. The string values should be encoded before being provided to the sha256() method.
import hashlib
sentence = "I like security."
result = hashlib.sha256(sentence.encode())
print(result.hexdigest())
da4df8e0711d0ef37f91565111ec51e1aaaaa48a0fa5871a4e8ca8385def385e
The output is the SHA256 value in hexadecimal presentation.
Calculate SHA256 For File
The sha265() method can be used to calculate file data SHA256 digest. First, the file data should be read and converted into byte format or it can be also read as byte format called binary read. Then the file content is provided as byte type to the sha265() method.
import hashlib
with open("/home/ismail/data.txt","rb") as f:
f_byte= f.read()
result = hashlib.sha256(f_byte)
print(result.hexdigest())
Print SHA256 As Byte Format
The SHA256 digest can be presented in different ways. Generally, the hexadecimal format provided with the hexdigest()
is more human-friendly than other formats. But The SHA256 digest can be also printed in byte format like below.
import hashlib
sentence = "I like security."
result = hashlib.sha256(sentence.encode())
print(result.digest())
b'\xdaM\xf8\xe0q\x1d\x0e\xf3\x7f\x91VQ\x11\xecQ\xe1\xaa\xaa\xa4\x8a\x0f\xa5\x87\x1aN\x8c\xa88]\xef8^'