Hacking Secret Ciphers with Python

(Ann) #1
Chapter 15 – The Affine Cipher 223

The if statement on line 75 checks to make sure that keyA is relatively prime with the size of
the symbol set by calling the gcd() function in the cryptomath module. If it is, then these
two keys are combined into a single key by multiplying keyA by the symbol set size and adding
keyB. (This is the opposite of what the getKeyParts() function does.) This value is returned
from the getRandomKey() function.


If the condition on line 75 was False, then the code loops back to the start of the while loop
on line 73 and picks random numbers for keyA and keyB again. The infinite loop ensures that
the program keeps looping again and again until it finds random numbers that are valid keys.


affineCipher.py



  1. If affineCipher.py is run (instead of imported as a module) call




  2. the main() function.



  3. if name == 'main':

  4. main()


Lines 81 and 82 call the main() function if this program was run by itself, rather than imported
by another program.


The Second Affine Key Problem: How Many Keys Can the Affine Cipher Have?


Key B of the affine cipher is limited to the size of the symbol set (in the case of affineCipher.py,
len(SYMBOLS) is 95 ). But it seems like Key A could be as large as we want it to be (as long as
it is relatively prime to the symbol set size). Therefore the affine cipher should have an infinite
number of keys and therefore cannot be brute-forced.


As it turns out, no. Remember how large keys in the Caesar cipher ended up being the same as
smaller keys due to the “wrap-around” effect. With a symbol set size of 26, the key 27 in the
Caesar cipher would produce the same encrypted text as the key 1. The affine cipher also “wraps
around”.


Since the Key B part of the affine cipher is the same as the Caesar cipher, we know it is limited
from 1 to the size of the symbol set. But to find out if the affine cipher’s Key A is also limited, we
can write a small program to encrypt a message with several different integers for Key A and see
what the ciphertext looks like.


Open a new file editor window and type the following source code. Save this file as
affineKeyTest.py, and then press F5 to run it.

Free download pdf