-
-
Notifications
You must be signed in to change notification settings - Fork 46.6k
/
Copy pathrunning_key_cipher.py
53 lines (42 loc) · 1.61 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
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 = []
for i in range(len(plaintext)):
p = ord(plaintext[i]) - 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 = []
for i in range(len(ciphertext)):
c = ord(ciphertext[i]) - ord("A")
k = ord(key[i % key_length]) - ord("A")
p = (c - k) % 26
plaintext.append(chr(p + ord("A")))
return "".join(plaintext)
if __name__ == "__main__":
key = "How does the duck know that? said Victor"
plaintext = input("Enter the plaintext: ").upper()
encrypted_text = running_key_encrypt(key, plaintext)
decrypted_text = running_key_decrypt(key, encrypted_text)
print("\nPlaintext:", plaintext)
print("Encrypted:", encrypted_text)
print("Decrypted:", decrypted_text)