Hacking Secret Ciphers with Python

(Ann) #1

130 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


4





math.ceil(4.2)
5
math.ceil(4.9)
5





The math.ceil() function will implement step 1 of the transposition decryption.


transpositionDecrypt.py


  1. def decryptMessage(key, message):


  2. The transposition decrypt function will simulate the "columns" and




  3. "rows" of the grid that the plaintext is written on by using a list




  4. of strings. First, we need to calculate a few values.






  5. The number of "columns" in our transposition grid:



  6. numOfColumns = math.ceil(len(message) / key)


  7. The number of "rows" in our grid will need:



  8. numOfRows = key


  9. The number of "shaded boxes" in the last "column" of the grid:



  10. numOfShadedBoxes = (numOfColumns * numOfRows) - len(message)


Line 25 calculates the number of columns (step 1 of decrypting) by dividing len(message) by
the integer in key. This value is passed to the math.ceil() function, and that return value is
stored in numOfColumns.


Line 27 calculates the number of rows (step 2 of decrypting), which is the integer stored in key.
This value gets stored in the variable numOfRows.


Line 29 calculates the number of shaded boxes in the grid (step 3 of decrypting), which will be
the number of columns times rows, minus the length of the message.


If we are decrypting “Cenoonommstmme oo snnio. s s c” with key 8, numOfColumns will be
set to 4 , numOfRows will be set to 8 , and numOfShadedBoxes will be set to 2.


transpositionDecrypt.py



  1. Each string in plaintext represents a column in the grid.



  2. plaintext = [''] * numOfColumns


Just like the encryption program had a variable named ciphertext that was a list of strings to
represent the grid of ciphertext, the decryptMessage() function will have a variable named
plaintext that is a list of strings. These strings start off as blank strings, and we will need one

Free download pdf