I have some binary data that I want to hash. Specifically I am hashing a 128 bit private key. But for the discussion let’s just use a 16 bit private key. So here is my code and it works great except when my private key begins with leading zero’s. Specifically 4 leading zeros or more.
10 my_data = "0000000010001100"
20
30 hex_data = "{0:0>4X}".format(int(my_data,2))
40 bin_data = binascii.a2b_hex(hex_data)
50 chksum = hashlib.sha256(bin_data).hexdigest()
So the “my_data” variable is a string and contains the binary bits of my private key. I know that at the Linux command line I can type:
echo 0000000010001100 | shasum -a 256 -0
and it will return the hash:
bd767b4aa0cdb6b8e4e62761c3e9744353845698ca9aa44f7a1ffb525cdf5cb8
which is correct.
However, my program is returning the hash:
9defb0a9e163278be0e05aa01b312ec78cfa3726869503385e76e3a4b7950648
which is NOT correct.
After pulling some hair out I have determined the reason is because it does not put the leading ZERO’s in the “hex_data” that it is passing to the hashing algorithm.
If I print(hex_data) after line 30 I get:
8C
When I should get:
008C
I manually set my “hex_data” to “008C” and ran the code after line 30 and it gave me the correct hash. So I know the problem is that my leading ZERO’s are being left off when I convert the BINARY STRING to HEX.
I know I can just pad my finished output with leading ZERO’s and that would probably fix my problem. Or I can set up a loop and convert my binary to hex in a more manual deliberate way by looking at the actual binary digits 4 at a time and putting the HEXADECIMAL equivalent character into my hex_data string. The ZERO’s would be added no problem then.
But I’m thinking there has to be a more graceful way to do this? So I’m just asking in an effort to become more elegant in my programming skills. I don’t want anyone pulling their hair out to try and find me an elegant solution. I’m just thinking some Python programming guru out there might just have the solution off the top of their heads.
I basically just want an elegant way of taking a character string that is made up of 128 “1’s” & “0’s”, a binary private key, and passing it to the sha256 hashing algorithm to get my hash so I can extract my checksum from it.
Anyway, thanks in advance for all of you who have made it all the way down to here in your reading. Your time is appreciated. Kresp.