Hacking Secret Ciphers with Python

(Ann) #1

272 http://inventwithpython.com/hacking


Email questions to the author: [email protected]




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




The comments at the top of the source code explain what the program is.


Import All the Things


simpleSubHacker.py


  1. import os, re, copy, pprint, pyperclip, simpleSubCipher, makeWordPatterns


Our simple substitution hacking program imports eight different modules, more than any other
program so far. By reusing the code in these modules, our hacking program becomes much
shorter and easier to write.


The re module is a module we haven’t seen before. This is the regular expression module which
lets our code do sophisticated string manipulation. Regular expressions are explained in the next
section.


simpleSubHacker.py


  1. if not os.path.exists('wordPatterns.py'):

  2. makeWordPatterns.main() # create the wordPatterns.py file

  3. import wordPatterns


The simple substitution cipher also needs the wordPatterns module. The .py file for this
module is created when the makeWordPatterns.py program is run. But
makeWordPatterns.py might not have been run before our hacking program has. In this case, our
hacking program checks if this file exists on line 6 and if it doesn’t, the
makeWordPatterns.main() function is called.


Remember, the main() function is the function that is run in our programs when they are run as
programs (rather than just imported with an import statement.) When we imported the
makeWordPatterns module on line 4, the main() function in makeWordPatterns.py was
not run. Since main() is the function that creates the wordPatterns.py file, we will call
makeWordPatterns.main() if wordPatterns.py does not yet exist.


Either way, by the time the program execution reaches line 8, the wordPatterns module will
exist and can be imported.


A Brief Intro to Regular Expressions and the sub() Regex Method


simpleSubHacker.py
1 0. LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

http://inventwithpython.com/hacking (BSD Licensed) - Hacking Secret Ciphers with Python - free download pdf - issuhub">
Free download pdf