pythonmessage-digest

How to create a SHA1 hash in python


My objective is to perform “Hash signing” using smart card in Python. There are hashlibs used, but there are 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:[1]

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

Any help is appreciated. Thank you in advance.


[1] This is a portion of the C code I'm currently porting to Python.


Solution

  • 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.