1
+ """
2
+ https://en.wikipedia.org/wiki/Running_key_cipher
3
+ """
4
+
5
+
1
6
def running_key_encrypt (key : str , plaintext : str ) -> str :
2
7
"""
3
8
Encrypts the plaintext using the Running Key Cipher.
@@ -10,12 +15,13 @@ def running_key_encrypt(key: str, plaintext: str) -> str:
10
15
key = key .replace (" " , "" ).upper ()
11
16
key_length = len (key )
12
17
ciphertext = []
18
+ ord_a = ord ("A" )
13
19
14
- for i in range ( len ( plaintext ) ):
15
- p = ord (plaintext [ i ] ) - ord ( "A" )
16
- k = ord (key [i % key_length ]) - ord ( "A" )
20
+ for i , char in enumerate ( plaintext ):
21
+ p = ord (char ) - ord_a
22
+ k = ord (key [i % key_length ]) - ord_a
17
23
c = (p + k ) % 26
18
- ciphertext .append (chr (c + ord ( "A" ) ))
24
+ ciphertext .append (chr (c + ord_a ))
19
25
20
26
return "" .join (ciphertext )
21
27
@@ -32,23 +38,22 @@ def running_key_decrypt(key: str, ciphertext: str) -> str:
32
38
key = key .replace (" " , "" ).upper ()
33
39
key_length = len (key )
34
40
plaintext = []
41
+ ord_a = ord ("A" )
35
42
36
- for i in range ( len ( ciphertext ) ):
37
- c = ord (ciphertext [ i ] ) - ord ( "A" )
38
- k = ord (key [i % key_length ]) - ord ( "A" )
43
+ for i , char in enumerate ( ciphertext ):
44
+ c = ord (char ) - ord_a
45
+ k = ord (key [i % key_length ]) - ord_a
39
46
p = (c - k ) % 26
40
- plaintext .append (chr (p + ord ( "A" ) ))
47
+ plaintext .append (chr (p + ord_a ))
41
48
42
49
return "" .join (plaintext )
43
50
44
51
45
52
def test_running_key_encrypt () -> None :
46
53
"""
47
54
>>> key = "How does the duck know that? said Victor"
48
- >>> plaintext = "DEFEND THIS"
49
- >>> ciphertext = running_key_encrypt(key, plaintext)
50
- >>> decrypted_text = running_key_decrypt(key, ciphertext)
51
- >>> decrypted_text == "DEFENDTHIS"
55
+ >>> ciphertext = running_key_encrypt(key, "DEFEND THIS")
56
+ >>> running_key_decrypt(key, ciphertext) == "DEFENDTHIS"
52
57
True
53
58
"""
54
59
@@ -59,11 +64,12 @@ def test_running_key_encrypt() -> None:
59
64
doctest .testmod ()
60
65
test_running_key_encrypt ()
61
66
62
- key = "How does the duck know that? said Victor"
63
67
plaintext = input ("Enter the plaintext: " ).upper ()
68
+ print (f"\n { plaintext = } " )
69
+
70
+ key = "How does the duck know that? said Victor"
64
71
encrypted_text = running_key_encrypt (key , plaintext )
65
- decrypted_text = running_key_decrypt ( key , encrypted_text )
72
+ print ( f" { encrypted_text = } " )
66
73
67
- print ("\n Plaintext:" , plaintext )
68
- print ("Encrypted:" , encrypted_text )
69
- print ("Decrypted:" , decrypted_text )
74
+ decrypted_text = running_key_decrypt (key , encrypted_text )
75
+ print (f"{ decrypted_text = } " )
0 commit comments