Atbash Cipher in Python

Atbash Cipher in Python

I just finished listening to The Da Vinci Code audiobook and am feeling inspired to noodle with some cryptograms in Python.  One of the clues in the story involves a word written Atbash.  This is a simple substitution cipher where the encrypted characters are mapped to the reverse of the alphabet:

A -> Z
B -> Y
C -> X

Z -> A

 


#!/usr/bin/python3.6

def toAtBash(text):
characters = list(text.upper())
result = ""
for character in characters:
if character in code_dictionary:
result += code_dictionary.get(character)
else:
result += character # preserve non-alpha chars found
return result

alphabet = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")

reverse_alphabet = list(reversed(alphabet))

code_dictionary = dict(zip(alphabet, reverse_alphabet))

plainText= "No more rhymes now, I mean it."

print(plainText)

cipherText = toAtBash(plainText)

print(cipherText)

cipherText = toAtBash(cipherText)

print(cipherText)

Now let’s write a Python script to do this  It’s been a while since I worked in Python,  but this what I came up with:

Output

No more rhymes now, I mean it.
ML NLIV ISBNVH MLD, R NVZM RG.
NO MORE RHYMES NOW, I MEAN IT.

It’s worth noting that Atbash works both ways.  If you convert text to Atbash, then covert that text to Atbash, you get the original text.

Like I said, it’s been a while since I touched Python.  I’ll take a look another look at how to do this, make sure I’m using proper idioms and such.  This was quick and dirty.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.