Hacking Secret Ciphers with Python

(Ann) #1
Chapter 20 – Frequency Analysis 317

freqAnalysis.py
78. # Find how many matches for the six least common letters there are.
79. for uncommonLetter in ETAOIN[-6:]:
80. if uncommonLetter in freqOrder[-6:]:
81. matchScore += 1


Lines 79 to 81 are much like lines 75 to 77 , except the last six letters in ETAOIN (V, K, J, X, Q,
and Z) are checked to see if they are in the last six letters in the freqOrder string. If they are,
then matchScore is incremented.


freqAnalysis.py
83. return matchScore


The integer in matchScore is returned on line 83.


The 14 letters in the middle of the frequency ordering are ignored with our frequency match score
calculation. This approach to comparing letter frequencies is pretty simple, but it works well
enough for our hacking program in the next chapter.


Summary


The sort() function is useful for sorting the values in a list. Normally sort() will sort them
in alphabetical or numerical order. But the reverse and key keyword arguments can be used to
sort them in different orders. This chapter also explains how functions themselves can be passed
as values in function calls.


Let’s use the frequency analysis module to hack the Vigenère cipher, a cipher that perplexed
cryptanalysts for hundreds of years!

Free download pdf