how to create a sha1 hash in python

Swetha picture Swetha · May 27, 2016 · Viewed 18.9k times · Source

My objective is to perform "Hashsigning" using smart card in python. there are hashlib's used but there is no specific SHA1 or SHA256 functions in python. My Work:

hash_object = hashlib.sha1(b'HelWorld')
pbHash = hash_object.hexdigest()

but the length of the hash object I get is 28 rather i should get 14 or 20 so that i can switch on condition as

 switch ( dwHashLen )
{
case 0x14: // SHA1 hash
             call scard transmit
case 0x20: // SHA256 hash
}

Any help is appreciated. Thank you in advance

Answer

Abdul Fatir picture Abdul Fatir · May 27, 2016

You're actually getting 40, which in hex is 0x28. Decode the hash in hexadecimal to ASCII as follows

>>> import hashlib
>>> hash_object = hashlib.sha1(b'HelWorld')
>>> pbHash = hash_object.hexdigest()
>>> length = len(pbHash.decode("hex"))
>>> print length
20

Or simply use digest instead of hexdigest as Dan D suggested.