Hacking Secret Ciphers with Python

(Ann) #1

194 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


The whitespace characters are the space character, the tab character, and the newline
character. Try typing the following into the interactive shell:





'Helloxxxxxx'.strip('x')
'Hello'
'aaaaaHELLOaa'.strip('a')
'HELLO'
'ababaHELLOab'.strip('ab')
'HELLO'
'abccabcbacbXYZabcXYZacccab'.strip('abc')
'XYZabcXYZ'





transpositionHacker.py


  1. if response.strip().upper().startswith('D'):

  2. return decryptedText


The expression on line 43 used for the if statement’s condition lets the user have some
flexibility with what has to be typed in. If the condition were response == 'D', then the user
would have to type in exactly “D” and nothing else in order to end the program.


If the user typed in 'd' or ' D' or 'Done' then the condition would be False and the
program would continue. To avoid this, the string in response has any whitespace removed
from the start or end with the call to strip(). Then the string that response.strip()
evaluates to has the upper() method called on it. If the user typed in either “d” or “D”, the
string returned from upper() will be 'D'. Little things like this make our programs easier for
the user to use.


If the user has indicated that the decrypted string is correct, the decrypted text is returned from
hackTransposition() on line 44.


transpositionHacker.py


  1. return None


Line 46 is the first line after the for loop that began on line 29. If the program execution reaches
this point, it’s because the return statement on line 44 was never reached. That would only
happen if the correctly decrypted text was never found for any of the keys that were tried.


In that case, line 46 returns the None value to indicate that the hacking has failed.


transpositionHacker.py


  1. if name == 'main':

Free download pdf