# Deciphering A Caesar Cipher with Python

Caesar ciphers map out characters to other characters based on a number key chosen by the designer of the Caesar cipher.

There are many mathematical methods to crack the key value but since we have the power of Python, weâ€™ll install english_words and import english_words_set to crack a one key cipher.

This is a handy True or False function we can use with the imported library

If you read my previous blog on creating a Caesar cipher, the following functions will seem familiar.

Weâ€™ll import ascii_lowercase to create the LETTERS dictionary. This dictionary stores the alphabet as each individual character with integer values representing its chronological placement.

{â€˜aâ€™:â€™1', â€˜bâ€™:â€™2', â€¦.., â€˜yâ€™:â€™25', â€˜zâ€™:â€™26'}

Our alphabet_position() function takes a string text and turns it into a list of numbers using LETTERS.

Next, weâ€™ll make the nums() function that takes a list of individual words and turns each character for each word into a number using alphabet_position().

Notice how each word has its own number list

Our next function, cipher_tester() takes the number list from the previous function and an integer value to create a new word.

Although the function takes the entire number list as a parameter, we are only using the first list within the number list to find the key.

The output shows a word that is not part of the English language

Now we can crack the key value for the cipher using lets_crack_it().

This function takes two parameters, the ciphered text and an integer that represents the max number that you suspect is the key.

Weâ€™ll run a for loop that tests every key value between 1 and the max value. Next, the output of cipher_tester() is compared to words in english_words_set. If a word matches, lets_crack_it() returns the attempt number as the key value and the word.

Lets use our discovered key value as the key_shift parameter in cipher_tester() to find the rest of the words!

Even though we successfully deciphered the text, there are a few things to note.

The original key was 6 but we discovered 20 to work. This suggests that our algorithm works in reverse starting with 26 as value 1. If you use 6 in cipher_tester(), youâ€™ll get different words.

Using this method, you might get unlucky and match with an English word thatâ€™s not part of the deciphered text. To avoid this, test different words by changing the test_word.

On our next Caesar cipher walkthrough, weâ€™ll build a cipher that has multiple key values and experiment with larger texts.

Join other developers and claim your FAUN account now!

@thecybermutt

Influence

Total Hits

Posts