Hacking Secret Ciphers with Python

(Ann) #1
Chapter 5 – The Reverse Cipher 55

But the code for the reverse cipher program is easy to explain, so we’ll use it as our first
encryption program.


Source Code of the Reverse Cipher Program


In IDLE, click on File ► New Window to create a new file editor window. Type in the following
code, save it as reverseCipher.py, and press F5 to run it: (Remember, don’t type in the line
numbers at the beginning of each line.)


Source code for reverseCipher.py




  1. Reverse Cipher




  2. http://inventwithpython.com/hacking (BSD Licensed)





  3. message = 'Three can keep a secret, if two of them are dead.'

  4. translated = ''



  5. i = len(message) - 1

  6. while i >= 0:

  7. translated = translated + message[i]

  8. i = i - 1



  9. print(translated)


Sample Run of the Reverse Cipher Program


When you run this program the output will look like this:


.daed era meht fo owt fi ,terces a peek nac eerhT


To decrypt this message, copy the “.daed era meht fo owt fi ,terces a peek nac eerhT” text to the
clipboard (see http://invpy.com/copypaste for instructions on how to copy and paste text) and
paste it as the string value stored in message on line 4. Be sure to have the single quotes at the
beginning and end of the string. The new line 4 will look like this (with the change in bold):


reverseCipher.py


  1. message = '.daed era meht fo owt fi ,terces a peek nac eerhT'


Now when you run the reverseCipher.py program, the output will decrypt to the original
message:


Three can keep a secret, if two of them are dead.

Free download pdf