# Modular math and the shift cipher

The Caesar Cipher is a type of **shift cipher**. Shift ciphers work by using the modulo operator to encrypt and decrypt messages. The shift cipher has a **key**,** **`K`

, which is an *integer from 0 to 25*. We will only share this key with people that we want to see our message.

# How to encrypt

For every letter in the message ** M** :

**1.** Convert the letter into the number that matches its order in the alphabet starting from 0—A=0, B=1, C=2 ... Y=24, Z=25—and call this number `X`

.

**2.** Calculate: `Y = (X + K) mod 26`

.

**3.** Convert the number ** Y** into a letter that matches its order in the alphabet starting from 0—A=0, B=1, C=2 ... Y=24, Z=25.

**For Example: **We agree with our friend to use the shift cipher with key** K=19** for our message.

We encrypt the message "KHAN":

So, after applying the shift cipher with key `K=19`

, our message text "KHAN" gives us cipher text** **"DATG"**.**

We give the message "DATG" to our friend.

# How to decrypt

For every letter in the cipher text `C`

:

1. Convert the letter into the number that matches its order in the alphabet starting from 0—A=0, B=1, C=2 ... Y=24, Z=25—and call this number `Y`

.

2. Calculate: `X= (Y - K) mod 26`

.

3. Convert the number **X** into a letter that matches its order in the alphabet starting from 0.

(A=0, B=1, C=2, ..., Y=24, Z=25)

Our friend now decodes the message using our agreed upon key,** K=19**:

After decrypting the shift cipher with key `K=19`

, our friend deciphers the cipher text "DATG" into the message text "KHAN".

# Why is the shift cipher insecure?

A cipher should prevent an attacker, who has a copy of the cipher text but does not know the key, from discovering the contents of the message. Since *we only have 26 choices for the key*, someone could easily* try all of the 26 keys*, one by one, until they recover the message. This type of attack is called a **brute force attack**.

Next let's practice this cipher and earn some energy points! You deserve it.