Chapter 2: Cryptography Fundamentals

Chapter 2: Cryptography Fundamentals

Cryptography is the cornerstone of blockchain technology. This chapter delves deep into the core cryptographic concepts that underpin blockchain security, including hash functions, public key cryptography, digital signatures, and other key technologies.

Chapter Objectives:

  • Understand the core role of cryptography in blockchain
  • Master the characteristics and applications of hash functions
  • Learn public/private key encryption mechanisms
  • Understand how digital signatures work
  • Explore advanced cryptographic structures like Merkle trees

2.1 Introduction to Cryptography

Cryptography is the science of secure communication in adversarial environments. In blockchain, cryptography provides the following key functions:

Core Goals of Cryptography

  1. Confidentiality

    • Ensures information can only be read by authorized parties
    • Prevents unauthorized access
  2. Integrity

    • Detects whether data has been tampered with
    • Ensures data has not been modified
  3. Authentication

    • Verifies the identity of communicating parties
    • Confirms message origin
  4. Non-repudiation

    • Sender cannot deny having sent a message
    • Provides evidence of actions

Cryptographic Applications in Blockchain

Hash Function Block Linking Proof of Work Address Gen Asymmetric Account System Tx Signing Identity Digital Sig Tx Authorization MultiSig Message Auth Merkle Tree Data Verify Light Node State Proof

2.2 Hash Functions

What is a Hash Function?

A Hash Function is a one-way function that maps input data of arbitrary length to fixed-length output.

Key Properties of Hash Functions

  1. Deterministic

    • Same input always produces same output
    • Reproducible and verifiable
  2. Fast Computation

    • Can quickly compute hash values
    • Efficient verification process
  3. One-way

    • Cannot reverse engineer original data from hash
    • Pre-image resistance
  4. Avalanche Effect

    • Small input changes cause massive output changes
    • Enhances security
  5. Collision Resistance

    • Extremely difficult to find two different inputs producing same output
    • Prevents forgery attacks

SHA-256 Algorithm

SHA-256 (Secure Hash Algorithm 256-bit) is the primary hash algorithm used by Bitcoin.

SHA-256 Characteristics

  • Output length: 256 bits (32 bytes)
  • Typically represented as 64 hexadecimal characters
  • Fast computation, high security

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// SHA-256 hash example
const crypto = require('crypto');

function sha256(data) {
return crypto.createHash('sha256')
.update(data)
.digest('hex');
}

// Example 1: Plain text
console.log(sha256('Hello, Blockchain!'));
// Output: 7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069

// Example 2: Small change leads to completely different hash
console.log(sha256('Hello, blockchain!')); // Note lowercase b
// Output: 93a0f1d4f8e8e8c4... (completely different)

Hash Applications in Blockchain

1. Block Linking

Block N-1 Block N Block N+1

2. Proof of Work (PoW)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Simplified PoW example
function proofOfWork(blockData, difficulty) {
let nonce = 0;
const target = '0'.repeat(difficulty);

while (true) {
const hash = sha256(blockData + nonce);

if (hash.startsWith(target)) {
return { nonce, hash };
}

nonce++;
}
}

// Find hash starting with 4 zeros
const result = proofOfWork('Block Data', 4);
console.log(`Found: ${result.hash} with nonce ${result.nonce}`);
// Output: Found: 0000a3f2... with nonce 157392

3. Address Generation

Public Key SHA-256 RIPEMD -160 Base58 Check Address

Other Important Hash Algorithms

RIPEMD-160

  • Output: 160 bits (20 bytes)
  • Use: Bitcoin address generation
  • Feature: Shorter output, saves space

Keccak-256

  • Used in: Ethereum
  • Output: 256 bits
  • Feature: SHA-3 variant

Blake2

  • Used in: Some emerging blockchains
  • Feature: Faster than SHA-256
  • Security: Comparable to SHA-3

2.3 Symmetric and Asymmetric Encryption

Symmetric Encryption

Uses the same key for encryption and decryption.

How It Works

Sender Receiver Shared Key K Encrypt(M, K) Ciphertext C Decrypt(C, K) Sender Receiver

Common Symmetric Encryption Algorithms

  • AES (Advanced Encryption Standard)

    • Most widely used
    • Supports 128, 192, 256-bit keys
  • DES/3DES

    • Older standard
    • No longer recommended

Pros and Cons

Pros:

  • Fast encryption speed
  • Suitable for large data volumes
  • Low computational resource consumption

Cons:

  • Difficult key distribution
  • Complex key management
  • Not suitable for public networks

Asymmetric Encryption

Uses a key pair: Public Key and Private Key.

Core Concept

Key Pair Gen Public Key Private Key Mathematical One-way Link

Encrypted Communication Flow

