Hacking Secret Ciphers with Python

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

 The sys module is imported for the exit() function.
 The pyperclip module is imported for the copy() clipboard function.
 The cryptomath module that we created in the last chapter is imported for the gcd()
and findModInverse() function.

In our program, the string stored in the SYMBOLS variable is the symbol set. The symbol set is
the list of all characters that can be encrypted. Any characters in the message to be encrypted that
don’t appear in SYMBOLS will be added to the ciphertext unencrypted.


affineCipher.py


  1. def main():

  2. myMessage = """"A computer would deserve to be called intelligent if it
    could deceive a human into believing that it was human." -Alan Turing"""

  3. myKey = 2023

  4. myMode = 'encrypt' # set to 'encrypt' or 'decrypt'


The main() function is almost exactly the same as the one from the transposition cipher
programs. The message, key, and mode are stored in variables on lines 9, 10, and 11.


affineCipher.py


  1. if myMode == 'encrypt':

  2. translated = encryptMessage(myKey, myMessage)

  3. elif myMode == 'decrypt':

  4. translated = decryptMessage(myKey, myMessage)


If myMode is set to 'encrypt', then line 14 will be executed and the return value of
encryptMessage() is stored in translated. Or else, if myMode is set to 'decrypt',
then decryptMessage() is called on line 16 and the return value is stored in translated.


Either way, after the execution has passed line 16, the translated variable will have the
encrypted or decrypted version of the message in myMessage.


affineCipher.py


  1. print('Key: %s' % (myKey))

  2. print('%sed text:' % (myMode.title()))
    1 9. print(translated)

  3. pyperclip.copy(translated)

  4. print('Full %sed text copied to clipboard.' % (myMode))


The string in translated (which is the encrypted or decrypted version of the string in
myMessage) is displayed on the screen on line 19 and copied to the clipboard on line 20.

Free download pdf