Hacking Secret Ciphers with Python

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


  1. if factor <= MAX_KEY_LENGTH:


  2. factorsByCount is a list of tuples: (factor, factorCount)




  3. factorsByCount has a value like: [(3, 497), (2, 487), ...]



  4. factorsByCount.append( (factor, factorCounts[factor]) )




  5. Sort the list by the factor count.



  6. factorsByCount.sort(key=getItemAtIndexOne, reverse=True)



  7. return factorsByCount





  8. def kasiskiExamination(ciphertext):


  9. Find out the sequences of 3 to 5 letters that occur multiple times




  10. in the ciphertext. repeatedSeqSpacings has a value like:




  11. {'EXG': [192], 'NAF': [339, 972, 633], ... }



  12. repeatedSeqSpacings = findRepeatSequencesSpacings(ciphertext)




  13. See getMostCommonFactors() for a description of seqFactors.



  14. seqFactors = {}

  15. for seq in repeatedSeqSpacings:

  16. seqFactors[seq] = []

  17. for spacing in repeatedSeqSpacings[seq]:

  18. seqFactors[seq].extend(getUsefulFactors(spacing))




  19. See getMostCommonFactors() for a description of factorsByCount.



  20. factorsByCount = getMostCommonFactors(seqFactors)




  21. Now we extract the factor counts from factorsByCount and




  22. put them in allLikelyKeyLengths so that they are easier to




  23. use later.



  24. allLikelyKeyLengths = []

  25. for twoIntTuple in factorsByCount:

  26. allLikelyKeyLengths.append(twoIntTuple[0])



  27. return allLikelyKeyLengths





  28. def getNthSubkeysLetters(n, keyLength, message):


  29. Returns every Nth letter for each keyLength set of letters in text.




  30. E.g. getNthSubkeysLetters(1, 3, 'ABCABCABC') returns 'AAA'




  31. getNthSubkeysLetters(2, 3, 'ABCABCABC') returns 'BBB'




  32. getNthSubkeysLetters(3, 3, 'ABCABCABC') returns 'CCC'




  33. getNthSubkeysLetters(1, 5, 'ABCDEFGHI') returns 'AF'






  34. Use a regular expression to remove non-letters from the message.



  35. message = NONLETTERS_PATTERN.sub('', message)

Free download pdf