230 http://inventwithpython.com/hacking
Email questions to the author: [email protected]
The Affine Cipher Hacking Function
affineHacker.py
- def hackAffine(message):
- print('Hacking...')
Python programs can be stopped at any time by pressing Ctrl-C (on
Windows) or Ctrl-D (on Mac and Linux)
- print('(Press Ctrl-C or Ctrl-D to quit at any time.)')
The hackAffine() function has the code that does the decryption. This can take a while, so if
the user wants to exit the program early, she can press Ctrl-C (on Windows) or Ctrl-D (on OS X
and Linux).
The ** Exponent Operator
There is another math operator besides the basic +, -, *, /, and // operators. The ** operator is
Python’s exponent operator. This does “to the power of” math on two numbers. For example,
“two to the power of five” would be 2 5 in Python code. This is equivalent to two
multiplied by itself five times: 2 2 2 2 2. Both the expressions 2 5 and 2
2 2 2 2 evaluate to the integer 32.
Try typing the following into the interactive shell:
2 6
64
42
16
24
16
12310
792594609605189126649
affineHacker.py
brute-force by looping through every possible key
- for key in range(len(affineCipher.SYMBOLS) ** 2):
- keyA = affineCipher.getKeyParts(key)[0]
The range of integers for the keys used to brute-force the ciphertext will range from 0 to the size
of the symbol set to the second power. The expression:
len(affineCipher.SYMBOLS) ** 2