Alice Bob Public Key pk_Bob Encrypt(M, pk_Bob) Ciphertext C Decrypt(C, sk_Bob) Alice Bob

Common Asymmetric Encryption Algorithms

1. RSA

  • Based on integer factorization problem
  • Key length: 2048-4096 bits
  • Use: TLS/SSL, digital signatures
1
2
3
4
5
6
7
8
9
// RSA concept example (simplified)
// Key generation
const { publicKey, privateKey } = generateRSAKeyPair();

// Encryption
const encrypted = rsaEncrypt(message, publicKey);

// Decryption
const decrypted = rsaDecrypt(encrypted, privateKey);

2. ECC (Elliptic Curve Cryptography)

  • Based on elliptic curve discrete logarithm problem
  • Key length: 256 bits (equivalent to RSA 3072-bit security)
  • Advantage: Shorter keys, more efficient

Common Curves in Blockchain:

  • secp256k1: Used by Bitcoin, Ethereum
  • Ed25519: Used by Solana, Polkadot
  • secp256r1: Some enterprise blockchains

How ECC Works

Elliptic Curve y²=x³+ax+b secp256k1 y²=x³+7 Point Add P+Q=R Private Key Random 256bit Public Key pk=sk×G

Example: Ethereum Key Pair

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Ethereum key pair generation example
const { randomBytes } = require('crypto');
const secp256k1 = require('secp256k1');

// 1. Generate private key (256-bit random number)
let privateKey;
do {
privateKey = randomBytes(32);
} while (!secp256k1.privateKeyVerify(privateKey));

console.log('Private Key:', privateKey.toString('hex'));
// Output: 7c4e8... (64 hex chars = 32 bytes = 256 bits)

// 2. Derive public key from private key
const publicKey = secp256k1.publicKeyCreate(privateKey, false);
console.log('Public Key:', publicKey.toString('hex'));
// Output: 04b8a... (130 hex chars = 65 bytes, uncompressed format)

// 3. Generate Ethereum address (last 20 bytes of Keccak-256 hash of public key)
const keccak256 = require('keccak256');
const address = keccak256(publicKey.slice(1)).slice(-20).toString('hex');
console.log('Address: 0x' + address);
// Output: 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb0

Symmetric vs Asymmetric Encryption Comparison

Feature Symmetric Asymmetric
Keys Single key Public + Private
Speed Fast Slow (10-1000x)
Key Distribution Difficult Easy
Use Case Large data encryption Key exchange, signatures
Examples AES, DES RSA, ECC
Blockchain App Wallet encryption Transaction signing

2.4 Digital Signatures

Digital Signatures use a private key to sign data, and anyone can verify the signature’s authenticity using the corresponding public key.

Purpose of Digital Signatures

  1. Authentication: Proves message truly comes from private key holder
  2. Data Integrity: Proves message hasn’t been tampered with
  3. Non-repudiation: Signer cannot deny having signed

Digital Signature Workflow

Message M Hash Sign sk Signature σ Verify pk Valid Invalid

ECDSA (Elliptic Curve Digital Signature Algorithm)

The signature algorithm used by Bitcoin and Ethereum.

Signature Generation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Ethereum transaction signing example
const secp256k1 = require('secp256k1');
const keccak256 = require('keccak256');

// Transaction data
const txData = {
nonce: 0,
gasPrice: '20000000000',
gasLimit: '21000',
to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb0',
value: '1000000000000000000', // 1 ETH
data: '0x'
};

// 1. Serialize transaction data (RLP encoding)
const serialized = rlpEncode(txData);

// 2. Calculate hash
const txHash = keccak256(serialized);

// 3. Sign with private key
const { signature, recid } = secp256k1.ecdsaSign(txHash, privateKey);

// 4. Signature result
const r = signature.slice(0, 32);
const s = signature.slice(32, 64);
const v = recid + 27; // Ethereum's v value

console.log('Signature - r:', r.toString('hex'));
console.log('Signature - s:', s.toString('hex'));
console.log('Signature - v:', v);

Signature Verification

1
2
3
4
5
6
7
8
// Verify signature
function verifySignature(txHash, signature, publicKey) {
return secp256k1.ecdsaVerify(signature, txHash, publicKey);
}

// Usage
const isValid = verifySignature(txHash, signature, publicKey);
console.log('Signature valid:', isValid); // true

Bitcoin Transaction Signing

Build Tx Serialize Double SHA-256 ECDSA Sign Complete Tx

Multi-Signature (MultiSig)

Requires multiple private keys to sign together to complete a transaction.

M-of-N MultiSig

2-of-3 MultiSig Alice Bob Charlie Tx Sig A Sig B Valid

Bitcoin P2SH MultiSig Script

