Hacking Secret Ciphers with Python

(Ann) #1

192 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


transpositionHacker.py


  1. else:

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

  3. print(hackedMessage)

  4. pyperclip.copy(hackedMessage)


Otherwise, the text of the decrypted message is printed to the screen on line 17 and also copied to
the clipboard on line 18.


transpositionHacker.py


  1. def hackTransposition(message):

  2. print('Hacking...')




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




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



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


Because there are many keys the program can go through, the program displays a message to the
user telling her that the hacking has started. The print() call on line 26 also tells her that she
can press Ctrl-C (on Windows) or Ctrl-D (on OS X and Linux) to exit the program at any point.
(Pressing these keys will always exit a running Python program.)


transpositionHacker.py



  1. brute-force by looping through every possible key



  2. for key in range(1, len(message)):

  3. print('Trying key #%s...' % (key))


The range of possible keys for the transposition cipher is the integers between 1 and the length of
the message. The for loop on line 29 will run the hacking part of the function with each of these
keys.


To provide feedback to the user, the key that is being tested is printed to the string on line 30,
using string interpolation to place the integer in key inside the 'Trying key #%s...' %
(key) string.


transpositionHacker.py


  1. decryptedText = transpositionDecrypt.decryptMessage(key, message)


Using the decryptMessage() function in the transpositionDecrypt.py program that we’ve
already written, line 32 gets the decrypted output from the current key being tested and stores it in
the decryptedText variable.

Free download pdf