Earlier we have seen a briefing about hash codes in Python and about hash codes using MD5 algorithm. Now we will see how to generate hash using SHA1 hash code algorithm in Python. To start with, let us see a simple example with detailed steps.
Example
# import the library module
import hashlib
# initialize a string
str = "www.MyTecBits.com"
# encode the string
encoded_str = str.encode()
# create a sha1 hash object initialized with the encoded string
hash_obj = hashlib.sha1(encoded_str)
# convert the hash object to a hexadecimal value
hexa_value = hash_obj.hexdigest()
# print
print("\n", hexa_value, "\n")
Output:
e1a2b13775249a8018372b9c9efd764fd9d9e703
Compact version of the above example
>>> import hashlib
>>> hashlib.sha1(b"www.MyTecBits.com").hexdigest()
'e1a2b13775249a8018372b9c9efd764fd9d9e703'
More options in Python SHA1
Now let us see the other commonly used options available in Pythonss sha1 hashing.
Hash code in byte
As you have noticed, the above examples returned the sha1 hash code as a hexadecimal value using the hexdigest() method. If you need to get the resultant sha1 hash code in byte value, then use the digest() method. Here is an example.
>>> import hashlib
>>> hashlib.md5(b"www.MyTecBits.com").digest()
b'6\x01^\x81\xe9\xd1\xcf\xc6\xe30\xc8SV\xe5\xab\xf0'
Using update()
In the earlier examples we have created the hash object initialized with the encoded string or byte string. There is another way to append the byte string to the sha1 hash object using update() method. You can use the update() multiple times to append the byte string or any other byte date. This method comes in handy when you want to append data to the hash object based on multiple conditions. Here is an example.
import hashlib
# create a sha1 hash object
hash_object = hashlib.sha1()
# append the byte string
hash_object.update(b"www.")
hash_object.update(b"MyTecBits")
hash_object.update(b".com")
print("\n", hash_object.hexdigest(), "\n")
Output:
e1a2b13775249a8018372b9c9efd764fd9d9e703
Using new()
In the earlier examples we have created the hash abject using the sha1() constructor method. There is another way to initialize sha1 hash object. It is by using the new() method. In the new() method, you have to specify the name of the algorithm you want to use as its first parameter. In addition, you can also add the encoded string as an optional second parameter. Here is an example
import hashlib
# create a sha1 hash object
hash_object = hashlib.new("sha1", "www.MyTecBits.com".encode())
print("\n", hash_object.hexdigest(), "\n")
Output:
e1a2b13775249a8018372b9c9efd764fd9d9e703
Reference
- Online SHA1 hash code generator at MyTecBits Tools Section
- More about hashlib module at Python docs.