Hacking Secret Ciphers with Python

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

Test #17: "WGNRHKIQZMOPBQTCRYPSEPWHLRDXZMJOUTJCLECKEZZRRMQRNI..."
Test #18: "PPVTELDHJRZFPBNMJRLAZWRXRQVKHUUMRPNFKXJCUKFOXAGEHM..."
Test #19: "UXUIGAYKGLYUQTFBWQUTFNSOPEGMIWMQYEZAVCALGOHUXJZPTY..."
Test #20: "JSYTDGLVLBCVVSITPTQPHBCYIZHKFOFMBWOZNFKCADHDKPJSJA..."
Transposition cipher test passed.


Our testing program works by importing the transpositionEncrypt.py and transpositionDecrypt.py
programs as modules. This way, we can call the encryptMessage() and
decryptMessage() functions in these programs. Our testing program will create a random
message and choose a random key. It doesn’t matter that the message is just random letters, we
just need to check that encrypting and then decrypting the message will result in the original
message.


Our program will repeat this test twenty times by putting this code in a loop. If at any point the
returned string from transpositionDecrypt() is not the exact same as the original
message, our program will print an error message and exit.


How the Program Works..........................................................................................................................................


transpositionTest.py



  1. Transposition Cipher Test




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





  3. import random, sys, transpositionEncrypt, transpositionDecrypt



  4. def main():


First our program imports two modules that come with Python, random and sys. We also want
to import the transposition cipher programs we’ve written: transpositionEncrypt.py and
transpositionDecrypt.py. Note that we don’t put the .py extension in our import statement.


Pseudorandom Numbers and the random.seed() Function


transpositionTest.py


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


Technically, the numbers produced by Python’s random.randint() function are not really
random. They are produced from a pseudorandom number generator algorithm, and this
algorithm is well known and the numbers it produces are predictable. We call these random-
looking (but predictable) numbers pseudorandom numbers because they are not truly random.

Free download pdf