-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrail_fence.py
executable file
·65 lines (40 loc) · 1.18 KB
/
rail_fence.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/bin/python
# https://en.wikipedia.org/wiki/Rail_fence_cipher
from collections import deque
from functools import reduce
import string
import sys
def generate_zigzag_indices(length: int, rail_count: int) -> list[int]:
rails = [[] for _ in range(rail_count)]
gaps = rail_count - 1
rail = 0
direction = 1
for i in range(length):
rails[rail].append(i)
rail += direction
if rail == 0 or rail == gaps:
direction *= -1
return reduce(lambda x, y: x.extend(y) or x, rails, [])
def encrypt(plaintext: str, rail_count: int) -> str:
result = []
for i in generate_zigzag_indices(len(plaintext), rail_count):
result.append(plaintext[i])
return ''.join(result)
def decrypt(ciphertext: str, rail_count: int) -> str:
result = [''] * len(ciphertext)
for i, char in zip(generate_zigzag_indices(len(ciphertext), rail_count), ciphertext):
result[i] = char
return ''.join(result)
def main():
assert(len(sys.argv) == 3)
rail_count = int(sys.argv[1])
mode = sys.argv[2]
assert(mode in ("-e", "-d"))
text = input().strip()
if mode == "-e":
print(encrypt(text, rail_count))
return
if mode == "-d":
print(decrypt(text, rail_count))
if __name__ == "__main__":
main()