DisSysLab

Cryptography for Cryptocurrency

Hash functions, hash pointers and digital signatures

A cryptocurrency is a distributed system in which agents who do not trust each other keep a shared ledger of payments. Before we can study how they agree on the ledger, we need three tools from cryptography: hash functions, hash pointers and digital signatures. The next lecture, Bitcoin, puts them together into cryptocurrencies.

This lecture follows chapter 1 of Narayanan, Bonneau, Felten, Miller and Goldfeder, Bitcoin and Cryptocurrency Technologies (Princeton University Press, 2016). A free draft of the book, video lectures and programming assignments are at bitcoinbook.cs.princeton.edu.

Every hash on this page is real The figures compute SHA-256, the hash function Bitcoin uses, in your browser. Type into them, change them, and try to break them.

1. Hash functions

A hash function H maps an input string of any size to an output of fixed size, and it is fast to compute. SHA-256 maps any input to 256 bits, written as 64 hexadecimal digits. The output is often called a digest: a short summary of a long message.

Input x
H(x) = SHA-256(x)
Figure 1. A hash function. Type anything: a word, a sentence, a whole book. The output is always 64 hexadecimal digits (256 bits). Press Change one character: the new hash differs from the old one in about half of its 256 bits (the changed hexadecimal digits are in orange). A small change to the input gives an unrecognizably different output.

Three properties we will assume A cryptographic hash function is collision resistant, hiding and puzzle friendly. The rest of this section explains each one and shows how they are used in cryptocurrency.

1.1 Collision resistance

Inputs x ≠ y collide if H(x) = H(y). Collisions must exist: there are infinitely many inputs and only finitely many outputs (2256 for SHA-256), so some outputs are shared by many inputs (the pigeonhole principle). A hash function is collision resistant if a collision — x ≠ y where H(x) = H(y) — cannot be found in a reasonable number of computational steps.

A caution

No hash function has been proved collision resistant. We use functions such as SHA-256 that experts have attacked for years without finding a collision. Some hash functions are clearly not collision resistant: one that returns the last 8 bits of its input collides on any two inputs that end in the same byte.

Question for you. Suppose H returns a 4-bit number, so there are 16 possible outputs. Keep an array D of 16 entries, all empty. Repeatedly pick a random input x, compute y = H(x); if D[y] is empty, store x there, and otherwise D[y] and x collide. How many times will you have to pick an input before you find the first collision? In the worst case you need 17 inputs: the first 16 could all land in different entries. How many do you need on average?

Let the hash have N possible outputs. The first collision happens at input number k if the first k−1 inputs land in different entries and input k lands in one of the k−1 occupied entries:

P(first collision at input k) = (N−1)/N · (N−2)/N · … · (N−k+2)/N · (k−1)/N,   for 2 ≤ k ≤ N+1.

This is the birthday paradox: in a room of only 23 people, the probability that two share a birthday is about 1/2, although there are 365 birthdays. A collision is expected after about √N inputs. For an n-bit hash, N = 2n, so a collision is expected after about 2n/2 inputs — for SHA-256, 2128 ≈ 3×1038, a very large number.

Figure 2. Hunting for a collision. To make collisions easy to find, this figure keeps only the first 8 bits of SHA-256, so there are N = 256 possible outputs, one per cell. Each step hashes a new random input and fills its cell. The hunt ends when an input lands in a cell that is already full. You might expect to need over a hundred inputs; you usually need about 20, close to √(πN/2) ≈ 20. Press Run 1,000 hunts to see the spread.

How collision resistance helps: message digests. If H(x) = H(y), we assume x = y, since H is collision resistant. To check that a file you downloaded is the file that was published, compare its hash with the published hash.

1.2 Hiding

Su makes a bet with Al that she can predict whether Al will wear shorts or trousers the next day. She puts her prediction in a sealed envelope and gives it to Tim for safekeeping. After Al appears the next day, they get the envelope from Tim and check whether Su was right.

Next, they want to use digital technology instead of depending on Tim. Su publishes y = H(x) where H is a collision-resistant hash, but Su keeps x secret. After Al appears the next day, Su reveals x; Al checks if H(x) = y; and they settle the bet.

If Al can find x from y and H then Al can choose what to wear to falsify Su's prediction.

Question for you. Can x be discovered?

Yes. There are only two possibilities. Al computes H for each possibility and finds the one that matches y. Though H is collision resistant, H does not hide information that comes from a small set.

