Hacking Secret Ciphers with Python

(Ann) #1
Chapter 10 – Programming a Program to Test Our Program 139

You won’t know unless you test the encryptMessage() and decryptMessage()
functions with different values for the message and key parameters. This would take a lot of
time. You’ll have to type out a message in the encryption program, set the key, run the encryption
program, paste the ciphertext into the decryption program, set the key, and then run the
decryption program. And you’ll want to repeat that with several different keys and messages!


That’s a lot of boring work. Instead we can write a program to test the cipher programs for us.
This new program can generate a random message and a random key. It will then encrypt the
message with the encryptMessage() function from transpositionEncrypt.py and then pass
the ciphertext from that to the decryptMessage() in transpositionDecrypt.py. If the plaintext
returned by decryptMessage() is the same as the original message, the program can know


that the encryption and decryption messages work. This is called automated testing.


There are several different message and key combinations to try, but it will only take the
computer a minute or so to test thousands different combinations. If all of those tests pass, then
we can be much more certain that our code works.


Source Code of the Transposition Cipher Tester Program


Open a new file editor window by clicking on File ► New Window. Type in the following code
into the file editor, and then save it as transpositionTest.py. Press F5 to run the program. Note
that first you will need to download the pyperclip.py module and place this file in the same
directory as the transpositionTest.py file. You can download this file from
http://invpy.com/pyperclip.py.


Source code for transpositionTest.py




  1. Transposition Cipher Test




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





  3. import random, sys, transpositionEncrypt, transpositionDecrypt



  4. def main():

  5. random.seed(42) # set the random "seed" to a static value



  6. for i in range(20): # run 20 tests


  7. Generate random messages to test.






  8. The message will have a random length:



  9. message = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' * random.randint(4, 40)




  10. Convert the message string to a list to shuffle it.



  11. message = list(message)

  12. random.shuffle(message)

Free download pdf