create a sha256 hash from a string in python

To create a SHA256 hash from a string in Python, you can use the hashlib module which provides a way to use popular hashing algorithms. Here is an example code snippet:

main.py
import hashlib

string_to_hash = "hello world"
encoded_string = string_to_hash.encode('utf-8')

hash_object = hashlib.sha256(encoded_string)
hex_dig = hash_object.hexdigest()

print("SHA256 hash of '{}' is {}".format(string_to_hash, hex_dig))
243 chars
10 lines

In the above code, the encode() method is used to convert the string to a byte string in utf-8 encoding which is required by the sha256() function. The sha256() method creates a SHA-256 hash object which is used to compute the hash of the input byte string. The hexdigest() method returns the hash as a string of hexadecimal digits. Finally, the hash value is displayed using the print() function.

gistlibby LogSnag