-
-
Notifications
You must be signed in to change notification settings - Fork 46k
/
running_key_cipher.py
75 lines (57 loc) · 1.98 KB
/
running_key_cipher.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
66
67
68
69
70
71
72
73
74
75
"""
https://en.wikipedia.org/wiki/Running_key_cipher
"""
def running_key_encrypt(key: str, plaintext: str) -> str:
"""
Encrypts the plaintext using the Running Key Cipher.
:param key: The running key (long piece of text).
:param plaintext: The plaintext to be encrypted.
:return: The ciphertext.
"""
plaintext = plaintext.replace(" ", "").upper()
key = key.replace(" ", "").upper()
key_length = len(key)
ciphertext = []
ord_a = ord("A")
for i, char in enumerate(plaintext):
p = ord(char) - ord_a
k = ord(key[i % key_length]) - ord_a
c = (p + k) % 26
ciphertext.append(chr(c + ord_a))
return "".join(ciphertext)
def running_key_decrypt(key: str, ciphertext: str) -> str:
"""
Decrypts the ciphertext using the Running Key Cipher.
:param key: The running key (long piece of text).
:param ciphertext: The ciphertext to be decrypted.
:return: The plaintext.
"""
ciphertext = ciphertext.replace(" ", "").upper()
key = key.replace(" ", "").upper()
key_length = len(key)
plaintext = []
ord_a = ord("A")
for i, char in enumerate(ciphertext):
c = ord(char) - ord_a
k = ord(key[i % key_length]) - ord_a
p = (c - k) % 26
plaintext.append(chr(p + ord_a))
return "".join(plaintext)
def test_running_key_encrypt() -> None:
"""
>>> key = "How does the duck know that? said Victor"
>>> ciphertext = running_key_encrypt(key, "DEFEND THIS")
>>> running_key_decrypt(key, ciphertext) == "DEFENDTHIS"
True
"""
if __name__ == "__main__":
import doctest
doctest.testmod()
test_running_key_encrypt()
plaintext = input("Enter the plaintext: ").upper()
print(f"\n{plaintext = }")
key = "How does the duck know that? said Victor"
encrypted_text = running_key_encrypt(key, plaintext)
print(f"{encrypted_text = }")
decrypted_text = running_key_decrypt(key, encrypted_text)
print(f"{decrypted_text = }")