Skip to content

Add running key cipher #10834

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Oct 29, 2023
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions ciphers/running_key_cipher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
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)


def test_running_key_encrypt():
"""
>>> key = "How does the duck know that? said Victor"
>>> plaintext = "DEFEND THIS"
>>> ciphertext = running_key_encrypt(key, plaintext)
>>> decrypted_text = running_key_decrypt(key, ciphertext)
>>> decrypted_text == "DEFENDTHIS"
True
"""


if __name__ == "__main__":
import doctest

doctest.testmod()
test_running_key_encrypt()

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)