Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Transposition Cipher (Decrypt)



The previous post was about encrypting a text with Transposition Cipher but now we will make a program to decrypt the message provided that you have the key.

Source Code :-

-------------------------------------------------------------

# Transposition Cipher Decryption
import math, pyperclip

def main():
myMessage = input("Enter the encoded text"" ")
myKey = int(input("Enter the key"" "))

plaintext = decryptMessage(myKey, myMessage)


# Print with a | (called "pipe" character) after it in case

# there are spaces at the end of the decrypted message.
    print(plaintext + '|')

pyperclip.copy(plaintext)


def decryptMessage(key, message):
# The Transposition decrypt function will simulate the "columns" and    
#"rows" of the Grid that the plaintext is written on by using a list    

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

    # The number of "columns" in our transposition grid:    
    numOfColumns = math.ceil(len(message) / key)
 # The number of "rows" in our grid will need:    
    numOfRows = key
    # The number of "shaded boxes" in the last "column" of the grid:    
    numOfShadedBoxes = (numOfColumns * numOfRows) - len(message)

# Each string in plaintext represents a column in the grid.
    plaintext = [''] * numOfColumns

# The col and row variables point to where in the grid the next
 # character in the encrypted message will go.    
    col = 0   
    row = 0
for symbol in message:
plaintext[col] += symbol
col += 1 # point to next column
       # If there are no more columns OR we're at a shaded box, go back to
        # the first column and the next row.       
        if (col == numOfColumns) or (col == numOfColumns - 1 and row >= numOfRows - numOfShadedBoxes):
col = 0 row += 1
return ''.join(plaintext)


# If transpositionDecrypt.py is run (instead of imported as a module) call
#the main() function.if __name__ == '__main__':
main()

---------------------------------------------

Result :-




If you face any problem just let me know in the comments below. Don't forget to subscribe for more such posts . :)



This post first appeared on CODE IT TO RULE IT, please read the originial post: here

Share the post

Transposition Cipher (Decrypt)

×

Subscribe to Code It To Rule It

Get updates delivered right to your inbox!

Thank you for your subscription

×