Hacking Secret Ciphers with Python

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

The message is then decrypted with the key by calling decryptMessage(). If
SILENT_MODE is False the “Tried Key” message will be printed on the screen. If
SILENT_MODE was set to True, the print() call on line 40 will be skipped.


affineHacker.py


  1. if detectEnglish.isEnglish(decryptedText):


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



  3. print()

  4. print('Possible encryption hack:')

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

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

  7. print()


Next, we use the isEnglish() function from our detectEnglish module to check if the
decrypted message is recognized as English. If the wrong decryption key was used, then the
decrypted message will look like random characters and isEnglish() will return False.


But if the decrypted message is recognized as readable English (by the isEnglish() function
anyway), then we will display this to the user.


affineHacker.py


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

  2. response = input('> ')



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

  4. return decryptedText


The program might not have found the correct key, but rather a key that produces gibberish that
the isEnglish() function mistakenly thinks is English. To prevent false positives, the
decrypted text is printed on the screen for the user to read. If the user decides that this is the
correct decryption, she can type in D and press Enter. Otherwise, she can just press Enter (which
returns a blank string from the input() call) and the hackAffine() function will continue
trying more keys.


affineHacker.py


  1. return None


From the indentation of line 54, you can see that this is line is executed after the for loop on line
33 has completed. If this loop has finished, then it has gone through every possible decryption

Free download pdf