330 http://inventwithpython.com/hacking
Email questions to the author: [email protected]
- i = n - 1
- letters = []
- while i < len(message):
- letters.append(message[i])
- i += keyLength
- return ''.join(letters)
- def attemptHackWithKeyLength(ciphertext, mostLikelyKeyLength):
Determine the most likely letters for each letter in the key.
- ciphertextUp = ciphertext.upper()
allFreqScores is a list of mostLikelyKeyLength number of lists.
These inner lists are the freqScores lists.
- allFreqScores = []
- for nth in range(1, mostLikelyKeyLength + 1):
- nthLetters = getNthSubkeysLetters(nth, mostLikelyKeyLength,
ciphertextUp)
freqScores is a list of tuples like:
[(
, <Eng. Freq. match score>), ... ]
List is sorted by match score. Higher score means better match.
See the englishFreqMatchScore() comments in freqAnalysis.py.
- freqScores = []
- for possibleKey in LETTERS:
- decryptedText = vigenereCipher.decryptMessage(possibleKey,
nthLetters) - keyAndFreqMatchTuple = (possibleKey,
freqAnalysis.englishFreqMatchScore(decryptedText)) - freqScores.append(keyAndFreqMatchTuple)
Sort by match score
- freqScores.sort(key=getItemAtIndexOne, reverse=True)
- allFreqScores.append(freqScores[:NUM_MOST_FREQ_LETTERS])
- if not SILENT_MODE:
- for i in range(len(allFreqScores)):
use i + 1 so the first letter is not called the "0th" letter
- print('Possible letters for letter %s of the key: ' % (i + 1),
end='') - for freqScore in allFreqScores[i]:
- print('%s ' % freqScore[0], end='')
- print() # print a newline
Try every combination of the most likely letters for each position
in the key.