Hacking Secret Ciphers with Python

(Ann) #1

220 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


Finally, Key A must be relatively prime with the symbol set size. This means that the greatest
common divisor of keyA and len(SYMBOLS) must be equal to 1. Line 37’s if statement
checks for this and exits the program if they are not relatively prime.


If all of the conditions in the checkKeys() function were False, there is nothing wrong with
the key and the program will not exit. Line 38 is the last line in the function, so the program
execution next returns to the line that originally called checkKeys().


The Affine Cipher Encryption Function


affineCipher.py


  1. def encryptMessage(key, message):

  2. keyA, keyB = getKeyParts(key)

  3. checkKeys(keyA, keyB, 'encrypt')


First we get the integer values for Key A and Key B from the getKeyParts() function. These
values are checked if they are valid keys or not by passing them to the checkKeys() function.
If the checkKeys() function does not cause the program to exit, then the rest of the code in the
encryptMessage() function after line 43 can assume that the keys are valid.


affineCipher.py


  1. ciphertext = ''

  2. for symbol in message:


The ciphertext variable will eventually hold the encrypted string, but starts off as a blank
string. The for loop that begins on line 45 will iterate through each of the characters in
message, and then add the encrypted character to ciphertext. By the time the for loop is
done looping, the ciphertext variable will have the complete string of the encrypted message.


affineCipher.py


  1. if symbol in SYMBOLS:


  2. encrypt this symbol



  3. symIndex = SYMBOLS.find(symbol)

  4. ciphertext += SYMBOLS[(symIndex * keyA + keyB) % len(SYMBOLS)]

  5. else:

  6. ciphertext += symbol # just append this symbol unencrypted


On each iteration of the loop, the symbol variable is assigned the single character from
message. If this character exists in SYMBOLS (that is, our symbol set), then the index in
SYMBOLS is found and assigned to symIndex. The value in symIndex is the “number”
version of the character.

Free download pdf