Hacking Secret Ciphers with Python

(Ann) #1

316 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


'A', 'N', 'O', 'R', 'S', 'H', 'C', 'L', 'MD', 'G', 'FU', 'P', 'BW', 'Y',


'V', 'K', 'X', 'QJ', 'Z']


freqAnalysis.py
62. return ''.join(freqOrder)


Line 6 2 creates a string from the list of strings in freqOrder by joining them together with the
join() method. If we continue using the previous example, getFrequencyOrder() will
return the string 'ETIANORSHCLMDGFUPBWYVKXQJZ'. According to this ordering, E is the
most frequent letter in the “Alan Mathison Turing...” example string, T is the second most
frequent letter, I is the third most frequent, and so on.


The Program’s englishFreqMatchScore() Function


freqAnalysis.py
65. def englishFreqMatchScore(message):
66. # Return the number of matches that the string in the message
67. # parameter has when its letter frequency is compared to English
68. # letter frequency. A "match" is how many of its six most frequent
69. # and six least frequent letters is among the six most frequent and
70. # six least frequent letters for English.
71. freqOrder = getFrequencyOrder(message)


The englishFreqMatchScore() function takes a string for message, and then returns an
integer between 0 and 12 to show message’s frequency match score with readable English’s
letter frequency. The higher the integer, the more that the frequency of the letters in message
matches the frequency of normal English text.


The first step in calculating the match score is to get the letter frequency ordering of message
by calling the getFrequencyOrder() function.


freqAnalysis.py
73. matchScore = 0
74. # Find how many matches for the six most common letters there are.
75. for commonLetter in ETAOIN[:6]:
76. if commonLetter in freqOrder[:6]:
77. matchScore += 1


The matchScore variable starts off at 0 on line 73. The for loop on line 75 goes through each
of the first 6 letters of the ETAOIN string. Remember that the [:6] slice is the same thing as
[0:6]. If one of these E, T, A, O, I, or N letters is in the first six letters in the freqOrder
string, then line 76’s condition is True and line 77 will increment matchScore.

Free download pdf