Hacking Secret Ciphers with Python

(Ann) #1

150 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


Line 20 uses string interpolation. The value that i+1 evaluates to will replace the first %s in the
string and the value that message[:50] evaluates to will replace the second %s. When using
string interpolation, be sure the number of %s in the string matches the number of values that are
in between the parentheses after it.


transpositionTest.py



  1. Check all possible keys for each message.



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


While the key for the Caesar cipher could be an integer from 0 to 25 , the key for the
transposition cipher can be between 1 and the length of the message. We want to test every
possible key for the test message, so the for loop on line 23 will run the test code with the keys
1 up to (but not including) the length of the message.


transpositionTest.py


  1. encrypted = transpositionEncrypt.encryptMessage(key, message)

  2. decrypted = transpositionDecrypt.decryptMessage(key, encrypted)


Line 24 encrypts the string in message using our encryptMessage() function. Since this
function is inside the transpositionEncrypt.py file, we need to add transpositionEncrypt.
(with the period at the end) to the front of the function name.


The encrypted string that is returned from encryptMessage() is then passed to
decryptMessage(). We use the same key for both function calls. The return value from
decryptMessage() is stored in a variable named decrypted. If the functions worked, then
the string in message should be the exact same as the string in decrypted.


The sys.exit() Function


transpositionTest.py



  1. If the decryption doesn't match the original message, display




  2. an error message and quit.



  3. if message != decrypted:

  4. print('Mismatch with key %s and message %s.' % (key,
    message))

  5. print(decrypted)

  6. sys.exit()



  7. print('Transposition cipher test passed.')

Free download pdf