Convert a string to SHA256 in Python

SHA256 generates an almost-unique 256-bit (32-byte) signature for text. SHA256 is the number of bits it takes in memory. The hash value is 64 characters long and it has alphabets and numbers ranging from [0-9] and [A-F]. Since every character occupies 4 bits => 64*4 = 256 bits of information of hash value.

Some blockchains are based on SHA256 encryption so lets create a simply Python program that takes some text as input and generates a SHA256 hash.

Below is a sample program in Python to convert a string into SHA256. SHA256 generates an almost-unique 256-bit (32-byte) signature for a text. Read the comments in the code below to understand how the code works and convert the “hello” string to a cryptographic hash.

#sha (secure hash algorithm) are a set of crypto graphic hash functions

import hashlib
str = 'Hello'

#encode() converts the string into bytes to be accepted by the hash function.

result = hashlib.sha256(str.encode())

#hexidigest() returns the encoded data in hexadecimal format

print('the hexadecimal equivalent of sha256 is : ', result.hexdigest())

#number of hex digits in the string * 4 binary digits = 256

print(result.block_size)

#bytes
print(result.digest_size)

Next Review – Test your connection to the Ethereum blockchain using Web3.py and Python

Leave a Reply