The fix is to add a secret random value r, chosen from a spread-out distribution, for example 256 random bits. Su computes y = H(r ‖ x), where ‖ means concatenation. Su publishes y and H but not r or x. Now Al must guess both r and x: 2 × 2256 possibilities. There are only two predictions, but r alone makes guessing hopeless. The next day Su reveals both r and x, and Al checks that H(r ‖ x) = y. The value y that Su publishes is called her commitment; from now on we write it c.

Hiding H is hiding if, when r is chosen from a very spread-out distribution, there is no feasible way to find x from H(r ‖ x).

Length of Su’s secret r
Figure 3. Al tries to discover Su’s prediction. Su predicts shorts or trousers, and picks a secret r of the length you choose. Al sees only y and tries every pair (r, prediction) until one matches. With no r he needs at most 2 tries. Every extra bit of r doubles the work: at 20 bits he needs up to two million tries, and with a 256-bit r he would need up to 2 × 2256, about 2×1077.

1.3 Commitments

Hiding protects Su from Al. Now look at it from Al’s side. Suppose Su predicted shorts, and the next morning Al appears in trousers. Su would like to claim that she predicted trousers. To do that, she must reveal some r′ with H(r′ ‖ trousers) = c = H(r ‖ shorts): a collision, which she cannot find.

So the same scheme stops both of them. It lets Su commit to a prediction now and reveal it later, so that Al cannot learn it early and Su cannot change it. It is called a commitment scheme:

# commit: Su picks a fresh random nonce r and publishes c
r = random_256_bits()
c = H(r ‖ prediction)

# reveal: Su publishes r and prediction; anyone can check
def verify(c, r, prediction):
    return H(r ‖ prediction) == c
  1. Hiding Seeing c reveals nothing about the prediction. This is the hiding property of section 1.2. It protects Su from Al.
  2. Binding Su cannot change her prediction after committing. To claim a different prediction p′, Su needs some r′ with H(r′ ‖ p′) = c = H(r ‖ prediction): a collision. Collision resistance makes the commitment binding. It protects Al from Su.

A commitment is not encrypted, and it is never decrypted. Su opens it by revealing r and her prediction, and anyone can check them against c. And Tim is no longer needed: Su can publish c anywhere, because nobody has to be trusted to hold it.

A secret value used once is called a nonce. Choose a new r for every commitment: if Su bets with Al every day and reuses r, equal predictions produce equal commitments, and Al learns when she predicts the same thing again.

Figure 4. Commit, reveal and an attempt to cheat. 1. Su picks a nonce r, predicts shorts, and publishes c = H(r ‖ shorts). 2. The next morning Al appears in trousers. 3. Su reveals honestly; Al recomputes the hash and it matches c: Su loses the bet. 4. Su tries instead to claim she predicted trousers, with the same r. The hash does not match. To succeed she would have to find a collision.

1.4 Puzzle friendliness

A search puzzle is given by a hash function H, a puzzle id id, and a set Y of target outputs. A solution is any x with H(id ‖ x) in Y.

Puzzle friendly Let H have N possible outputs. H is puzzle friendly if there is no way to solve a search puzzle much faster than trying random values of x. Each try then succeeds with probability about |Y| / N, so the expected number of tries is about N / |Y|.

These numbers are approximate because no real hash function is perfect: its outputs are spread almost, but not exactly, evenly over the N possibilities.

Example. SHA-256 returns 256 bits, so it has N = 2256 possible outputs. Each try succeeds with probability about |Y| / 2256, and the expected number of tries is about 2256 / |Y|.

So the size of Y sets the difficulty of the puzzle. If Y is the set of all possible outputs, the first try succeeds. If Y is half the set of outputs, the expected number of tries to get a value in Y is about 2. If Y is the set of outputs in which the first d bits are zero, then increasing d by 1 reduces the size of Y by half, and the expected number of tries to get a value in Y doubles. This is Bitcoin’s mining puzzle, and it is the subject of a later lecture.

Puzzle id Leading zero bits d 12
Current try
Figure 5. Solving a search puzzle. Find a number x such that H(id ‖ x) begins with d zero bits (shown in teal). Each press of Solve numbers the id #1, #2, …, so each press is a new puzzle. The only method is to try x = 0, 1, 2, … Press Solve several times: the number of tries varies a lot from puzzle to puzzle, but averages about 2d. Raise d by one and the average doubles.

1.5 How a hash handles inputs of any length

Question for you. Suppose you have a function f that maps inputs of exactly m + n bits to outputs of m bits. How would you build a hash function for inputs of any length?

