Chapter 21 – Hacking the Vigenère Cipher 353
vigenereHacker.py
240. # If none of the key lengths we found using Kasiski Examination
241. # worked, start brute-forcing through key lengths.
242. if hackedMessage == None:
243. if not SILENT_MODE:
244. print('Unable to hack message with likely key length(s).
Brute-forcing key length...')
245. for keyLength in range(1, MAX_KEY_LENGTH + 1):
246. # don't re-check key lengths already tried from Kasiski
247. if keyLength not in allLikelyKeyLengths:
248. if not SILENT_MODE:
249. print('Attempting hack with key length %s (%s possible
keys)...' % (keyLength, NUM_MOST_FREQ_LETTERS ** keyLength))
250. hackedMessage = attemptHackWithKeyLength(ciphertext,
keyLength)
251. if hackedMessage != None:
252. break
If the hack had failed for all the possible key lengths that kasiskiExamination() returned,
hackedMessage will be set to None when the if statement on line 242 executes. In this case,
all the other key lengths up to MAX_KEY_LENGTH are tried. If Kasiski Examination failed to
calculate the correct key length, then we can just brute-force through the key lengths.
Line 245 starts a for loop that will call attemptHackWithKeyLength() for each value of
keyLength (which ranges from 1 to MAX_KEY_LENGTH) as long as it was not in
allLikelyKeyLengths. (This is because the key lengths in allLikelyKeyLengths
have already been tried in the code on lines 233 to 2 38 .)
vigenereHacker.py
253. return hackedMessage
Finally, the value in hackedMessage is returned on line 253.
vigenereHacker.py
256. # If vigenereHacker.py is run (instead of imported as a module) call
257. # the main() function.
258. if name == 'main':
259. main()
Lines 258 and 2 59 call the main() function if this program was run by itself rather than
imported by another program.