Chapter 16 – Hacking the Affine Cipher 229
- SILENT_MODE = False
Our affine cipher hacking program fits in 60 lines of code because we’ve already written much of
the code it uses.
When you run the hacker program, you can see that this program produces a lot of output as it
works its way through all the possible decryptions. However, printing out this input does slow
down the program. If you change line 6 to set the SILENT_MODE variable to True, the program
will be silenced and not print out all these messages. This will speed up the program immensely.
But showing all that text while your hacking program runs makes it look cool. (And if you want
your programs to look cool by printing out text slowly one character at a time for a “typewriter”
effect, check out the typewriter.py module at http://invpy.com/typewriter.py.))
affineHacker.py
- def main():
You might want to copy & paste this text from the source code at
http://invpy.com/affineHacker.py
- 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"""
- hackedMessage = hackAffine(myMessage)
- if hackedMessage != None:
The plaintext is displayed on the screen. For the convenience of
the user, we copy the text of the code to the clipboard.
- print('Copying hacked message to clipboard:')
- print(hackedMessage)
- pyperclip.copy(hackedMessage)
- else:
- print('Failed to hack encryption.')
The ciphertext to be hacked is stored as a string in myMessage, and this string is passed to the
hackAffine() function (described next). The return value from this call is either a string of
the original message (if the ciphertext was hacked) or the None value (if the hacking failed).
The code on lines 15 to 22 will check if hackedMessage was set to None or not. If
hackedMessage is not equal to None, then the message will be printed to the screen on line
19 and copied to the clipboard on line 20. Otherwise, the program will simply print that it was
unable to hack the message.