Hacking Secret Ciphers with Python

(Ann) #1

284 http://inventwithpython.com/hacking


Email questions to the author: [email protected]






  1. First create a simple sub key from the letterMapping mapping.



  2. key = ['x'] * len(LETTERS)


Since the simpleSubstitutionCipher.decryptMessage() function only decrypts
with keys instead of letter mappings, we need the decryptWithCipherletterMapping()
function to convert a letter mapping into a string key.


The simple substitution keys are strings of 26 characters. The character at index 0 in the key
string is the substitution for A, the character at index 1 is the substitution for B, and so on.


Since the letter mapping might only have solutions for some of the letters, we will start out with a
key of ['x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x',
'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x',
'x']. This list is created on line 140 by using list replication to replicate the list ['x'] 26
times. Since LETTERS is a string of the letters of the alphabet, len(LETTERS) evaluates to
26. When the multiplication operator is used on a list and integer, it does list replication.


We don’t have to use 'x', we can use any lowercase letter. The reason we need to use a
lowercase letter is because it acts as a “placeholder” for the simple substitution key. The way
simpleSubCipher.py works, since LETTERS only contains uppercase letters, any lowercase letters
in the key will not be used to decrypt a message.


The 26-item list in key will be joined together into a 26-character string at the end of the
decryptWithCipherletterMapping() function.


simpleSubHacker.py
141. for cipherletter in LETTERS:
142. if len(letterMapping[cipherletter]) == 1:
143. # If there's only one letter, add it to the key.
144. keyIndex = LETTERS.find(letterMapping[cipherletter][0])
145. key[keyIndex] = cipherletter


The for loop on line 141 will let us go through each of the letters in LETTERS for the
cipherletter variable, and if the cipherletter is solved (that is,
letterMapping[cipherletter] has only one letter in it) then we can replace an 'x' in
the key with the letter.


So on line 1 44 letterMapping[cipherletter][0] is the decryption letter, and
keyIndex is the index of the decryption letter in LETTERS (which is returned from the
find() call). This index in the key list is set to the decryption letter on line 145.

Free download pdf