Hacking Secret Ciphers with Python

(Ann) #1

116 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


Hello world!





spam = ['dog']
spam += ['cat']
print(spam)
['dog', 'cat']





The statement spam += 2 does the exact same thing as spam = spam + 2. It’s just a little
shorter to type. The += operator works with integers to do addition, strings to do string
concatenation, and lists to do list concatenation. Table 8 - 1 shows the augmented assignment
operators and what they are equivalent to:


Table 8-1. Augmented Assignment Operators
Augmented Assignment Equivalent Normal
Assignment
spam += 42 spam = spam + 42
spam -= 42 spam = spam - 42
spam *= 42 spam = spam * 42
spam /= 42 spam = spam / 42

Back to the Code


transpositionEncrypt.py



  1. Keep looping until pointer goes past the length of the message.



  2. while pointer < len(message):


  3. Place the character at pointer in message at the end of the




  4. current column in the ciphertext list.



  5. ciphertext[col] += message[pointer]




  6. move pointer over



  7. pointer += key


Inside the for loop that started on line 26 is a while loop that starts on line 30. For each
column, we want to loop through the original message variable and pick out every keyth
character. (In the example we’ve been using, we want every 8th character since we are using a key
of 8 .) On line 27 for the first iteration of the for loop, pointer was set to 0.


While the value in pointer is less than the length of the message string, we want to add the
character at message[pointer] to the end of the colth string in ciphertext. We add 8
(that is, the value in key) to pointer each time through the loop on line 36. The first time it is
message[0], the second time message[8], the third time message[16], and the fourth
time message[24]. Each of these single character strings are concatenated to the end of

Free download pdf