+ 1

I have trouble hashing binaries [python]

I want to hash this binaries: 0011001010000101011111010000101111111111101000001001000001001010110100010101111001001011000100111100011110001001111011110111011010010100110011001110111001100010111011010010101101010011110100100110101111110001100101011001000110100010000110110001100101110001 Hashing them correctly returns the hash: f3f06d74b794b20645460aa0b17d4e7a77eaaea283ee55344adbfcece4a63432 if I use hashlib.sha256(x.encode('utf-8')) I get something different 44f6dafa3d7a1720b5ebbf2adc1663df4dab03776eed48d2cda775237a547e59 So bin() still returns string data. How can I convert it to binary data or make the hash function see the string as binaries?

28th Jan 2021, 4:09 PM
Maurice
2 ответов
+ 4
Your code is hashing the utf8 bytes for the characters '0' and '1' which looks like b"0011" == bytes([0x30, 0x30, 0x31, 0x31]). You have to convert the binary into actual bytes first. Convert the binary string to an int: int(x, 2) Convert the int to bytes using the to_bytes(length, byteorder) method: int(x, 2).to_bytes(len(x) // 8, "big") // length of the binary string was 256 so you have 256 / 8 = 32 bytes You can now hash this value.
28th Jan 2021, 6:34 PM
jtrh
jtrh - avatar
+ 1
thanks, this worked perfectly
31st Jan 2021, 11:21 AM
Maurice