Hacking Secret Ciphers with Python

(Ann) #1
Chapter 8 – The Transposition Cipher, Encrypting 121

This if statement on line 44 ends up actually being one of the first lines of code executed when
we press F5 to run our transposition cipher encryption program (after the import statement on
line 4 and the def statements on lines 6 and 21).


The reason we set up our code this way is although Python sets name to 'main'
when the program is run, it sets it to the string 'transpositionEncrypt' if our program is
imported by a different Python program. This is how our program can know if it is being run as a
program or imported by a different program as a module.


Just like how our program imports the pyperclip module to call the functions in it, other
programs might want to import transpositionEncrypt.py to call its encryptMessage()
function. When an import statement is executed, Python will look for a file for the module by
adding “.py” to the end of the name. (This is why import pyperclip will import the
pyperclip.py file.)


When a Python program is imported, the name variable is set to the filename part before
“.py” and then runs the program. When our transpositionEncrypt.py program is imported, we
want all the def statements to be run (to define the encryptMessage() function that the
importing program wants to use), but we don’t want it to call the main() function because that
will execute the encryption code for 'Common sense is not so common.' with key 8.


That is why we put that part of the code inside a function (which by convention is named
main()) and then add code at the end of the program to call main(). If we do this, then our
program can both be run as a program on its own and also imported as a module by
another program.


Key Size and Message Length


Notice what happens when the message length is less than twice the key size:


C o m m o n (s) s e n s e (s) i s (s) n o t (s) s o (s) c o
m m o n.


When using a key of 25, the “Common sense is not so common.” message encrypts to
“Cmommomno.n sense is not so co”. Part of the message isn’t encrypted! This happens whenever
key size becomes more than twice the message length, because that causes there to only be one
character per column and no characters get scrambled for that part of the message.


Because of this, the transposition cipher’s key is limited to half the length of the message it is
used to encrypt. The longer a message is, the more possible keys that can be used to encrypt it.

Free download pdf