B++ Logo

Cryptography in Bitcoin

Bitcoin relies on several cryptographic primitives to secure transactions, prove ownership, and maintain the integrity of the blockchain. Understanding these cryptographic foundations is essential for grasping how Bitcoin achieves trustless security.

The Power of Cryptography

Cryptography enables remarkable capabilities that seem almost magical:

  • Prove knowledge without revealing it: You can prove you know a secret (like a private key) without ever exposing the secret itself. This is how you sign Bitcoin transactions.
  • Create unforgeable signatures: Only the holder of a private key can create a valid signature, but anyone can verify it with the corresponding public key.
  • Commit to data irrevocably: Hash functions create unique fingerprints that bind you to specific data without revealing it until you choose to.
  • Verify integrity instantly: Detect any tampering with data, no matter how large, by comparing small hash values.

These concepts aren't unique to Bitcoin. You encounter cryptography daily:

ApplicationCryptographic Use
HTTPS/TLSEncrypts web traffic, verifies website identity
PGP/GPGEmail encryption and digital signatures
Signal/WhatsAppEnd-to-end encrypted messaging
SSHSecure remote server access
Password StorageHashing passwords so they're never stored in plain text

Bitcoin combines these proven cryptographic techniques in a novel way to create a trustless monetary system.


Overview

Bitcoin uses cryptography for three main purposes:

  1. Ownership & Authentication: Proving you own bitcoin without revealing your private key
  2. Integrity: Ensuring data hasn't been tampered with
  3. Proof-of-Work: Securing the blockchain through computational work

Hash Functions

A cryptographic hash function takes any input data and produces a fixed-size output (the "hash" or "digest"). Hash functions are one-way: easy to compute, but practically impossible to reverse.

Properties of Cryptographic Hash Functions:

PropertyDescription
DeterministicSame input always produces same output
FastQuick to compute for any input
One-wayCannot derive input from output
Collision-resistantInfeasible to find two inputs with same output
Avalanche effectSmall input change = completely different output

SHA-256

Bitcoin's primary hash function is SHA-256 (Secure Hash Algorithm, 256-bit).

Characteristics:

  • Output: 256 bits (32 bytes, 64 hex characters)
  • Designed by NSA, published in 2001
  • No known practical attacks

Example:

Input:  "Hello"
SHA-256: 185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969

Input:  "Hello!"
SHA-256: 334d016f755cd6dc58c53a86e183882f8ec14f52fb05345887c8a5edd42c87b7

Notice how adding a single character completely changes the output (avalanche effect).

Double SHA-256 (SHA256D)

Bitcoin often uses double SHA-256: SHA256(SHA256(data))

Used for:

Why double hashing?

  • Defense against length-extension attacks
  • Additional security margin
  • Historical design choice by Satoshi

Code: SHA-256 and Double SHA-256

RIPEMD-160 and Hash160

RIPEMD-160 produces a 160-bit (20-byte) hash, used in combination with SHA-256.

Hash160 = RIPEMD160(SHA256(data))

Used for:

  • Bitcoin addresses (P2PKH, P2SH)
  • Shorter than SHA-256, reducing address length
  • Still cryptographically secure

Code: Hash160


Elliptic Curve Cryptography

Elliptic Curve Cryptography

Elliptic Curve Cryptography (ECC) is a public-key cryptography system based on the algebraic structure of elliptic curves over finite fields.

Why Bitcoin uses ECC:

  • Smaller key sizes than RSA (256-bit vs 3072-bit for equivalent security)
  • Faster computation
  • Lower bandwidth and storage requirements

The secp256k1 Curve

Bitcoin uses the secp256k1 elliptic curve (see ECDSA), defined by the equation:

y² = x³ + 7 (mod p)

Parameters:

  • p (prime): 2²⁵⁶ - 2³² - 977
  • Order (n): Number of points on the curve
  • Generator point (G): Fixed starting point for key generation

Why secp256k1?

  • Chosen by Satoshi (not the most common curve at the time)
  • Efficiently computable
  • No known weaknesses
  • Parameters are "nothing up my sleeve" numbers (verifiably random)

Key Generation

Private Key:

  • Random 256-bit number (1 to n-1)
  • Must be kept secret
  • Generated from cryptographically secure random source

Public Key:

  • Derived from private key: Public Key = Private Key × G
  • Point multiplication on the elliptic curve
  • Cannot reverse to find private key (discrete logarithm problem)
  • Can be shared publicly

Key Relationship:

Random Number → Private Key → Public Key → Bitcoin Address
     (256 bits)    (256 bits)   (512 bits)   (160 bits)

Code: Key Generation

The Discrete Logarithm Problem

Why can't you derive the private key from the public key?

Given Q = k × G where:

  • Q is the public key (known)
  • G is the generator point (known)
  • k is the private key (unknown)

Finding k requires solving the Elliptic Curve Discrete Logarithm Problem (ECDLP), which is computationally infeasible for sufficiently large numbers.

Security Level:

  • 256-bit private key = ~128 bits of security
  • Would take billions of years with current technology
  • Quantum computers could theoretically break this (see future considerations)

Digital Signatures

A digital signature proves:

  1. Authenticity: Message came from the claimed sender
  2. Integrity: Message hasn't been altered
  3. Non-repudiation: Sender cannot deny sending

ECDSA (Elliptic Curve Digital Signature Algorithm)

Bitcoin originally used ECDSA for all signatures.