1
2
3
4
5
# 2-of-3 multisig script
OP_2
<Public Key A> <Public Key B> <Public Key C>
OP_3
OP_CHECKMULTISIG

2.5 Merkle Trees

A Merkle Tree, also known as a hash tree, is a tree data structure used to efficiently verify the integrity of large datasets.

Merkle Tree Structure

Merkle Root Hash 0-1 Hash 2-3 Hash 0 Hash 1 Hash 2 Hash 3 Tx 0 Tx 1 Tx 2 Tx 3

Building a Merkle Tree

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// Merkle tree implementation example
const crypto = require('crypto');

class MerkleTree {
constructor(leaves) {
this.leaves = leaves.map(l => this.hash(l));
this.root = this.buildTree(this.leaves);
}

hash(data) {
return crypto.createHash('sha256')
.update(data)
.digest('hex');
}

buildTree(nodes) {
if (nodes.length === 1) {
return nodes[0];
}

const parents = [];

for (let i = 0; i < nodes.length; i += 2) {
const left = nodes[i];
const right = nodes[i + 1] || nodes[i]; // Duplicate last node if odd count

const parent = this.hash(left + right);
parents.push(parent);
}

return this.buildTree(parents);
}

getRoot() {
return this.root;
}
}

// Usage example
const transactions = ['tx1', 'tx2', 'tx3', 'tx4'];
const tree = new MerkleTree(transactions);
console.log('Merkle Root:', tree.getRoot());

Merkle Proof

Lightweight verification without downloading all data.

Hash 3 Hash 0-1 Hash Tx 2 Hash 2-3 Calc Root Compare Exists Not Found

Merkle Proof Code Implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class MerkleTree {
// ... previous code ...

// Generate Merkle proof
getProof(leaf) {
let index = this.leaves.indexOf(this.hash(leaf));
if (index === -1) return null;

const proof = [];
let nodes = this.leaves;

while (nodes.length > 1) {
const parents = [];

for (let i = 0; i < nodes.length; i += 2) {
const left = nodes[i];
const right = nodes[i + 1] || nodes[i];

if (i === index || i === index - 1) {
// Record sibling node
const sibling = (i === index) ? right : left;
const position = (i === index) ? 'right' : 'left';
proof.push({ hash: sibling, position });
index = Math.floor(index / 2);
}

parents.push(this.hash(left + right));
}

nodes = parents;
}

return proof;
}

// Verify Merkle proof
verifyProof(leaf, proof, root) {
let hash = this.hash(leaf);

for (const { hash: siblingHash, position } of proof) {
if (position === 'left') {
hash = this.hash(siblingHash + hash);
} else {
hash = this.hash(hash + siblingHash);
}
}

return hash === root;
}
}

// Usage example
const tree = new MerkleTree(['tx1', 'tx2', 'tx3', 'tx4']);
const proof = tree.getProof('tx2');
const isValid = tree.verifyProof('tx2', proof, tree.getRoot());

console.log('Merkle Proof:', proof);
console.log('Verification Result:', isValid); // true

Applications of Merkle Trees

1. Bitcoin Block Structure

Version Previous Hash Merkle Root Timestamp Difficulty Nonce Transactions

2. SPV Light Nodes

SPV (Simplified Payment Verification) nodes only download block headers, not all transactions.

Full Node ~500GB Full Verify Light Node ~100MB Merkle Proof

3. State Tree

Ethereum uses Merkle Patricia Trie to store account state.

State Tree Account State Tx Tree Tx Data Receipt Tree Tx Receipts

2.6 Advanced Cryptographic Concepts

Zero-Knowledge Proof (ZKP)

Zero-Knowledge Proof allows a prover to convince a verifier that a statement is true without revealing any additional information.

Classic Example: Ali Baba’s Cave

Alice enters Bob requests Alice exits from requested side Knows secret 100% success Doesn't know Prob 1/2^N

zk-SNARKs

zk-SNARKs (Zero-Knowledge Succinct Non-Interactive Argument of Knowledge)

Applications:

  • Zcash: Privacy transactions
  • Tornado Cash: Ethereum mixer
  • zkSync: Layer 2 scaling
Succinct ~200 bytes Non-Interactive Setup Prove Verify

Homomorphic Encryption

Homomorphic Encryption allows computation directly on ciphertext, with decryption yielding the result of operations on plaintext.

Traditional: E(a)+E(b)≠E(a+b) Homomorphic: E(a)⊕E(b)=E(a+b) Private Comp

Threshold Signature

Multiple parties jointly hold fragments of a private key, requiring t-of-n fragments to generate a valid signature.

Shard 1 Shard 2 Shard 3 Any 3 Combine Sig Shard 4 Shard 5 ≤2 Cannot sign

Chapter Summary

Navigation:

0%