Hacking Secret Ciphers with Python

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

Input Validation on the Keys


affineCipher.py


  1. def checkKeys(keyA, keyB, mode):

  2. if keyA == 1 and mode == 'encrypt':

  3. sys.exit('The affine cipher becomes incredibly weak when key A is
    set to 1. Choose a different key.')

  4. if keyB == 0 and mode == 'encrypt':

  5. sys.exit('The affine cipher becomes incredibly weak when key B is
    set to 0. Choose a different key.')


Encrypting with the affine cipher involves a character’s index in SYMBOLS being multiplied by
Key A and added to Key B. But if keyA is 1 , the encrypted text will be very weak because
multiplying the index by 1 does not change it. Similarly, if keyB is 0 , the encrypted text will be
weak because adding the index to 0 does not change it. And if both keyA was 1 and keyB was
0 , the “encrypted” message would be the exact same as the original message. It wouldn’t be
encrypted at all!


The if statements on line 31 and 33 check for these “weak key” conditions, and exit the program
with a message telling the user what was wrong. Notice on lines 32 and 34, a string is being
passed to the sys.exit() call. The sys.exit() function has an optional parameter of a
string that will be printed to the screen before terminating the program. This can be used to
display an error message on the screen before the program quits.


Of course, these checks only apply to prevent you from encrypting with weak keys. If mode is set
to 'decrypt', then the checks on lines 31 and 33 don’t apply.


affineCipher.py


  1. if keyA < 0 or keyB < 0 or keyB > len(SYMBOLS) - 1:

  2. sys.exit('Key A must be greater than 0 and Key B must be between 0
    and %s.' % (len(SYMBOLS) - 1))


The condition on line 35 checks if keyA is a negative number (that is, it is less than 0 ) or if
keyB is greater than 0 or less than the size of the symbol set minus one. (The reason the Key B
check has this range is described later in the “How Many Keys Does the Affine Cipher Have?”
section.) If any of these things are True, the keys are invalid and the program exits.


affineCipher.py


  1. if cryptomath.gcd(keyA, len(SYMBOLS)) != 1:

  2. sys.exit('Key A (%s) and the symbol set size (%s) are not
    relatively prime. Choose a different key.' % (keyA, len(SYMBOLS)))

Free download pdf