The Merkle–Damgård transform does it, and SHA-256 is built this way. Its compression function f takes 768 bits — a 256-bit chaining value and a 512-bit block of the message — and returns 256 bits.

  1. Pad the message so that its length is a multiple of 512 bits. The padding includes the length of the message; the security argument below depends on it.
  2. Split it into 512-bit blocks B1, …, Bk.
  3. Start from a fixed 256-bit initialization vector IV, given in the SHA-256 standard.
  4. Chain: C0 = IV, and for i > 0, Ci = f(Ci−1, Bi). The hash is Ck.

Why it is secure If the compression function f is collision resistant, then so is the hash built from it. A collision in the whole hash would give a collision in f at some step of the chain.

Figure 6. SHA-256 as a chain of compression steps. The message is split into 64-byte (512-bit) blocks; the last block ends with padding, shown as ·. Starting from the IV, each step feeds the chaining value and the next block into f. These are SHA-256’s real chaining values (the first 10 of 64 hex digits are shown), and the last one is the SHA-256 hash of the message. Edit the message: every chaining value after the block you changed is different.

2. Hash pointers

A hash pointer to data D is a pair (ptr, H(D)): ptr says where D is, and H(D) lets you check that D has not changed. If the data to which ptr points is modified from D to D′, while the hash pointer (ptr, H(D)) remains unchanged, then an agent can detect the modification because H(D′) ≠ H(D): since H is collision resistant, nobody can find a D′ ≠ D with H(D′) = H(D). So the data pointed to by a hash pointer is tamper-evident, provided the hash pointer itself is kept somewhere safe.

2.1 The block chain

Question for you. Design a tamper-evident ledger: a sequence of transactions that nobody can modify without others being able to tell.

A block chain is a linked list that uses hash pointers rather than regular pointers. The list starts with a standard genesis block — the zeroth block, B0, in the list. The k-th block, Bk, for k > 0, contains (1) a hash pointer (pk−1, H(Bk−1)) and (2) data Dk, where pk−1 is a pointer to Bk−1. An agent gets access to the list from the hash pointer to the head of the list.

Tamper evidence Lemma: If the hash pointer (pk, H(Bk)) to the k-th block remains unchanged, then a change to any block Bi, for i ≤ k, is detectable.

Proof, by induction on k

If block Bk is changed to Bk′, the change is detected because H(Bk′) ≠ H(Bk): since H is collision resistant, nobody can find a different block with the same hash. In particular, this proves the case k = 0: a change to the genesis block is detected.

If k > 0 and Bk is unchanged, then the hash pointer that Bk contains, (pk−1, H(Bk−1)), is unchanged too. So, by induction, a change to any of Bk−1, …, B0 is detectable.

Figure 7. A tamper-evident block chain. Each block stores prev, the hash of the previous block (the first 10 hex digits are shown), and the figure recomputes that hash and checks it. You hold the hash pointer to the head, in the last box. Edit any block’s data, or press Tamper: the next block turns orange. Press Attacker rewrites: the attacker updates every later block, and the mismatch moves to the head pointer, which the attacker cannot change.

2.2 Merkle trees

A Merkle tree is a binary tree that uses hash pointers in place of regular pointers. The tree is used as a tamper-evident data structure for storing data. The data is stored in the leaves of the tree. The verifier already holds the hash of the root, from a source it trusts. To show that data D is in the tree and has not changed, the prover supplies D and the hashes along D’s path to the root: one sibling hash per level. The verifier rehashes up the path and compares the result with the root it holds.

Using the same reasoning as for block chains, any change to D is detectable. The root must come from the verifier, not from the prover: a prover who could supply its own root could build any tree it liked.

With n items, the proof requires about log2 n hashes: 20 hashes for a million transactions. Checking one item in a block chain of n blocks can mean rehashing all n blocks; a Merkle tree needs only log2 n. Bitcoin puts each block’s transactions in a Merkle tree.

Figure 8. A Merkle tree and a proof of membership. Click a transaction at the bottom. Its path to the root is in blue, and the proof — one sibling hash per level, three for eight transactions — is in orange. Verify a proof rehashes up the path step by step and compares with the root that you hold. Tamper changes a transaction: every hash on its path changes, and the root no longer matches.

If the leaves are kept sorted, a Merkle tree can also prove non-membership: show the two adjacent leaves between which the missing item would be, with their paths to the root.

3. Digital signatures

Digital signatures with secret and public keys are implemented in three parts.

1. Create the keys. The owner generates a pair of keys. The owner keeps the secret key sk to itself, and publishes the public key pk for everyone.

(sk, pk) = generateKeys(keysize)

2. Sign a message. The owner signs a message with its secret key, and sends the message together with the signature. In the code below, the function sign is the signing algorithm.

