Hacking Secret Ciphers with Python

(Ann) #1
Chapter 16 – Hacking the Affine Cipher 227


  1. def main():


  2. You might want to copy & paste this text from the source code at




  3. http://invpy.com/affineHacker.py



  4. myMessage = """U&'<3dJ^Gjx'-3^MS'Sj0jxuj'G3'%j'<mMMjS'g{GjMMg9j{G'g"'gG
    '<3^MS'Sj<jguj'm'P^dm{'g{G3'%jMgjug{9'GPmG'gG'-m0'P^dm{LU'5&Mm{'_^xg{9"""



  5. hackedMessage = hackAffine(myMessage)



  6. if hackedMessage != None:


  7. The plaintext is displayed on the screen. For the convenience of




  8. the user, we copy the text of the code to the clipboard.



  9. print('Copying hacked message to clipboard:')

  10. print(hackedMessage)

  11. pyperclip.copy(hackedMessage)

  12. else:

  13. print('Failed to hack encryption.')





  14. def hackAffine(message):

  15. print('Hacking...')




  16. Python programs can be stopped at any time by pressing Ctrl-C (on




  17. Windows) or Ctrl-D (on Mac and Linux)



  18. print('(Press Ctrl-C or Ctrl-D to quit at any time.)')




  19. brute-force by looping through every possible key



  20. for key in range(len(affineCipher.SYMBOLS) ** 2):

  21. keyA = affineCipher.getKeyParts(key)[0]

  22. if cryptomath.gcd(keyA, len(affineCipher.SYMBOLS)) != 1:

  23. continue



  24. decryptedText = affineCipher.decryptMessage(key, message)

  25. if not SILENT_MODE:

  26. print('Tried Key %s... (%s)' % (key, decryptedText[:40]))



  27. if detectEnglish.isEnglish(decryptedText):


  28. Check with the user if the decrypted key has been found.



  29. print()

  30. print('Possible encryption hack:')

  31. print('Key: %s' % (key))

  32. print('Decrypted message: ' + decryptedText[:200])

  33. print()

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

  35. response = input('> ')



Free download pdf