Hacking Secret Ciphers with Python

(Ann) #1
Chapter 18 – Hacking the Simple Substitution Cipher 273

1 1. nonLettersOrSpacePattern = re.compile('[^A-Z\s]')


The simple substitution hacking program will have a LETTERS global variable like many of our
previous cipher programs.


The re.compile() function is new. This function compiles (that is, creates) a new regular
expression pattern object, or “regex object” or “pattern object” for short. Regular expressions are
strings that define a specific pattern that matches certain strings. Regular expressions can do
many special things with strings that are beyond the scope of this book, but you can learn about
them at http://invpy.com/regex.


The string '[^A-Za-z\s]' is a regular expression that matches any character that is not a
letter from A to Z or a “whitespace” character (e.g. a space, tab, or newline character). The
pattern object has a sub() method (short for “substitute”) that works very similar to the
replace() string method. The first argument to sub() is the string that replaces any instances
of the pattern in the second string argument. Try typing the following into the interactive shell:





pat = re.compile('[^A-Z\s]')
pat.sub('abc', 'ALL! NON!LETTERS? AND123 NONSPACES. REPLACED')
'ALLabc NONabcLETTERSabc ANDabcabcabc NONSPACESabc REPLACED'
pat.sub('', 'ALL! NON!LETTERS? AND 123 NONSPACES. REPLACED')
'ALL NONLETTERS AND NONSPACES REPLACED'





There are many sophisticated string manipulations you can perform if you learn more about
regular expressions, but we will only use them in this book to remove characters from a string
that are not uppercase letters or spaces.


The Hacking Program’s main() Function


simpleSubHacker.py
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)

Free download pdf