sig = sign(sk, message)
send (message, sig)

3. Verify the message. A receiver checks the signature with the owner’s public key. verify returns True or False.

ok = verify(pk, message, sig)
  1. Valid Valid signatures verify. verify(pk, message, sign(sk, message)) is True.
  2. Unforgeable An agent without the secret key cannot sign a message so that it is verified using the public key. For any message that the owner of sk has not signed, an agent without sk cannot produce a sig with verify(pk, message, sig) = True, except with negligible probability.
A signature is not encryption

Bitcoin uses ECDSA, which has no encryption step for signing messages. Encryption is a different tool for keeping a message secret.

Unforgeability is defined by a game between a challenger, who holds the secret key sk, and an attacker, who knows only the challenger’s public key pk. The attacker may ask the challenger to sign any messages it chooses, a reasonable number of times — for example 230, but not 2128. Then the attacker must produce a signature that verifies on a new message (which is different from the messages that the attacker asked the challenger to sign). The scheme is unforgeable if every attacker that runs for a reasonable time, and asks for a reasonable number of signatures, wins with negligible probability.

Figure 9. The unforgeability game. The challenger generates keys and gives the attacker pk. The attacker picks messages and the challenger signs them. Then the attacker submits a new message with a signature it has made up. The signatures it has seen are no help: each belongs to its own message. verify fails, and the attacker loses. (The σ values here stand in for real signatures; the page does not implement a signature scheme.)

Sign the hash. A signature scheme signs short messages. To sign a long message M, sign H(M); because H is collision resistant, this is as good as signing M. In particular, to sign a whole ledger kept as a block chain, sign the hash pointer to its head: that one signature covers every block in the chain.

3.1 How to send secret, signed messages

Ana wants to send Ben a message M that only Ben can read, and Ben wants to be sure it came from Ana and was not changed.

  1. Ana signs using her secret key: sig = sign(skAna, M).
  2. Ana encrypts the pair (M, sig) with Ben’s public encryption key, msg = encrypt(pkBen, (M, sig)), and sends msg to Ben.
  3. Ben decrypts msg with his secret key and gets (M, sig) = decrypt(skBen, msg).
  4. Ben verifies Ana’s signature using her public key. If verify(pkAna, M, sig) = True, then Ana sent M and it was not changed.

4. Public keys as identities

Decentralized identity An agent can make a new public key, secret key pair by calling generateKeys. There is no registry and no central authority required to generate the keys. An agent can use different public keys that it generates as separate identities.

An agent X who uses public key, secret key pairs (pkX0, skX0) and (pkX1, skX1) can send some messages using (pkX0, skX0) and others using (pkX1, skX1). A receiver who gets a message signed with skX0 checks it with pkX0; the secret key never leaves X. The receiver knows only that the message is from the agent that holds that key pair, but cannot learn the agent’s name from the key.

The anonymity offered by public keys is limited: every message sent with one key is linked to that key, and patterns in those messages can reveal who is behind it. In Bitcoin these identities are called addresses; an address is the hash of a public key.

Next Bitcoin uses these tools. It starts with two simple cryptocurrencies, Goofycoin and Scroogecoin, and the double-spending problem, and ends with Bitcoin itself.

Summary

ToolPropertyWhat it gives us
Hash functionCollision resistant A short digest that identifies a document
Hiding, with collision resistanceCommitments: commit now, reveal later, no change possible
Puzzle friendlySearch puzzles whose difficulty we can set
Hash pointerDetects any change to the data Block chains and Merkle trees
Digital signatureUnforgeable Authorised payments; public keys as identities

Exercises

  1. A hash function returns the last 8 bits of its input. Give two inputs that collide. Why is a hash function that returns the first 8 bits of SHA-256 (as in figure 2) also easy to break?
  2. About how many random inputs do you need to find a collision in a 16-bit hash? In a 64-bit hash? Use figure 2 to check the 8-bit case.
  3. Why must Su choose a new random r for every commitment? Give an example in which reusing r leaks information.
  4. In figure 5, how many tries do you expect for d = 20? Bitcoin sets the difficulty so that the whole network solves one puzzle about every 10 minutes. If the network computes 1020 hashes per second, about how many leading zero bits does that correspond to?
  5. You keep only the hash pointer to the head of a block chain of 1,000 blocks. Someone gives you the whole chain. How do you check it, and how many hashes must you compute?
  6. A Merkle tree holds 220 transactions. How many hashes are in a proof of membership? Explain how a sorted Merkle tree proves that a transaction is not in it.
  7. Explain why signing H(M) is as good as signing M, if H is collision resistant.