Skip to content
Newer
Older
100644 40 lines (29 sloc) 1.36 KB
f16b361 @asweigart Initial commit.
authored Aug 19, 2012
1 # Transposition Cipher Test
2 # http://inventwithpython.com/codebreaker (BSD Licensed)
3
4 import transpositionEncrypt, transpositionDecrypt, random, sys
5
91f8abb @asweigart First round of personal fixes. This is an unhelpful log message.
authored Aug 24, 2012
6 def main():
7 random.seed(42) # set the random "seed" to a static value
8
9 for i in range(20): # run 20 tests
10 # Generate random messages to test.
11
12 # The message will have a random length:
13 message = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' * random.randint(4, 40)
14
15 # Convert the message string to a list to shuffle it.
16 message = list(message)
17 random.shuffle(message)
18 message = ''.join(message) # convert list to string
19
20 print('Test #%s: "%s..."' % (i+1, message[:50]))
21
22 # Check all possible keys for each message.
23 for key in range(1, len(message)):
24 encrypted = transpositionEncrypt.encryptMessage(key, message)
25 decrypted = transpositionDecrypt.decryptMessage(key, encrypted)
26
27 # If the decryption doesn't match the original message, display
28 # an error message and quit.
29 if message != decrypted:
30 print('Mismatch with key %s and message %s.' % (key, message))
31 print(decrypted)
32 sys.exit()
33
34 print('Transposition cipher test passed.')
35
36
37 # If transpositionTest.py is run (instead of imported as a module) call
38 # the main() function.
39 if __name__ == '__main__':
40 main()
Something went wrong with that request. Please try again.