create a sha1 hash from a string in python

To create a SHA1 hash from a string in Python, we can use the hashlib module, which provides various hashing algorithms. Here's an example code snippet that shows how to generate a SHA1 hash from a string:

main.py
import hashlib

# create a string to hash
my_string = "Hello, world!"

# encode the string to bytes
my_bytes = my_string.encode('utf-8')

# create a SHA1 hash object
my_hash = hashlib.sha1()

# update the hash object with the bytes of the string
my_hash.update(my_bytes)

# get the hex digest of the hash
hash_digest = my_hash.hexdigest()

print(hash_digest) # prints "943a702d06f34599aee1f8da8ef9f7296031d699"
411 chars
19 lines

In this example, we first create a string "Hello, world!", then encode it to bytes using the utf-8 encoding. We then create a SHA1 hash object using hashlib.sha1() and update the object with the bytes of the string using my_hash.update(my_bytes). Finally, we get the hex digest of the hash using my_hash.hexdigest(), which gives us the SHA1 hash of the string "Hello, world!".

gistlibby LogSnag