BitcoinDev 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
PrimitivePurposeUsed in
Hash (SHA-256, SHA256D)Integrity, commitments, PoWBlock hashes, TXIDs, Merkle trees, mining
ECDSASignatures (legacy)P2PKH, P2SH, pre-Taproot outputs
Schnorr (BIP 340)Signatures (Taproot)P2TR outputs, signature aggregation
--- Sign ---
[Private key] ----\
                   --> [Signature]
[Message] ---------/

--- Verify ---
[Signature] ----\
[Message] ------- --> [Valid or Invalid]
[Public key] ----/

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

You can try hashing with the Hash tool.

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:

  • Block hashes
  • Transaction IDs (TXIDs)
  • Merkle tree nodes
  • Proof-of-work

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


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


Elliptic Curve Cryptography

Elliptic Curve Cryptography

Elliptic Curve

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 (used by both ECDSA and Schnorr for signatures), 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)

ECC and Signature Schemes

Elliptic Curve Cryptography (ECC) provides the curve (secp256k1), key generation, and the underlying math, it answers how you get a public key from a private key. Signature schemes such as ECDSA and Schnorr are different algorithms built on top of ECC that use those key pairs to sign and verify messages. Bitcoin uses the same curve for both; ECC is the foundation, ECDSA and Schnorr are the signature algorithms.


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

Signature types in Bitcoin:

  • ECDSA: Used for legacy outputs (P2PKH, P2SH, pre-Taproot SegWit).
  • Schnorr (BIP 340): Used for Taproot (P2TR) outputs; enables smaller signatures and aggregation.

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

ECDSA

ECDSA (Elliptic Curve Digital Signature Algorithm) was Bitcoin's original signature scheme. Bitcoin used it for all signatures until Taproot introduced Schnorr.

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 signatures (BIP 340) are Bitcoin's signature scheme for Taproot (P2TR) outputs, activated in November 2021 (block 709,632). Pieter Wuille was a key designer of BIP 340.

Why Schnorr in Bitcoin?

Schnorr offers simpler mathematics, stronger security proofs under standard assumptions, and linearity, the property that enables key and signature aggregation. Fixed 64-byte signatures reduce size and cost compared to variable-length ECDSA.

Schnorr vs ECDSA

PropertyECDSASchnorr (BIP 340)
Signature size70–72 bytes (DER)64 bytes (fixed)
EncodingVariable (DER)Fixed r||s
NonceMust be secret, unique; reuse leaks keyDerived (e.g. BIP 340 nonce); safer
AggregationNoYes (e.g. MuSig)
Batch verificationPer-signatureFaster batch mode
Security proofsMore complexSimpler, well-understood

BIP 340 Format

  • Signature: 64 bytes = 32-byte r (x-coordinate of ephemeral point) concatenated with 32-byte s (scalar).
  • Public key: 32-byte x-only public key (y-coordinate omitted; implied by curve and x). No encoding variability.
  • Tagged hashes: BIP 340 uses domain-separated hashes (e.g. BIP0340/challenge, BIP0340/aux, BIP0340/nonce) to avoid cross-protocol misuse.

Schnorr in Bitcoin (BIP 340)

Schnorr Signature Equations

Schnorr Signature Equations

Schnorr signatures in Bitcoin follow BIP 340: they use the secp256k1 curve, x-only public keys, and tagged hashes for all hashing steps (signing, nonce derivation, challenge computation).

Code: BIP-340 Schnorr Tagged Hash

Signature Aggregation

Schnorr's linearity allows multiple signatures to be combined into one. MuSig and MuSig2 (BIP 327) let multiple signers produce a single Schnorr signature for a combined public key. Benefits:

  • Privacy: Multi-party spends look like single-signature spends on-chain.
  • Efficiency: One 64-byte signature instead of many; lower fees.
  • Compatibility: Aggregated output is a normal Taproot key-path spend.

For how Taproot uses Schnorr and MuSig in practice, see Taproot.

Relation to Taproot

Taproot (BIPs 341, 342) uses Schnorr for all P2TR signatures. Key-path spends need only one Schnorr signature; script-path spends reveal one branch of a Merkle tree and still use Schnorr in Tapscript. That way, complex contracts can look identical to simple single-sig payments. For MAST, script paths, and address format, see Taproot.

Resources


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