Signing Process:

  1. Hash the message: z = SHA256(message)
  2. Generate random number k (nonce)
  3. Calculate point R = k × G
  4. Calculate signature: s = k⁻¹(z + r × privateKey) mod n
  5. Signature is the pair (r, s)

Verification Process:

  1. Hash the message: z = SHA256(message)
  2. Calculate: u1 = z × s⁻¹ mod n
  3. Calculate: u2 = r × s⁻¹ mod n
  4. Calculate point: P = u1 × G + u2 × PublicKey
  5. Signature valid if P.x = r

ECDSA Characteristics:

  • Signature size: 70-72 bytes (DER encoded)
  • Requires secure random nonce k
  • Reusing k exposes private key!

Code: ECDSA Signing and Verification

Schnorr Signatures

Schnorr Signature Equations

Schnorr signatures were introduced with the Taproot upgrade (2021).

Advantages over ECDSA:

  • Simpler: Mathematically cleaner
  • Smaller: Fixed 64-byte signatures
  • Linearity: Enables key and signature aggregation
  • Provably secure: Better security proofs
  • Batch verification: Faster validation of multiple signatures

Signature Aggregation: Multiple signatures can be combined into one, enabling:

  • MuSig: Multi-signature schemes that look like single signatures
  • Privacy: Multi-party transactions appear as single-party
  • Efficiency: Reduced transaction size and fees

Code: BIP-340 Schnorr Tagged Hash

Signing a Bitcoin Transaction

When you spend bitcoin:

  1. Construct transaction with inputs and outputs
  2. Create signature hash (sighash) of transaction data
  3. Sign the sighash with your private key
  4. Include signature in transaction's witness/scriptSig
  5. Broadcast transaction to network
  6. Nodes verify signature matches public key and transaction

Merkle Trees

A Merkle tree (or hash tree) is a data structure that efficiently summarizes and verifies large datasets.

Structure:

                    Merkle Root
                   /            \
              Hash AB          Hash CD
             /      \         /      \
         Hash A   Hash B   Hash C   Hash D
            |        |        |        |
           Tx A    Tx B     Tx C     Tx D

How Bitcoin Uses Merkle Trees

Block Structure:

  • Each block contains a Merkle root in its header
  • Merkle root summarizes all transactions in the block
  • Changing any transaction changes the Merkle root

Benefits:

  1. Efficient verification: Prove transaction inclusion with O(log n) hashes
  2. Compact proofs: SPV nodes don't need full blockchain
  3. Data integrity: Any tampering is immediately detectable

Merkle Proofs (SPV)

Simplified Payment Verification allows lightweight clients to verify transactions without downloading the full blockchain.

To prove Tx B is in a block:

Provide: Hash A, Hash CD
Client calculates:
  1. Hash B (from Tx B)
  2. Hash AB = SHA256(Hash A + Hash B)
  3. Merkle Root = SHA256(Hash AB + Hash CD)
  4. Compare with block header's Merkle root

Code: Merkle Tree and Proof Verification


Address Encoding

Base58Check

Base58 encoding uses 58 characters (excluding 0, O, I, l to avoid confusion):

123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz

Base58Check adds a checksum:

  1. Add version byte prefix
  2. Calculate checksum: SHA256(SHA256(data)) (first 4 bytes)
  3. Append checksum to data
  4. Encode in Base58

Used for: Legacy addresses (1..., 3...)

Bech32 and Bech32m

Bech32 encoding (BIP-173) is used for SegWit addresses:

Characteristics:

  • Case-insensitive
  • Better error detection (BCH codes)
  • QR code friendly
  • Prefix: bc1 for mainnet, tb1 for testnet

Address Types:

  • bc1q...: Native SegWit (P2WPKH, P2WSH) - Bech32
  • bc1p...: Taproot (P2TR) - Bech32m

Bech32m (BIP-350) is a modified version for Taproot addresses with improved error detection.

Code: Address Generation (Full Pipeline)


Cryptographic Security Assumptions

What Bitcoin Assumes

Bitcoin's security relies on these assumptions holding true:

AssumptionIf Broken
SHA-256 is collision-resistantCould create invalid blocks
SHA-256 is preimage-resistantCould forge proof-of-work
ECDLP is hardPrivate keys could be derived from public keys
Random number generation is securePrivate keys could be predicted

Quantum Computing Considerations

Potential Threats:

  • Shor's algorithm could break ECDSA/Schnorr (public key → private key)
  • Grover's algorithm could speed up SHA-256 attacks (but only quadratic speedup)

Current Status:

  • No quantum computer capable of breaking Bitcoin exists today
  • Estimates suggest decades before practical quantum threats
  • Bitcoin community is researching post-quantum solutions
  • Addresses that haven't revealed public keys are safer

Mitigations:

  • Don't reuse addresses (limits public key exposure)
  • Post-quantum signature schemes being researched
  • Soft fork could add quantum-resistant signatures

Summary

Cryptographic PrimitivePurpose in Bitcoin
SHA-256Block hashing, TXIDs, PoW
SHA-256d (double)Block headers, Merkle trees
RIPEMD-160Address generation (Hash160)
secp256k1 (ECC)Key pairs, signatures
ECDSALegacy transaction signatures
SchnorrTaproot signatures, aggregation
Merkle TreesTransaction summarization, SPV proofs
Base58CheckLegacy address encoding
Bech32/Bech32mSegWit/Taproot address encoding

Resources