Hacking Secret Ciphers with Python

(Ann) #1

230 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


The Affine Cipher Hacking Function


affineHacker.py


  1. def hackAffine(message):

  2. print('Hacking...')




  3. Python programs can be stopped at any time by pressing Ctrl-C (on




  4. Windows) or Ctrl-D (on Mac and Linux)



  5. 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
4
2
16
24
16
123
10
792594609605189126649





affineHacker.py



  1. brute-force by looping through every possible key



  2. for key in range(len(affineCipher.SYMBOLS) ** 2):

  3. 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
Free download pdf