Search code examples
pythonhashcryptographypython-cryptography

How to hash SHA256 byte 00 with Python?


I'm trying to SHA256 a byte b"00" with python but don't understand what I have to encode.

import binascii
import hashlib

byte_ = binascii.unhexlify(b"00")
byte_ = b"00".decode("ascii")

hashed_byte = hashlib.sha256(byte_)
print((hashed_byte.hexdigest()))

What am I doing wrong? Why does this work with a string and not a byte?


Solution

  • Python's hashlib already accepts binary strings.

    import hashlib
    
    m = hashlib.sha256()
    
    m.update(b"\x00")  #or use m.update(bytes.fromhex('00'))
    hashed = m.hexdigest()
    
    print(hashed)
    

    outputs

    6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d

    There are NIST SHA-256 byte-oriented test vectors, however, there is no test vector for b"\x00". I've tested for other byte values like 0xd3 outputs

    28969cdfa74a12c82f3bad960b0b000aca2ac329deea5c2328ebc6f2ba9802c1 correctly.


    If you want to see the internals see https://sha256algorithm.com/