Hacking Secret Ciphers with Python

(Ann) #1
Chapter 21 – Hacking the Vigenère Cipher 337

vigenereHacker.py
46. # Found a repeated sequence.
47. if seq not in seqSpacings:
48. seqSpacings[seq] = [] # initialize blank list
49.
50. # Append the spacing distance between the repeated
51. # sequence and the original sequence.
52. seqSpacings[seq].append(i - seqStart)


The spacing between the sequence we’ve found at message[i:i + seqLen] and the
original sequence at message[seqStart:seqStart+seqLen] is simply i -
seqStart. Notice that i and seqStart are the beginning indexes before the colons. So the
integer that i - seqStart evaluates to is the spacing between the two sequences, which is
appended to the list stored at seqSpacings[seq].


(Lines 4 7 and 4 8 guarantee there is a list at this key by checking beforehand if seq exists as a
key in seqSpacings. If it does not, then seqSpacings[seq] is set as a key with a blank
list as its value.)


vigenereHacker.py
53. return seqSpacings


By the time all these for loops have finished, the seqSpacings dictionary will contain every
repeated sequence of length 3, 4, and 5 and their spacings. This dictionary is returned from
findRepeatSequencesSpacings() on line 5 3.


Calculating Factors


vigenereHacker.py
56. def getUsefulFactors(num):
57. # Returns a list of useful factors of num. By "useful" we mean factors
58. # less than MAX_KEY_LENGTH + 1. For example, getUsefulFactors(144)
59. # returns [2, 72, 3, 48, 4, 36, 6, 24, 8, 18, 9, 16, 12]
60.
61. if num < 2:
62. return [] # numbers less than 2 have no useful factors
63.
64. factors = [] # the list of factors found


The only useful factors for the hacking program’s Kasiski Examination code are of length
MAX_KEY_LENGTH and under, not including 1. The getUsefulFactors() takes a num

Free download pdf