Hacking Secret Ciphers with Python

(Ann) #1

128 http://inventwithpython.com/hacking


Email questions to the author: [email protected]



  1. plaintext = decryptMessage(myKey, myMessage)




  2. Print with a | (called "pipe" character) after it in case




  3. there are spaces at the end of the decrypted message.



  4. print(plaintext + '|')



  5. pyperclip.copy(plaintext)


The first part of the program is very similar to the first part of transpositionEncrypt.py. The
pyperclip module is imported along with a different module named math. If you separate the
module names with commas, you can import multiple modules with one import statement.


The main() function creates variables named myMessage and myKey, and then calls the
decryption function decryptMessage(). The return value of this function is the decrypted
plaintext of the ciphertext and key that we passed it. This is stored in a variable named
plaintext, which is then printed to the screen (with a pipe character at the end in case there
are spaces at the end of the message) and copied to the clipboard.


transpositionDecrypt.py


  1. def decryptMessage(key, message):


Look at the six steps to decrypting from earlier in this chapter. For example, if we are decrypting
“Cenoonommstmme oo snnio. s s c” (which has 30 characters) with the key 8, then the final set of
boxes will look like this:


C e n o
o n o m
m s t m
m e (s) o
o (s) s n
n i o.
(s) s (s)
s (s) c

The decryptMessage() function implements each of the decryption steps as Python code.


The math.ceil(), math.floor() and round() Functions


When you divide numbers using the / operator, the expression returns a floating point number
(that is, a number with a decimal point). This happens even if the number divides evenly. For
example, 21 / 7 will evaluate to 3.0, not 3.

Free download pdf