🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Cryptographic Primitives

Blockchain Internals🟢 Free Lesson

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

Input: arbitrary lengthHash Function h()Output: fixed lengthPreimageResistanceSecond PreimageResistanceCollisionResistanceAvalancheEffect

SHA-256 (Bitcoin)

SHA-256 produces a 256-bit digest and is used in Bitcoin's proof-of-work and Merkle tree construction.

python
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.

python
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.

python
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

FunctionOutputBlock SizeRoundsSecuritySpeed
SHA-256256 bits512 bits64128 bitsBaseline
SHA-3-256256 bits1088 bits24128 bits0.8x
Keccak-256256 bits1088 bits24128 bits0.8x
BLAKE2b-256256 bits128 bits10128 bits3-5x
BLAKE3256 bits64 bits7128 bits10x+

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 LevelHash BitsBirthday BoundBrute Force
80-bit160
112-bit224
128-bit256
192-bit384

Preimage Resistance

Given hash , finding any message such that is computationally infeasible.

python
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

PropertyPreimage ResistanceSecond Preimage Resistance
GivenHash Message , hash
FindAny where where
Difficulty
Use casePassword storageDigital signatures

Hash Chains

Hash chains provide a one-way sequence useful for key revocation, cryptocurrency wallets, and commitment schemes.

Construction

Hash Chain Diagram

h₀ (seed)h₁ = H(h₀)h₂ = H(h₁)h₃ = H(h₂)h₄ = H(h₃)...Easy to compute forward: h₀ → h₁ → h₂ → ... → hₙHard to compute backward: hₙ → hₙ₋₁ → ... → h₀

Lamport One-Time Signatures

python
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)
python
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 CaseApplication
HD WalletsBIP-32 key derivation
Payment ChannelsLightning Network HTLCs
State ProofsEthereum light client
API AuthenticationBlockchain 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
python
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

Phase 1: CommitValue vRandom r→Commitment CPhase 2: OpenCommitment CValue vRandom r→✓

Properties

PropertyDescription
HidingCommitment reveals nothing about
BindingCannot open commitment to different
Perfect HidingComputationally hiding (requires random )
Computational BindingComputationally binding (requires discrete log assumption)

Applications in Blockchain

ApplicationUse Case
ZcashShielded transactions
Confidential TransactionsAmount hiding in Monero
Commit-RevealFair randomness, voting
State ChannelsOff-chain state updates

Trade-offs

Hash Function Selection

AlgorithmSecuritySpeedUse Case
SHA-256HighModerateBitcoin, general purpose
Keccak-256HighModerateEthereum, addresses
BLAKE2HighFastHigh-throughput chains
BLAKE3HighVery fastModern applications

Trade-offs Table

Trade-offOption AOption B
Speed vs SecurityBLAKE3 (fast)SHA-3 (conservative)
Standardization vs PerformanceSHA-256 (standard)BLAKE2 (fast)
Compatibility vs InnovationSHA-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

  1. Take public key: 04a1b2c3...
  2. Keccak-256 hash: 8c5be1e5...
  3. Take last 20 bytes: 5e6f7a8b...
  4. 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:

  1. An attacker would need to extend through two hash states
  2. The inner hash output isn't directly usable
  3. 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:

  1. Perfect hiding: Even with unlimited computation, the commitment reveals nothing about the value
  2. Homomorphic addition: enables confidential transactions without revealing amounts
  3. Non-interactive: No challenge-response needed
  4. 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

  1. Implement a Merkle tree using SHA-256 and verify proofs
  2. Build a Lamport one-time signature scheme
  3. Create a simple HMAC-based authentication system
  4. Compare the performance of SHA-256 vs BLAKE2b for large data
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-16

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Blockchain Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement