Hacking Secret Ciphers with Python

(Ann) #1

330 http://inventwithpython.com/hacking


Email questions to the author: [email protected]





  1. i = n - 1

  2. letters = []

  3. while i < len(message):

  4. letters.append(message[i])

  5. i += keyLength

  6. return ''.join(letters)





  7. def attemptHackWithKeyLength(ciphertext, mostLikelyKeyLength):


  8. Determine the most likely letters for each letter in the key.



  9. ciphertextUp = ciphertext.upper()


  10. allFreqScores is a list of mostLikelyKeyLength number of lists.




  11. These inner lists are the freqScores lists.



  12. allFreqScores = []

  13. for nth in range(1, mostLikelyKeyLength + 1):

  14. nthLetters = getNthSubkeysLetters(nth, mostLikelyKeyLength,
    ciphertextUp)




  15. freqScores is a list of tuples like:




  16. [(, <Eng. Freq. match score>), ... ]




  17. List is sorted by match score. Higher score means better match.




  18. See the englishFreqMatchScore() comments in freqAnalysis.py.



  19. freqScores = []

  20. for possibleKey in LETTERS:

  21. decryptedText = vigenereCipher.decryptMessage(possibleKey,
    nthLetters)

  22. keyAndFreqMatchTuple = (possibleKey,
    freqAnalysis.englishFreqMatchScore(decryptedText))

  23. freqScores.append(keyAndFreqMatchTuple)


  24. Sort by match score



  25. freqScores.sort(key=getItemAtIndexOne, reverse=True)



  26. allFreqScores.append(freqScores[:NUM_MOST_FREQ_LETTERS])



  27. if not SILENT_MODE:

  28. for i in range(len(allFreqScores)):


  29. use i + 1 so the first letter is not called the "0th" letter



  30. print('Possible letters for letter %s of the key: ' % (i + 1),
    end='')

  31. for freqScore in allFreqScores[i]:

  32. print('%s ' % freqScore[0], end='')

  33. print() # print a newline




  34. Try every combination of the most likely letters for each position




  35. in the key.



Free download pdf