Hacking Secret Ciphers with Python

(Ann) #1
Chapter 18 – Hacking the Simple Substitution Cipher 265


  1. def hackSimpleSub(message):

  2. intersectedMap = getBlankCipherletterMapping()

  3. cipherwordList = nonLettersOrSpacePattern.sub('',
    message.upper()).split()

  4. for cipherword in cipherwordList:


  5. Get a new cipherletter mapping for each ciphertext word.



  6. newMap = getBlankCipherletterMapping()



  7. wordPattern = makeWordPatterns.getWordPattern(cipherword)

  8. if wordPattern not in wordPatterns.allPatterns:

  9. continue # This word was not in our dictionary, so continue.




  10. Add the letters of each candidate to the mapping.



  11. for candidate in wordPatterns.allPatterns[wordPattern]:

  12. newMap = addLettersToMapping(newMap, cipherword, candidate)




  13. Intersect the new mapping with the existing intersected mapping.



  14. intersectedMap = intersectMappings(intersectedMap, newMap)




  15. Remove any solved letters from the other lists.



  16. return removeSolvedLettersFromMapping(intersectedMap)





  17. def decryptWithCipherletterMapping(ciphertext, letterMapping):


  18. Return a string of the ciphertext decrypted with the letter mapping,




  19. with any ambiguous decrypted letters replaced with an _ underscore.






  20. First create a simple sub key from the letterMapping mapping.



  21. key = ['x'] * len(LETTERS)

  22. for cipherletter in LETTERS:

  23. if len(letterMapping[cipherletter]) == 1:


  24. If there's only one letter, add it to the key.



  25. keyIndex = LETTERS.find(letterMapping[cipherletter][0])

  26. key[keyIndex] = cipherletter

  27. else:

  28. ciphertext = ciphertext.replace(cipherletter.lower(), '_')

  29. ciphertext = ciphertext.replace(cipherletter.upper(), '_')

  30. key = ''.join(key)




  31. With the key we've created, decrypt the ciphertext.



  32. return simpleSubCipher.decryptMessage(key, ciphertext)





  33. if name == 'main':

  34. main()

Free download pdf