beanz Magazine

Python Ciphers

Trending Topics 2019 on Flickr

Pretend to be a spy with some of these fun python encryption methods!

Python Ciphers

Take a look at the following four messages:

  1. gvlsjgqqszqovusuvamoomvixvpihtflqzplmqh
  2. deiruberasdnuopnoillimowtwolebteefytrof
  3. for tyf eet bel owt wom ill ion pou nds are bur ied
  4. deiruberasdnuopnoillimowtwolebteefytrof

All four are different encryptions of the same message: “Forty feet below two million pounds are buried”. This is a real message, found on a stone tablet approximately 27 meters down in a pit on Oak Island, Nova Scotia. To this day no treasure has been found on the island, and we do not know if there is really a treasure at the bottom of a 40 foot pit on the island or not. But the first to find this message had to unscramble the original jumble of letters in order to learn that a treasure may exist nearby.

For over three thousand years, people have been sending encrypted messages to communicate secrets of all sorts. The messages range from top secret military information to friends trying to evade parents and teachers while communicating plans between one another. The ability to send sensitive information that an enemy or “spy” cannot read is so prized that its study has gone from being mostly a branch of language and linguistics, to a rather complex branch of mathematics and computer science known as cryptography.

Without cryptography, we would never enter our credit card numbers into online shopping sites or send emails containing personal or valuable information. The ability to keep our personal information out of the hands of those who might misuse it is foundational to just about anything we do online. As such, cryptography plays a major role in the world economy, as well as in most people’s everyday lives.

Useful Functions and Methods

The encryption techniques used by cryptographers today often require years of study to master. However, Python has a few built-in methods and functions that can be used to create relatively simple programs which allow a beginner to quickly encode a message. The methods used to encrypt the message at the beginning of the article include:

Proper capitalization can provide big clues to anyone trying to decipher your code. As such, we decided to first convert all the letters in any message to lowercase. The “s” stands for the string of letters (the message) that we want to rewrite in all lower case letters. If you prefer messages in upper case, try s.upper() instead.

s.replace(‘ ‘,”)
White spaces in an encrypted message tell a “spy” how long each word is, which is a significant clue to anyone trying to break your code. As such, we eliminate all spaces by using the .replace() method to tell Python that every time it sees a blank space, ‘ ‘, replace it with no space, ”.

Mod – %
Mod is used to tell us the remainder when one number is divided by another. For example, 7 % 2 equals 1 (seven divided by two has a remainder of one). The fact that any integer divided by two has a remainder of either zero or one is useful for pulling out every other letter in a message.

.maketrans(string1, string2) replaces each letter in string1 with the corresponding letter in string2. This makes it easy to “rename” letters in a transposition cipher. Note: string1 and string2 must have equal lengths and ideally will contain all the letters of the alphabet.

The join() method converts a list into a string. This is a bit technical, but in order to add something (such as a space) into a string in Python, we must first convert to string to a list (using square brackets), and then turn it back into a string, joining it together with a blank space.

The len() function in Python counts the length of its argument. For example, len(‘computer’) equals eight, because the word computer contains eight letters.

The Code: Forty feet below two million pounds are buried

The following snippets of code are written in Python (3.7) and used to create the encryptions of “Forty feet below two million pounds are buried” at the beginning of the article. Although we wouldn’t want to trust any of our deepest secrets to these forms of encryption, they can be fun for scrambling less sensitive messages or challenging a friend to decode a note. You can copy them directly into Python 3.x (just about any version of Python 3) and try entering your own messages.

Substitution: gvlsjgqqszqovusuvamoomvixvpihtflqzplmqh
In a substitution cipher, we replace each letter of the alphabet with a different letter. It may be hard to believe, but in a 26 letter alphabet, this leads to over 400,000,000,000,000,000,000,000,000 possible encryptions!

text_to_cipher = input('Text to cipher: ')

lowercase = text_to_cipher.lower()
nospace = lowercase.replace(' ', '')

alphabet = 'abcdefghijklmnopqrstuvwxyz'
cipher_letters = 'fzkhqgcdmynoaivxbltspruwje'
translate = str.maketrans(alphabet, cipher_letters)

ciphered = nospace.translate(translate)
print(f'Ciphered text: {ciphered}')

Rail Fence Cipher: otfeblwwmlinonsrbrefryeteotoilopudaeuid
In a rail fence cipher (with two rows), we remove every other letter of a message, and tack these letters on to the end. For example, ‘ilovecode’, becomes ‘lvcdioeoe’.

message = input('Text to cipher: ')

lowercase = message.lower()
nospace = lowercase.replace(' ', '')

even = ''
odd = ''
total = 0

for letter in nospace:
    if total % 2 == 0:
        even = even + letter
        odd = odd + letter
    total = total + 1

ciphertext = odd + even


Insert Spaces: for tyf eet bel owt wom ill ion pou nds are bur ied
It is surprising how jumbled a message becomes when we simply add a space every few letters. This technique is even more effective when we add the spaces in at random intervals, but for the sake of keeping the code simple, we chose to add a space after every three characters.

message = input('Text to cipher: ')
lowercase = message.lower()
nospace = lowercase.replace(' ', '')

n = 3

insert = [nospace[i:i+n] for i in range(0, len(nospace), n)]
result = ' '.join(insert)


Reverse Cipher: deiruberasdnuopnoillimowtwolebteefytrof
Once a message extends beyond a couple of words, simply writing it backwards may be enough to throw off an unsuspecting reader.

message = input('Text to cipher: ')

lowercase = message.lower()
nospace = lowercase.replace(' ','')

translate = ' '

i = len(nospace) - 1


while i >= 0:
    translate = translate + nospace[i]
    i = i - 1


Learn More

Mysterious Codes and Ciphers

Cracking Codes with Python




Hacking Secret Ciphers with Python

Cryptography with Python

Monoalphabetic and Polyalphabetic cipher in Python

Cracking Codes with Python

Silly ciphers

Codes, Cipher, Encryption and Cryptology

Secret Codes for Kids

Also In The April 2020 Issue

As students reach the age of 13 the importance of them understanding their rights and privacy online becomes crucial.

The iDTech summer camp recently posted 102 questions. Here are a few with links to the full list.

Being well-read is essential in everything in life, and coding is no exception! Here are some book recommendations to make you a coding master.

The circus is in town, but they're missing one of their colourful balls. Let's make one for them!

Sundials were one of the first ways people kept track of time. But how did they work?

New to physical computing? MircoPython may be perfect or you!

It's project time! In this article we go over how the same processes used in big factories can be used to control a simple LED.

What do bubbles, pancakes, and spaghetti all have in common? They're all great for sorting!

Yee-ha! In the wild wild west of the internet, antivirus software is a must-have partner.

Exploring the concept of RAM and how it helps your MInecraft game run better.

Breaking down big problems into smaller ones is a great way to solve them. Let's see how recursion helps us do this!

How did this pale blue dot that we call Earth first begin? The answer is even more fascinating than imagined.

Have you ever wondered why your computer's mouse is called that? Well it all started with a fellow named Douglas and a block of wood...

How do you power devices at the top of mountains and the bottom of oceans? Let's find out!

Links from the bottom of all the April 2020 articles, collected in one place for you to print, share, or bookmark.

Interesting stories about computer science, software programming, and technology for April 2020.