Chapter 17 – The Simple Substitution Cipher 237
Source Code of the Simple Substitution Cipher
Open a new file editor window by clicking on File ► New Window. Type in the following code
into the file editor, and then save it as simpleSubCipher.py. Press F5 to run the program. Note that
first you will need to download the pyperclip.py module and place this file in the same directory
as the simpleSubCipher.py file. You can download this file from http://invpy.com/pyperclip.py.
Source code for simpleSubCipher.py
Simple Substitution Cipher
http://inventwithpython.com/hacking (BSD Licensed)
- import pyperclip, sys, random
- LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
- def main():
- 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' - myKey = 'LFWOAYUISVKMNXPBDCRJTQEGHZ'
- myMode = 'encrypt' # set to 'encrypt' or 'decrypt'
- checkValidKey(myKey)
- if myMode == 'encrypt':
- translated = encryptMessage(myKey, myMessage)
- elif myMode == 'decrypt':
- translated = decryptMessage(myKey, myMessage)
- print('Using key %s' % (myKey))
- print('The %sed message is:' % (myMode))
- print(translated)
- pyperclip.copy(translated)
- print()
- print('This message has been copied to the clipboard.')
- def checkValidKey(key):
- keyList = list(key)
- lettersList = list(LETTERS)
- keyList.sort()
- lettersList.sort()