# Chapter 2: Symmetric-key Cryptography#

Imagine you and your best friend have a secret language that only the two of you understand. That’s essentially what symmetric-key cryptography is all about. It’s like having a special lockbox where you both have the same key.

## How Symmetric-key Cryptography Works#

You and your friend agree on a secret key (let’s say, it’s a special way to mix up letters).

When you want to send a message, you use this key to scramble (encrypt) your message.

Your friend receives the scrambled message and uses the same key to unscramble (decrypt) it.

Anyone who doesn’t have the key just sees gibberish!

It’s simple and fast, but there’s a catch: how do you share the key without anyone else finding out?

## A Simple Example: The Caesar Cipher#

Let’s start with one of the oldest encryption techniques: the Caesar Cipher. It’s named after Julius Caesar, who used it to send secret military messages.

Here’s how it works:

Choose a number (let’s say 3).

Shift each letter in your message by that number.

To decrypt, shift back by the same number.

Let’s see it in action:

```
def caesar_cipher(text, shift, mode='encrypt'):
result = ""
for char in text:
if char.isalpha():
# Determine the ASCII offset based on whether the character is uppercase or lowercase
ascii_offset = 65 if char.isupper() else 97
if mode == 'encrypt':
# Shift forward for encryption
result += chr((ord(char) - ascii_offset + shift) % 26 + ascii_offset)
else:
# Shift backward for decryption
result += chr((ord(char) - ascii_offset - shift) % 26 + ascii_offset)
else:
# If it's not a letter, leave it unchanged
result += char
return result
# Let's try it out!
message = "HELLO WORLD"
shift = 3
encrypted = caesar_cipher(message, shift, 'encrypt')
decrypted = caesar_cipher(encrypted, shift, 'decrypt')
print(f"Original: {message}")
print(f"Encrypted: {encrypted}")
print(f"Decrypted: {decrypted}")
```

```
Original: HELLO WORLD
Encrypted: KHOOR ZRUOG
Decrypted: HELLO WORLD
```

Cool, right? But here’s the thing: the Caesar Cipher is super easy to crack. If someone knows it’s a Caesar Cipher, they just need to try 25 different shifts to find the right one.

## Modern Symmetric Encryption: AES#

Today, we use much more complex algorithms. One of the most popular is AES (Advanced Encryption Standard). It’s like the Caesar Cipher on steroids!

Instead of just shifting letters, AES:

Breaks the message into blocks

Applies multiple rounds of scrambling to each block

Uses a key that can be 128, 192, or 256 bits long (that’s a lot of possible keys!)

Let’s see a simple example of AES in action:

```
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
import os
def encrypt_aes(plaintext, key):
# Generate a random 16-byte IV
iv = os.urandom(16)
# Create an encryptor object
cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend())
encryptor = cipher.encryptor()
# Encrypt the plaintext
ciphertext = encryptor.update(plaintext.encode()) + encryptor.finalize()
return iv + ciphertext
def decrypt_aes(ciphertext, key):
# Extract the IV from the first 16 bytes
iv = ciphertext[:16]
ciphertext = ciphertext[16:]
# Create a decryptor object
cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend())
decryptor = cipher.decryptor()
# Decrypt the ciphertext
plaintext = decryptor.update(ciphertext) + decryptor.finalize()
return plaintext.decode()
# Let's try it out!
key = os.urandom(32) # 256-bit key
message = "AES is much stronger than Caesar Cipher!"
encrypted = encrypt_aes(message, key)
decrypted = decrypt_aes(encrypted, key)
print(f"Original: {message}")
print(f"Encrypted (hex): {encrypted.hex()}")
print(f"Decrypted: {decrypted}")
```

```
Original: AES is much stronger than Caesar Cipher!
Encrypted (hex): cb712bc8bb9bcb023ff5104f89e29dbf301356417c10f4890b293717345fcce11c89825e6c01f5ac223928080126399036237c8e3e5bcac5
Decrypted: AES is much stronger than Caesar Cipher!
```

## Pros and Cons of Symmetric-key Cryptography#

Pros:

It’s fast! Great for encrypting large amounts of data.

Uses less computational power than some other methods.

The algorithms are well-studied and considered secure (when used correctly).

Cons:

The big challenge: how do you securely share the key?

You need a different key for each person you communicate with securely.

If the key is compromised, all messages encrypted with it are at risk.

## Real-world Applications#

Securing your WhatsApp messages

Protecting data stored on your computer

Securing communication between your browser and websites (as part of HTTPS)

## What We Learned#

Symmetric-key cryptography uses the same key for encryption and decryption.

It’s like a secret language between friends.

The Caesar Cipher is a simple (but insecure) example.

Modern algorithms like AES are much more complex and secure.

It’s fast and efficient, but key distribution is a challenge.

## Quick Check: Did You Get It?#

Let’s see if you caught the main ideas:

In symmetric encryption, what’s the same for both sender and receiver? (Hint: It starts with ‘K’)

What’s the name of the ancient Roman who used a simple cipher? (Hint: Think salad)

What does AES stand for? (Hint: It’s Advanced, and it’s a Standard)

Think about your answers, then check below!

## Click to see the answers

Key

Caesar

Advanced Encryption Standard

Great job if you got them all!