Hacking Secret Ciphers with Python

(Ann) #1

236 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


The transposition and affine ciphers have thousands of possible keys, but a computer can still
brute-force through all of them easily. We’ll need a cipher that has so many possible keys, no
computer can possibly brute-force through them all.


The simple substitution cipher is effectively invulnerable to a brute-force attack. Even if your
computer could try out a trillion keys every second, it would still take twelve million years for it
to try out every key.


The Simple Substitution Cipher with Paper and Pencil


To implement the simple substitution cipher, choose a random letter to encrypt each letter of the
alphabet. Use each letter once and only once. The key will end up being a string of 26 letters of
the alphabet in random order. There are 403,291,461,126,605,635,584,000,000 possible orderings
for keys. (To see how this number was calculated, see http://invpy.com/factorial)..)


Let’s do the simple substitution cipher with paper and pencil first. For example, let’s encrypt the
message, “Attack at dawn.” with the key VJZBGNFEPLITMXDWKQUCRYAHSO. First write
out the letters of the alphabet and then write the key underneath it.


A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕
V J Z B G N F E P L I T M X D W K Q U C R Y A H S O


To encrypt a message, find the letter from the plaintext in the top row and substitute it with the
letter in the bottom row. A encrypts to V, and T encrypts to C, C encrypts to Z, and so on. So the
message “Attack at dawn.” encrypts to “Vccvzi vc bvax.”


To decrypt, find the letter from the ciphertext in the bottom row and replace it with the letter from
the top row. V decrypts to A, C decrypts to T, Z decrypts to C, and so on.


This is very similar to how the Caesar cipher works with the St. Cyr slide, except the bottom row
is scrambled instead of in alphabetical order and just shifted over. The advantage of the simple
substitution cipher is that there are far more possible keys. The disadvantage is that the key is 26
characters long and harder to memorize. If you write down the key, make sure that this key is
never read by anyone else!


Practice Exercises, Chapter 17, Set A


Practice exercises can be found at http://invpy.com/hackingpractice 17 A.

Free download pdf