244 http://inventwithpython.com/hacking
Email questions to the author: [email protected]
The translateMessage() function does the encryption (or decryption, if the mode
parameter is set to the string 'decrypt'). The encryption process is very simple: for each letter
in the message parameter, we look up its index in LETTERS and replace it with the letter at that
same index in the key parameter. To decrypt we do the opposite: we look up the index in key
and replace it with the letter at the same index in the LETTERS.
The table below shows why using the same index will encrypt or decrypt the letter. The top row
shows the characters in charsA (which is set to LETTERS on line 47), the middle row shows
the characters in charsB (which is set to key on line 48), and the bottom row are the integer
indexes (for our own reference in this example).
A B C D E F G H I J K L M
↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕
V J Z B G N F E P L I T M
0 1 2 3 4 5 6 7 8 9 10 11 12
N O P Q R S T U V W X Y Z
↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕
X D W K Q U C R Y A H S O
13 14 15 16 17 18 19 20 21 22 23 24 25
The code in translateMessage() will always look up the message character’s index in
charsA and replace it with the character at that index in charsB.
So to encrypt, we can just leave charsA and charsB as they are. This will replace the character
in LETTERS with the character in key, because charsA is set to LETTERS and charsB is set
to key.
When decrypting, the values in charsA and charsB (that is, LETTERS and key) are swapped
on line 52, so the table would look like this:
V J Z B G N F E P L I T M
↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕
A B C D E F G H I J K L M
0 1 2 3 4 5 6 7 8 9 10 11 12