Python theorytheory 0/50 · 0%
Web3 integration · medium

32. Hashing with hashlib

Computing cryptographic hashes for integrity and addresses.

`hashlib` provides hash algorithms like SHA-256, common for content addressing, Merkle trees, and integrity checks.

python
import hashlib

digest = hashlib.sha256(b"hello").hexdigest()
# note: hash functions take bytes, not str -- encode first
hashlib.sha256("hello".encode()).hexdigest()

For a simple Merkle-style combine step: `hashlib.sha256(left + right).digest()` where `left`/`right` are raw bytes digests. `hashlib.new("ripemd160", data)` (when available) and `hashlib.sha3_256` cover algorithms used by various chains, though Ethereum addresses specifically use Keccak-256, which differs subtly from the standardized SHA3-256 and isn't in the stdlib.

Check your understanding

  1. 1. What input type does `hashlib.sha256()` require?

  2. 2. What does `.hexdigest()` return compared to `.digest()`?

  3. 3. Is Ethereum's Keccak-256 the same as stdlib's sha3_256?