Hacking Secret Ciphers with Python

(Ann) #1

242 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


keyList.sort()

...and not look like this:


keyList = keyList.sort()

simpleSubCipher.py
33. if keyList != lettersList:
34. sys.exit('There is an error in the key or symbol set.')


Once sorted, the keyList and lettersList values should be the same, since keyList was
just the characters in LETTERS with the order scrambled. If keyList and lettersList are
equal, we also know that keyList (and, therefore, the key parameter) does not have any
duplicates in it, since LETTERS does not have any duplicates in it.


However, if the condition on line 33 is True, then the value in myKey was set to an invalid
value and the program will exit by calling sys.exit().


Wrapper Functions


simpleSubCipher.py
37. def encryptMessage(key, message):
38. return translateMessage(key, message, 'encrypt')
39.
40.
41. def decryptMessage(key, message):
42. return translateMessage(key, message, 'decrypt')
43.
44.
45. def translateMessage(key, message, mode):


The code for encrypting and the code for decrypting are almost exactly the same. It’s always a
good idea to put code into a function and call it twice rather than type out the code twice. First,
this saves you some typing. But second, if there’s ever a bug in the duplicate code, you only have
to fix the bug in one place instead of multiple places. It is (usually) much more reasonable to
replace duplicate code with a single function that has the code.


Wrapper functions simply wrap the code of another function, and return the value the wrapped
function returns. Often the wrapper function might make a slight change to the arguments or
return value of wrapped function (otherwise you would just call the wrapped function directly.) In
this case, encryptMessage() and decryptMessage() (the wrapper functions) calls

Free download pdf