forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransposition_cipher.py
More file actions
Latest commit
68 lines (53 loc) · 1.77 KB
/
Copy pathtransposition_cipher.py
File metadata and controls
68 lines (53 loc) · 1.77 KB
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
66
67
68
importmath
"""
In cryptography, the TRANSPOSITION cipher is a method of encryption where the
positions of plaintext are shifted a certain number(determined by the key) that
follows a regular system that results in the permuted text, known as the encrypted
text. The type of transposition cipher demonstrated under is the ROUTE cipher.
"""
defmain() ->None:
message=input("Enter message: ")
key=int(input(f"Enter key [2-{len(message) -1}]: "))
mode=input("Encryption/Decryption [e/d]: ")
ifmode.lower().startswith("e"):
text=encrypt_message(key, message)
elifmode.lower().startswith("d"):
text=decrypt_message(key, message)
# Append pipe symbol (vertical bar) to identify spaces at the end.
print(f"Output:\n{text+'|'}")
defencrypt_message(key: int, message: str) ->str:
"""
>>> encrypt_message(6, 'Harshil Darji')
'Hlia rDsahrij'
"""
cipher_text= [""] *key
forcolinrange(key):
pointer=col
whilepointer<len(message):
cipher_text[col] +=message[pointer]
pointer+=key
return"".join(cipher_text)
defdecrypt_message(key: int, message: str) ->str:
"""
>>> decrypt_message(6, 'Hlia rDsahrij')
'Harshil Darji'
"""
num_cols=math.ceil(len(message) /key)
num_rows=key
num_shaded_boxes= (num_cols*num_rows) -len(message)
plain_text= [""] *num_cols
col=0
row=0
forsymbolinmessage:
plain_text[col] +=symbol
col+=1
if (col==num_cols) or (
(col==num_cols-1) and (row>=num_rows-num_shaded_boxes)
):
col=0
row+=1
return"".join(plain_text)
if__name__=="__main__":
importdoctest
doctest.testmod()
main()