Hacking Secret Ciphers with Python

(Ann) #1

240 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


The first few lines are comments describing the program. Then the pyperclip, sys, and
random modules are imported. Finally, the LETTERS constant variable is set to a string of all
the uppercase letters. The LETTERS string will be our symbol set for the simple substitution
cipher program.


The Program’s main() Function


simpleSubCipher.py


  1. def main():

  2. myMessage = 'If a man is offered a fact which goes against his
    instincts, he will scrutinize it closely, and unless the evidence is
    overwhelming, he will refuse to believe it. If, on the other hand, he is
    offered something which affords a reason for acting in accordance to his
    instincts, he will accept it even on the slightest evidence. The origin of
    myths is explained in this way. -Bertrand Russell'

  3. myKey = 'LFWOAYUISVKMNXPBDCRJTQEGHZ'

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


The main() function is similar to the main() function of cipher programs in the previous
chapters. It contains the variables that store the message, key, and mode that will be used for
the program.


simpleSubCipher.py


  1. checkValidKey(myKey)


The keys for simple substitution ciphers are easy to get wrong. For example, the key might not
have every letter of the alphabet. Or the key may have the same letter twice. The
checkValidKey() function (which is explained later) makes sure the key is usable by the
encryption and decryption functions, and will exit the program with an error message if they are
not.


simpleSubCipher.py


  1. if myMode == 'encrypt':

  2. translated = encryptMessage(myKey, myMessage)

  3. elif myMode == 'decrypt':

  4. translated = decryptMessage(myKey, myMessage)


If the program execution returns from checkValidKey() instead of terminating, we can
assume the key is valid. Lines 16 through 19 check whether the myMode variable is set to
'encrypt' or 'decrypt' and calls either encryptMessage() or
decryptMessage(). The return value of encryptMessage() and decryptMessage()

Free download pdf