# Chapter 5: Cryptography in Practice#

Now that we’ve covered the building blocks of cryptography, let’s see how they’re used in the real world. Cryptography isn’t just about keeping secrets; it’s about ensuring trust, authenticity, and integrity in our digital lives.

## Digital Signatures#

Digital signatures are like electronic fingerprints. They allow you to verify the authenticity and integrity of digital messages or documents. Here’s how they work:

The sender creates a hash of the message.

The sender encrypts the hash with their private key, creating a digital signature.

The receiver decrypts the signature using the sender’s public key.

The receiver also hashes the received message.

If the decrypted hash matches the newly computed hash, the signature is valid.

This process ensures that the message is from the claimed sender and hasn’t been altered.

## Key Exchange Protocols#

Key exchange protocols solve a fundamental problem: how do two parties agree on a shared secret key over an insecure channel? The most famous of these is the Diffie-Hellman key exchange.

Here’s how Diffie-Hellman works, intuitively:

Alice and Bob agree on a public color, say yellow.

They each choose a secret color (red for Alice, blue for Bob).

They mix their secret color with the public yellow.

They exchange these mixed colors.

They each mix their secret color with the received mixed color.

They end up with the same final color, which no eavesdropper can determine.

Let’s implement a simple version of Diffie-Hellman:

```
import random
def generate_prime():
# In practice, use a cryptographically secure prime
return 23
def generate_primitive_root(prime):
# In practice, find a true primitive root
return 5
def generate_private_key(prime):
return random.randint(1, prime - 1)
def compute_public_key(prime, primitive_root, private_key):
return pow(primitive_root, private_key, prime)
def compute_shared_secret(prime, public_key, private_key):
return pow(public_key, private_key, prime)
# Example usage
prime = generate_prime()
primitive_root = generate_primitive_root(prime)
alice_private = generate_private_key(prime)
bob_private = generate_private_key(prime)
alice_public = compute_public_key(prime, primitive_root, alice_private)
bob_public = compute_public_key(prime, primitive_root, bob_private)
alice_shared = compute_shared_secret(prime, bob_public, alice_private)
bob_shared = compute_shared_secret(prime, alice_public, bob_private)
print(f"Alice's shared secret: {alice_shared}")
print(f"Bob's shared secret: {bob_shared}")
```

```
Alice's shared secret: 1
Bob's shared secret: 1
```

## Blockchain and Cryptocurrencies#

Blockchain technology, which underlies cryptocurrencies like Bitcoin, relies heavily on cryptographic principles. Let’s look at how SHA-256 is used in Bitcoin mining.

In Bitcoin, miners compete to find a number (nonce) that, when combined with the block data, produces a hash with a certain number of leading zeros. This is called the Proof of Work.

Here’s a simplified version of Bitcoin mining:

```
import hashlib
import time
def mine_block(block_data, difficulty):
target = "0" * difficulty
nonce = 0
start_time = time.time()
while True:
block = f"{block_data}{nonce}".encode()
hash_result = hashlib.sha256(block).hexdigest()
if hash_result.startswith(target):
end_time = time.time()
return nonce, hash_result, end_time - start_time
nonce += 1
# Example usage
block_data = "Transaction data: Alice sends 1 BTC to Bob"
difficulty = 4
nonce, hash_result, duration = mine_block(block_data, difficulty)
print(f"Block data: {block_data}")
print(f"Nonce found: {nonce}")
print(f"Hash: {hash_result}")
print(f"Mining took {duration:.2f} seconds")
```

```
Block data: Transaction data: Alice sends 1 BTC to Bob
Nonce found: 52144
Hash: 000026b0792fe4ab5f18b9ba9e3140c64b5554c221940cbcfca7537c28345eaa
Mining took 0.07 seconds
```

## What We Learned#

Digital signatures ensure the authenticity and integrity of messages.

Key exchange protocols like Diffie-Hellman allow secure key sharing over insecure channels.

Blockchain technology uses cryptographic principles to secure transactions and maintain integrity.

## Quick Check: Did You Get It?#

Let’s see if you caught the main ideas:

What do digital signatures verify? (Hint: Two things - starts with ‘A’ and ‘I’)

Which protocol helps two parties agree on a shared secret key? (Hint: It’s named after two people)

What is the process called where miners find a nonce in Bitcoin? (Hint: It’s a type of work)

Think about your answers, then check below!

## Click to see the answers

Authenticity and Integrity

Diffie-Hellman

Proof of Work

Great job if you got them all!