Hacking Secret Ciphers with Python

(Ann) #1

280 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


The next part of the code creates a list of cipherletters that have exactly one potential decryption
letter. We will put these cipherletter strings in a list that is in solvedLetters. The
solvedLetters variable starts off as a blank list on line 95.


The for loop on line 96 goes through all 26 possible cipherletters and looks at the cipherletter
mapping’s list of potential decryption letters for that cipherletter. (That is, the list is at
letterMapping[cipherletter].)


If the length of this list is 1 (which is checked on line 97 ), then we know that there is only one
letter that the cipherletter could decrypt to and the cipherletter is solved. We will add the letter
(the potential decryption letter, not the cipherletter) to the solvedLetters list on line 98. The
solved letter will always be at letterMapping[cipherletter][0] because
letterMapping[cipherletter] is a list of potential decryption letters that only has one
string value in it at index 0 of the list.


simpleSubHacker.py
100. # If a letter is solved, than it cannot possibly be a potential
101. # decryption letter for a different ciphertext letter, so we
102. # should remove it from those other lists.
103. for cipherletter in LETTERS:
104. for s in solvedLetters:
105. if len(letterMapping[cipherletter]) != 1 and s in
letterMapping[cipherletter]:
106. letterMapping[cipherletter].remove(s)


After the previous for loop that started on line 96 has finished, the solvedLetters variable
will be a list of all the letters that are solved decryptions of a cipherletter. The for loop on line
103 loops through all 26 possible cipherletters and looks at the cipherletter mapping’s list of
potential decryption letters.


For each cipherletter that is examined, the letters in solvedLetters are looped through on
line 1 04 to check if each of them exist in the list of potential decryption letters for
letterMapping[cipherletter]. Line 1 05 checks if a list of potential decryption letters is
not solved (that is, if len(letterMapping[cipherletter]) != 1) and the solved
letter exists in the list of potential decryption letters. If this condition is True, then the solved
letter in s is removed from the list of potential decryption letters on line 1 06.


simpleSubHacker.py
107. if len(letterMapping[cipherletter]) == 1:
108. # A new letter is now solved, so loop again.
109. loopAgain = True

Free download pdf