Hacking Secret Ciphers with Python

(Ann) #1

352 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


Otherwise, after the for loop on line 188 iterates through all of the possible indexes to use and
none of the decryptions look like English, the hacking has failed and the None value is returned.


vigenereHacker.py
223. def hackVigenere(ciphertext):
224. # First, we need to do Kasiski Examination to figure out what the
225. # length of the ciphertext's encryption key is.
226. allLikelyKeyLengths = kasiskiExamination(ciphertext)


Now we define the hackVigenere() function, which calls all of the previous functions.
We’ve already defined all the work it will do. Let’s run through the steps it goes through to
perform the hacking. The first step is to get the most likely lengths of the Vigenère key based on
Kasiski Examination of ciphertext.


vigenereHacker.py
227. if not SILENT_MODE:
228. keyLengthStr = ''
229. for keyLength in allLikelyKeyLengths:
230. keyLengthStr += '%s ' % (keyLength)
231. print('Kasiski Examination results say the most likely key lengths
are: ' + keyLengthStr + '\n')


The likely key lengths are printed to the screen if SILENT_MODE is False.


The break Statement


Similar to how the continue statement is used inside of a loop to continue back to the start of
the loop, the break statement (which is just the break keyword by itself) is used inside of a
loop to immediately exit the loop. When the program execution “breaks out of a loop”, it
immediately moves to the first line of code after the loop ends.


vigenereHacker.py
233. for keyLength in allLikelyKeyLengths:
234. if not SILENT_MODE:
235. print('Attempting hack with key length %s (%s possible
keys)...' % (keyLength, NUM_MOST_FREQ_LETTERS ** keyLength))
236. hackedMessage = attemptHackWithKeyLength(ciphertext, keyLength)
237. if hackedMessage != None:
238. break


For each possible key length, the code calls the attemptHackWithKeyLength() function
on line 236. If attemptHackWithKeyLength() does not return None, then the hack was
successful and the program execution should break out of the for loop on line 238.

Free download pdf