Hacking Secret Ciphers with Python

(Ann) #1

114 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


What’s so special about the numbers 0, 8, 16, and 24? These are the numbers we get when,
starting from 0, we add the key (which in this example is 8). 0 + 8 is 8, 8 + 8 is 16, 16 + 8 is 24.
24 + 8 would be 32, but since 32 is larger than the length of the message, we stop at 24.


So, for the nth column’s string we start at index n, and then keep adding 8 (which is the key) to get
the next index. We keep adding 8 as long as the index is less than 30 (the message length), at
which point we move to the next column.


If we imagine a list of 8 strings where each string is made up of the characters in each column,
then the list value would look like this:


['Ceno', 'onom', 'mstm', 'me o', 'o sn', 'nio.', ' s ', 's c']


This is how we can simulate the boxes in Python code. First, we will make a list of blank strings.
This list will have a number of blank strings equal to the key because each string will represent a
column of our paper-and-pencil boxes. (Our list will have 8 blank strings since we are using the
key 8 in our example.) Let’s look at the code.


transpositionEncrypt.py



  1. Each string in ciphertext represents a column in the grid.



  2. ciphertext = [''] * key


The ciphertext variable will be a list of string values. Each string in the ciphertext
variable will represent a column of the grid. So ciphertext[0] is the leftmost column,
ciphertext[1] is the column to the right of that, and so on.


The string values will have all the characters that go into one column of the grid. Let’s look again
at the grid from the “Common sense is not so common.” example earlier in this chapter (with
column numbers added to the top):


0 1 2 3 4 5 6 7
C o m m o n (s) s
e n s e (s) i s (s)
n o t (s) s o (s) c
o m m o n.

The ciphertext variable for this grid would look like this:





ciphertext = ['Ceno', 'onom', 'mstm', 'me o', 'o sn', 'nio.', ' s ', 's c']
ciphertext[0]
'Ceno'




Free download pdf