Cryptographic Primitives
Hash functions (SHA-256, Keccak-256, BLAKE2), collision resistance, preimage resistance, hash chains, HMAC, and commitment schemes.
Overview
Cryptographic primitives are the building blocks of blockchain security. They provide data integrity, authentication, and confidentiality guarantees that make decentralized systems possible.
Hash Functions
A cryptographic hash function maps arbitrary-length input to fixed-length output with specific security properties.
Formal Definition
Where is the output length (e.g., 256 bits).
Security Properties
SHA-256 (Bitcoin)
SHA-256 produces a 256-bit digest and is used in Bitcoin's proof-of-work and Merkle tree construction.
import hashlib
import struct
def sha256_double(data: bytes) -> bytes:
"""Bitcoin's double SHA-256 hash."""
first = hashlib.sha256(data).digest()
second = hashlib.sha256(first).digest()
return second
def merkle_root(transactions: list) -> bytes:
"""Compute Merkle root of transaction list."""
if not transactions:
return b'\x00' * 32
current_level = [sha256_double(tx) for tx in transactions]
while len(current_level) > 1:
next_level = []
for i in range(0, len(current_level), 2):
left = current_level[i]
right = current_level[i + 1] if i + 1 < len(current_level) else left
combined = left + right
next_level.append(sha256_double(combined))
current_level = next_level
return current_level[0]
# Example usage
txs = [b"tx1", b"tx2", b"tx3", b"tx4"]
root = merkle_root(txs)
print(f"Merkle Root: {root.hex()}")
Keccak-256 (Ethereum)
Ethereum uses Keccak-256 (pre-NIST standardization) for address generation, storage keys, and event topics.
from Crypto.Hash import keccak
def keccak256(data: bytes) -> bytes:
"""Keccak-256 hash used in Ethereum."""
k = keccak.new(digest_bits=256)
k.update(data)
return k.digest()
def ethereum_address(pubkey: bytes) -> str:
"""Derive Ethereum address from public key."""
# Keccak-256 of public key (without 04 prefix)
hash_result = keccak256(pubkey[1:])
# Take last 20 bytes
address = hash_result[-20:]
return "0x" + address.hex()
def storage_slot(key: int, value: int) -> bytes:
"""Compute storage slot hash for mapping."""
# keccak256(key . slot_number)
data = key.to_bytes(32, 'big') + (0).to_bytes(32, 'big')
return keccak256(data)
BLAKE2 (Zcash, Polkadot)
BLAKE2 is optimized for speed while maintaining cryptographic security.
import hashlib
def blake2b_hash(data: bytes, digest_size: int = 32) -> bytes:
"""BLAKE2b hash used in Zcash and Polkadot."""
return hashlib.blake2b(data, digest_size=digest_size).digest()
def blake2s_hash(data: bytes, digest_size: int = 32) -> bytes:
"""BLAKE2s hash - 32-bit optimized variant."""
return hashlib.blake2s(data, digest_size=digest_size).digest()
# Performance comparison
import time
data = b"x" * 1000000 # 1MB
start = time.time()
for _ in range(100):
hashlib.sha256(data).digest()
sha256_time = time.time() - start
start = time.time()
for _ in range(100):
hashlib.blake2b(data, digest_size=32).digest()
blake2_time = time.time() - start
print(f"SHA-256: {sha256_time:.3f}s")
print(f"BLAKE2b: {blake2_time:.3f}s")
print(f"Speedup: {sha256_time/blake2_time:.1f}x")
Hash Function Comparison
| Function | Output | Block Size | Rounds | Security | Speed |
|---|---|---|---|---|---|
| SHA-256 | 256 bits | 512 bits | 64 | 128 bits | Baseline |
| SHA-3-256 | 256 bits | 1088 bits | 24 | 128 bits | 0.8x |
| Keccak-256 | 256 bits | 1088 bits | 24 | 128 bits | 0.8x |
| BLAKE2b-256 | 256 bits | 128 bits | 10 | 128 bits | 3-5x |
| BLAKE3 | 256 bits | 64 bits | 7 | 128 bits | 10x+ |
Collision Resistance
A hash function is collision-resistant if finding two distinct inputs with the same output is computationally infeasible.
Birthday Attack Bound
For a hash with -bit output:
- After hashes, collision probability ≈ 50%
- This is called the birthday bound
Security Levels
| Security Level | Hash Bits | Birthday Bound | Brute Force |
|---|---|---|---|
| 80-bit | 160 | ||
| 112-bit | 224 | ||
| 128-bit | 256 | ||
| 192-bit | 384 |
Preimage Resistance
Given hash , finding any message such that is computationally infeasible.
import hashlib
import secrets
class HashChain:
"""One-way hash chain for key derivation."""
def __init__(self, seed: bytes, length: int = 1000):
self.chain = self._generate_chain(seed, length)
def _generate_chain(self, seed: bytes, length: int) -> list:
chain = [seed]
current = seed
for _ in range(length):
current = hashlib.sha256(current).digest()
chain.append(current)
return chain
def get_element(self, index: int) -> bytes:
"""Get element at index (forward direction - easy)."""
return self.chain[index]
def verify_chain(self, start: int, end: int) -> bool:
"""Verify chain from start to end."""
current = self.chain[start]
for i in range(start, end):
expected = hashlib.sha256(current).digest()
if expected != self.chain[i + 1]:
return False
current = self.chain[i + 1]
return True
# Example: Lightning Network payment channels
seed = secrets.token_bytes(32)
chain = HashChain(seed, length=1000)
# Reveal from end (for payment)
print(f"Last hash: {chain.get_element(999).hex()}")
Preimage vs Second Preimage
| Property | Preimage Resistance | Second Preimage Resistance |
|---|---|---|
| Given | Hash | Message , hash |
| Find | Any where | where |
| Difficulty | ||
| Use case | Password storage | Digital signatures |
Hash Chains
Hash chains provide a one-way sequence useful for key revocation, cryptocurrency wallets, and commitment schemes.
Construction
Hash Chain Diagram
Lamport One-Time Signatures
import hashlib
import secrets
class LamportOTS:
"""Lamport one-time signature scheme using hash chains."""
def __init__(self, security_bits: int = 256):
self.n = security_bits
self.private_key = None
self.public_key = None
def keygen(self):
"""Generate key pair."""
self.private_key = {
'0': [secrets.token_bytes(32) for _ in range(self.n)],
'1': [secrets.token_bytes(32) for _ in range(self.n)],
}
self.public_key = {
'0': [hashlib.sha256(sk).digest() for sk in self.private_key['0']],
'1': [hashlib.sha256(sk).digest() for sk in self.private_key['1']],
}
return self.public_key
def sign(self, message: bytes) -> list:
"""Sign a message (one-time use!)."""
msg_hash = hashlib.sha256(message).digest()
bits = ''.join(format(byte, '08b') for byte in msg_hash)
signature = []
for i, bit in enumerate(bits[:self.n]):
signature.append(self.private_key[bit][i])
return signature
def verify(self, message: bytes, signature: list, public_key: dict) -> bool:
"""Verify signature."""
msg_hash = hashlib.sha256(message).digest()
bits = ''.join(format(byte, '08b') for byte in msg_hash)
for i, bit in enumerate(bits[:self.n]):
expected = hashlib.sha256(signature[i]).digest()
if expected != public_key[bit][i]:
return False
return True
# Usage
ots = LamportOTS(security_bits=256)
pub = ots.keygen()
msg = b"Transfer 1 BTC"
sig = ots.sign(msg)
valid = ots.verify(msg, sig, pub)
print(f"Signature valid: {valid}")
HMAC (Hash-based Message Authentication Code)
HMAC provides both integrity and authentication of messages.
HMAC Construction
Where:
- is the key (padded or hashed to block size)
import hashlib
import hmac
class HMAC:
"""HMAC implementation for blockchain authentication."""
def __init__(self, key: bytes, hash_func=hashlib.sha256):
self.key = key
self.hash_func = hash_func
self.block_size = hash_func().block_size
def _process_key(self) -> bytes:
"""Process key to match block size."""
key = self.key
if len(key) > self.block_size:
key = self.hash_func(key).digest()
if len(key) < self.block_size:
key = key + b'\x00' * (self.block_size - len(key))
return key
def compute(self, message: bytes) -> bytes:
"""Compute HMAC."""
key = self._process_key()
ipad = bytes([0x36] * self.block_size)
opad = bytes([0x5c] * self.block_size)
inner_key = bytes([a ^ b for a, b in zip(key, ipad)])
outer_key = bytes([a ^ b for a, b in zip(key, opad)])
inner_hash = self.hash_func(inner_key + message).digest()
return self.hash_func(outer_key + inner_hash).digest()
def verify(self, message: bytes, mac: bytes) -> bool:
"""Verify HMAC with constant-time comparison."""
computed = self.compute(message)
return hmac.compare_digest(computed, mac)
# Usage
secret_key = secrets.token_bytes(32)
hmac_obj = HMAC(secret_key)
message = b"Block #12345 data"
mac = hmac_obj.compute(message)
print(f"HMAC: {mac.hex()}")
print(f"Valid: {hmac_obj.verify(message, mac)}")
HMAC in Blockchain
| Use Case | Application |
|---|---|
| HD Wallets | BIP-32 key derivation |
| Payment Channels | Lightning Network HTLCs |
| State Proofs | Ethereum light client |
| API Authentication | Blockchain node APIs |
Commitment Schemes
Commitment schemes allow a party to commit to a value while keeping it hidden, with the ability to reveal it later.
Pedersen Commitment
Where:
- is the committed value
- is the random blinding factor
- are generator points on the curve
from hashlib import sha256
from secrets import randbelow
class PedersenCommitment:
"""Simplified Pedersen commitment (conceptual)."""
def __init__(self, p: int, g: int, h: int):
self.p = p # Prime modulus
self.g = g # Generator
self.h = h # Second generator (from hash)
def commit(self, value: int) -> tuple:
"""Create commitment to value."""
# Blinding factor
r = randbelow(self.p - 1)
# C = g^v * h^r mod p
c = (pow(self.g, value, self.p) * pow(self.h, r, self.p)) % self.p
return c, r
def verify(self, commitment: int, value: int, randomness: int) -> bool:
"""Verify commitment opens to value."""
expected = (pow(self.g, value, self.p) * pow(self.h, randomness, self.p)) % self.p
return commitment == expected
# Example parameters (simplified)
p = 2332810182561094714382979694167168940045892325918207417257001773851016921839
g = 3
h = 6 # In practice, h = Hash(g)
scheme = PedersenCommitment(p, g, h)
value = 42
commitment, randomness = scheme.commit(value)
print(f"Commitment: {commitment}")
print(f"Verified: {scheme.verify(commitment, value, randomness)}")
Commitment Diagram
Properties
| Property | Description |
|---|---|
| Hiding | Commitment reveals nothing about |
| Binding | Cannot open commitment to different |
| Perfect Hiding | Computationally hiding (requires random ) |
| Computational Binding | Computationally binding (requires discrete log assumption) |
Applications in Blockchain
| Application | Use Case |
|---|---|
| Zcash | Shielded transactions |
| Confidential Transactions | Amount hiding in Monero |
| Commit-Reveal | Fair randomness, voting |
| State Channels | Off-chain state updates |
Trade-offs
Hash Function Selection
| Algorithm | Security | Speed | Use Case |
|---|---|---|---|
| SHA-256 | High | Moderate | Bitcoin, general purpose |
| Keccak-256 | High | Moderate | Ethereum, addresses |
| BLAKE2 | High | Fast | High-throughput chains |
| BLAKE3 | High | Very fast | Modern applications |
Trade-offs Table
| Trade-off | Option A | Option B |
|---|---|---|
| Speed vs Security | BLAKE3 (fast) | SHA-3 (conservative) |
| Standardization vs Performance | SHA-256 (standard) | BLAKE2 (fast) |
| Compatibility vs Innovation | SHA-256 (widely supported) | Newer functions |
Real-World Examples
Bitcoin Mining
Bitcoin's proof-of-work requires finding a nonce such that:
Current difficulty requires finding a hash with ~78 leading zeros (in hex).
Ethereum Address Generation
- Take public key:
04a1b2c3... - Keccak-256 hash:
8c5be1e5... - Take last 20 bytes:
5e6f7a8b... - Add prefix:
0x5e6f7a8b...
Zcash Equihash
Zcash uses Equihash, a memory-hard proof-of-work based on the Generalized Birthday Problem:
Where and memory requirement is .
Interview Questions
Q1: Why does Bitcoin use double SHA-256 instead of single SHA-256?
Answer: Double SHA-256 provides protection against length-extension attacks. Single SHA-256 (like MD5 and SHA-1) is vulnerable to attacks where an attacker can compute without knowing . The second hash prevents this because:
- An attacker would need to extend through two hash states
- The inner hash output isn't directly usable
- This was a defensive measure against potential SHA-256 vulnerabilities
Q2: Explain the birthday paradox and its relevance to hash security.
Answer: The birthday paradox states that with hash outputs, collision probability is approximately where is the hash output size. For SHA-256:
- To achieve 50% collision probability: hashes needed
- This is why 256-bit hashes provide 128-bit collision resistance
- Miners performing hashes per year don't come close to this bound
Q3: What is the advantage of Pedersen commitments over hash-based commitments in blockchain?
Answer: Pedersen commitments offer:
- Perfect hiding: Even with unlimited computation, the commitment reveals nothing about the value
- Homomorphic addition: enables confidential transactions without revealing amounts
- Non-interactive: No challenge-response needed
- Zero-knowledge proofs: Can prove properties about committed values without revealing them
Quiz Questions
Q1: Which hash property ensures that finding two inputs with the same output is computationally infeasible?
A) Preimage resistance B) Second preimage resistance C) Collision resistance D) Avalanche effect
Answer: C) Collision resistance
Q2: What is the primary security advantage of BLAKE2 over SHA-256?
A) Stronger security guarantees B) Faster hashing with equivalent security C) Smaller output size D) Better collision resistance
Answer: B) Faster hashing with equivalent security
Q3: In a Pedersen commitment, what provides the hiding property?
A) The generator point B) The value C) The blinding factor D) The modulus
Answer: C) The blinding factor
Practice
- Implement a Merkle tree using SHA-256 and verify proofs
- Build a Lamport one-time signature scheme
- Create a simple HMAC-based authentication system
- Compare the performance of SHA-256 vs BLAKE2b for large data