Study notesWeek 2: Cryptography You Need
Week 2

Cryptography You Need

Outcomes

What You Will Be Able To Do

Map

Three Needs, Four Tools

NeedTool
Detect changeHash function
Prove authorshipDigital signature
Summarise many itemsMerkle tree
Identify an ownerPublic key
Hashing

Hash Function: A Digital Fingerprint

Security

Properties That Matter

Live code

Demo: Hashing In Python

import hashlib

a = hashlib.sha256(b'Alice pays Bob 5').hexdigest()
b = hashlib.sha256(b'Alice pays Bob 6').hexdigest()
print(a)
print(b)
print(a == b)
Tamper evidence

Hashes Chain Blocks

Block 1: hash A
Block 2: prev A, hash B
Block 3: prev B, hash C

Edit Block 1 -> hash A'
Block 2 says prev A: mismatch
Key pairs

Public And Private Keys

Responsibility

Your Key Is Your Authority

Authorisation

Digital Signatures

Live code

Demo: Sign And Verify

from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from cryptography.exceptions import InvalidSignature

key = Ed25519PrivateKey.generate()
sig = key.sign(b'Alice pays Bob 5')
key.public_key().verify(sig, b'Alice pays Bob 5')
try:
    key.public_key().verify(sig, b'Alice pays Bob 500')
except InvalidSignature:
    print('rejected')
Commitment

Why A Merkle Tree

Merkle root

Building The Tree

LevelContents
LeavesHash of each transaction
MiddleHash of each pair
RootOne hash for everything
tx1 tx2 tx3 tx4
 h1  h2  h3  h4
  h12     h34
      root
Live code

Demo: Merkle Root In Python

import hashlib

def h(b):
    return hashlib.sha256(b).digest()

def merkle_root(txs):
    level = [h(t) for t in txs]
    while len(level) > 1:
        if len(level) % 2 == 1:
            level.append(level[-1])
        level = [h(level[i] + level[i + 1]) for i in range(0, len(level), 2)]
    return level[0].hex()
Putting it together

All Tools In One Block

Header { prev_hash, merkle_root, time, nonce }
Body   { tx1+sig, tx2+sig, tx3+sig }
Week 2 in five lines

Recap

Week 3

Next Week: Bitcoin

Hands-on

Questions And Exercise