Hacking Secret Ciphers with Python

(Ann) #1

344 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


After this for loop completes, the allLikelyKeyLengths variable contains all the factor
integers that were in factorsByCount. This list is returned from
kasiskiExamination().


vigenereHacker.py
137. def getNthSubkeysLetters(n, keyLength, message):
138. # Returns every Nth letter for each keyLength set of letters in text.
139. # E.g. getNthSubkeysLetters(1, 3, 'ABCABCABC') returns 'AAA'
140. # getNthSubkeysLetters(2, 3, 'ABCABCABC') returns 'BBB'
141. # getNthSubkeysLetters(3, 3, 'ABCABCABC') returns 'CCC'
142. # getNthSubkeysLetters(1, 5, 'ABCDEFGHI') returns 'AF'
143.
144. # Use a regular expression to remove non-letters from the message.
145. message = NONLETTERS_PATTERN.sub('', message)


In order to pull out the letters from a ciphertext that were encrypted with the same subkey, we
need a function that can create a string for the 1st, 2nd, or “N^ th” subkey’s letters from a message.
The first part of getting these letters is to remove the non-letter characters from message using a
regular expression object and its sub() method on line 145. (Regular expressions were first
discussed in Chapter 18’s “A Brief Intro to Regular Expressions and the sub() Regex Method”.)
This letters-only string is stored as the new value in message.


vigenereHacker.py
147. i = n - 1
148. letters = []
149. while i < len(message):
150. letters.append(message[i])
151. i += keyLength
152. return ''.join(letters)


Next we will build up a string by appending the letter strings to a list and using the join() list
method to create the final string value. This approach executes much faster than string
concatenation with the + operator. (This approach was first discussed in Chapter 18’s “Building
Strings in Python with Lists” section.)


The i variable will point to the index of the letter in message that we want to append to our
string-building list. This list is stored in a variable named letters. The i variable starts with
the value n - 1 on line 147 and the letters variable starts with a blank list on line 148.


The while loop on line 149 keeps looping while i is less than the length of message. On each
iteration the letter at message[i] is appended to the list in letters. Then i is updated to
point to the next of the subkey’s letters by adding keyLength to i on line 151.

Free download pdf