Hacking Secret Ciphers with Python

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


  1. for indexes in itertools.product(range(NUM_MOST_FREQ_LETTERS),
    repeat=mostLikelyKeyLength):


  2. Create a possible key from the letters in allFreqScores



  3. possibleKey = ''

  4. for i in range(mostLikelyKeyLength):

  5. possibleKey += allFreqScores[i][indexes[i]][0]



  6. if not SILENT_MODE:

  7. print('Attempting with key: %s' % (possibleKey))



  8. decryptedText = vigenereCipher.decryptMessage(possibleKey,
    ciphertextUp)



  9. if detectEnglish.isEnglish(decryptedText):


  10. Set the hacked ciphertext to the original casing.



  11. origCase = []

  12. for i in range(len(ciphertext)):

  13. if ciphertext[i].isupper():

  14. origCase.append(decryptedText[i].upper())

  15. else:

  16. origCase.append(decryptedText[i].lower())

  17. decryptedText = ''.join(origCase)




  18. Check with user to see if the key has been found.



  19. print('Possible encryption hack with key %s:' % (possibleKey))

  20. print(decryptedText[:200]) # only show first 200 characters

  21. print()

  22. print('Enter D for done, or just press Enter to continue
    hacking:')

  23. response = input('> ')



  24. if response.strip().upper().startswith('D'):

  25. return decryptedText




  26. No English-looking decryption found, so return None.



  27. return None





  28. def hackVigenere(ciphertext):


  29. First, we need to do Kasiski Examination to figure out what the




  30. length of the ciphertext's encryption key is.



  31. allLikelyKeyLengths = kasiskiExamination(ciphertext)

  32. if not SILENT_MODE:

  33. keyLengthStr = ''

  34. for keyLength in allLikelyKeyLengths:

  35. keyLengthStr += '%s ' % (keyLength)

Free download pdf