Skip to content
This repository has been archived by the owner on Apr 14, 2019. It is now read-only.

added rail fence cipher #15

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions rail-fence-cipher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
def encrypt(clearText, key):
Copy link
Contributor

@sibasish14 sibasish14 Dec 30, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@debck add the name of the cipher in a comment line at the top.

result = ""
matrix = [["" for x in range(len(clearText))] for y in range(key)]
increment = 1
row = 0
col = 0
for c in clearText:
if row + increment < 0 or row + increment >= len(matrix):
increment = increment * -1
matrix[row][col] = c
row += increment
col += 1
for mlist in matrix:
result += "".join(mlist)
return result


def decrypt(cipherText, key):
result = ""
matrix = [["" for x in range(len(cipherText))] for y in range(key)]
idx = 0
increment = 1
for selectedRow in range(0, len(matrix)):
row = 0
for col in range(0, len(matrix[row])):
if row + increment < 0 or row + increment >= len(matrix):
increment = increment * -1
if row == selectedRow:
matrix[row][col] += cipherText[idx]
idx += 1
row += increment
matrix = transpose(matrix)
for klist in matrix:
result += "".join(klist)
return result


def transpose(m):
result = [[0 for y in range(len(m))] for x in range(len(m[0]))]
for i in enumerate(m):
for j in enumerate(m[0]):
result[j][i] = m[i][j]
return result


def main():
clearText = "i am the king"
print("Original Text: " + clearText)
key = 3
cipherText = encrypt(clearText, key)
print("Encrypted Text: {0}".format(cipherText))
decipherText = decrypt(cipherText, key)
print("Decrypted Text: {0}".format(decipherText))
return


if __name__ == '__main__':
main()