262 http://inventwithpython.com/hacking
Email questions to the author: [email protected]
Lines 5 1 and 5 2 call the main() function if this program was run by itself (to create the
wordPattern.py file) rather than imported by another program that wants to use its
getWordPattern() function.
Hacking the Simple Substitution Cipher
The hacking program uses the abstract concepts of “word patterns” and “cipherletter mappings”.
But don’t worry, in our Python program “word patterns” are represented by string values and
“cipherletter mappings” are represented with dictionary values. The previous sections explained
what word patterns are and how to generate them from a string. Cipherletter mappings are used in
the hacking program to keep track of the possible letters that each of the 26 cipherletters could
decrypt to. Go ahead and type in the source code for the simpleSubHacker.py program.
Source Code of the Simple Substitution Hacking Program......................................................................................
Source code for simpleSubHacker.py
Simple Substitution Cipher Hacker
http://inventwithpython.com/hacking (BSD Licensed)
- import os, re, copy, pprint, pyperclip, simpleSubCipher, makeWordPatterns
- if not os.path.exists('wordPatterns.py'):
- makeWordPatterns.main() # create the wordPatterns.py file
- import wordPatterns
1 0. LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
1 1. nonLettersOrSpacePattern = re.compile('[^A-Z\s]')
1 2.
1 3. def main():
1 4. message = 'Sy l nlx sr pyyacao l ylwj eiswi upar lulsxrj isr
sxrjsxwjr, ia esmm rwctjsxsza sj wmpramh, lxo txmarr jia aqsoaxwa sr
pqaceiamnsxu, ia esmm caytra jp famsaqa sj. Sy, px jia pjiac ilxo, ia sr
pyyacao rpnajisxu eiswi lyypcor l calrpx ypc lwjsxu sx lwwpcolxwa jp isr
sxrjsxwjr, ia esmm lwwabj sj aqax px jia rmsuijarj aqsoaxwa. Jia pcsusx py
nhjir sr agbmlsxao sx jisr elh. -Facjclxo Ctrramm'
1 5.
1 6. # Determine the possible valid ciphertext translations.
1 7. print('Hacking...')
1 8. letterMapping = hackSimpleSub(message)
1 9.
2 0. # Display the results to the user.
2 1. print('Mapping:')
2 2. pprint.pprint(letterMapping)
2 3. print()
2 4. print('Original ciphertext:')