Hacking Secret Ciphers with Python

(Ann) #1

154 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


Patrick Ball

Up until now our programs have only worked on small messages that we type directly into the
source code as string values. The cipher program in this chapter will use the transposition cipher
to encrypt and decrypt entire files, which can be millions of characters in size.


Plain Text Files


This program will encrypt and decrypt plain text files. These are the kind of files that only have
text data and usually have the .txt file extension. Files from word processing programs that let
you change the font, color, or size of the text do not produce plain text files. You can write your
own text files using Notepad (on Windows), TextMate or TextEdit (on OS X), or gedit (on Linux)
or a similar plain text editor program. You can even use IDLE’s own file editor and save the files
with a .txt extension instead of the usual .py extension.


For some samples, you can download the following text files from this book’s website:


 http://invpy.com/devilsdictionary.txt
 http://invpy.com/frankenstein.txt
 http://invpy.com/siddhartha.txt
 http://invpy.com/thetimemachine.txt

These are text files of some books (that are now in the public domain, so it is perfectly legal to
download them.) For example, download Mary Shelley’s classic novel “Frankenstein” from
http://invpy.com/frankenstein.txt. Double-click the file to open it in a text editor program. There
are over 78 ,000 words in this text file! It would take some time to type this into our encryption
program. But if it is in a file, the program can read the file and do the encryption in a couple
seconds.


If you get an error that looks like “UnicodeDecodeError: 'charmap' codec can't
decode byte 0x90 in position 148: character maps to
then you are running the cipher program on a non-plain text file, also called a “binary file”.


To find other public domain texts to download, go to the Project Gutenberg website at
http://www.gutenberg.org/.


Source Code of the Transposition File Cipher Program


Like our transposition cipher testing program, the transposition cipher file program will import
our transpositionEncrypt.py and transpositionDecrypt.py files so we can use the

Free download pdf