How to create a SHA1 hash in python
Asked Answered
H

2

30

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.

Hypoxia answered 27/5, 2016 at 11:53 Comment(5)
What do you mean by length of hash object? And where do you get 28? SHA1 is 40 chars long.Giefer
and what do you mean switch and case that is surely not python...Caty
the sha1 digest itself is 20 bytes - 40 characters hex encoded. maybe that's what is meant here. sha256 is 32 bytes (64 characters in hex). not sure what should be 14 - even md5 is 16 bytes.Caty
Note that those are hex values that 0x14 is 20 and 0x20 is 32 so you are expecting binary hashes not hex encoded ones. Use .digest() not .hexdigest() to get the binary hash not the hex encoded one.Phenylalanine
@domoarrigato switch case is in my c code. i am porting to python.Hypoxia
G
47

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.

Giefer answered 27/5, 2016 at 12:26 Comment(0)
H
1

The answer Abdul Fatir gave did not work for me:

AttributeError: 'str' object has no attribute 'decode'. Did you mean: 'encode'?

This is how I used Python 3.12 hashlib to evaluate the SHA1 example hashes in Wikipedia:

import hashlib


# SHA1 hex digest for some input string
def SHA1(msg: str) -> str:
    return hashlib.sha1(msg.encode()).hexdigest()


assert (
    SHA1("The quick brown fox jumps over the lazy dog")
    == "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12"
)
assert (
    SHA1("The quick brown fox jumps over the lazy cog")
    == "de9f2c7fd25e1b3afad3e85a0bd17d9b100db4b3"
)
assert SHA1("") == "da39a3ee5e6b4b0d3255bfef95601890afd80709"

We can see that each digest contains 40 hex digits, which corresponds to the expected 20 bytes of binary data that I could have obtained using hashlib.sha1(msg.encode()).digest().

Hypophosphite answered 22/4 at 13:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.