Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 77f3cb0

Browse files
committedOct 11, 2024·
Add Gronsfeld cipher implementation
1 parent e9e7c96 commit 77f3cb0

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
 

‎ciphers/gronsfeld.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
def gronsfeld_encrypt(plaintext, key):
2+
"""
3+
Encrypts a plaintext using the Gronsfeld cipher.
4+
5+
Parameters:
6+
plaintext (str): The message to be encrypted.
7+
key (str): A numeric key used for encryption (e.g., "31415").
8+
9+
Returns:
10+
str: The encrypted message.
11+
"""
12+
ciphertext = ""
13+
key = [int(k) for k in key]
14+
key_length = len(key)
15+
16+
for i, letter in enumerate(plaintext):
17+
if letter.isalpha():
18+
shift = key[i % key_length]
19+
base = ord('A') if letter.isupper() else ord('a')
20+
# Shift and wrap around the alphabet
21+
ciphertext += chr((ord(letter) - base + shift) % 26 + base)
22+
else:
23+
ciphertext += letter
24+
25+
return ciphertext
26+
27+
28+
def gronsfeld_decrypt(ciphertext, key):
29+
"""
30+
Decrypts a ciphertext using the Gronsfeld cipher.
31+
32+
Parameters:
33+
ciphertext (str): The message to be decrypted.
34+
key (str): A numeric key used for decryption (e.g., "31415").
35+
36+
Returns:
37+
str: The decrypted message.
38+
"""
39+
plaintext = ""
40+
key = [int(k) for k in key]
41+
key_length = len(key)
42+
43+
for i, letter in enumerate(ciphertext):
44+
if letter.isalpha():
45+
shift = key[i % key_length]
46+
base = ord('A') if letter.isupper() else ord('a')
47+
# Reverse the shift to decrypt
48+
plaintext += chr((ord(letter) - base - shift) % 26 + base)
49+
else:
50+
plaintext += letter
51+
52+
return plaintext
53+
54+
55+
# Example usage:
56+
plaintext = input("Enter a message to encrypt: ")
57+
key = input("Enter a key (e.g., 31415): ")
58+
59+
encrypted_message = gronsfeld_encrypt(plaintext, key)
60+
print(f"Encrypted: {encrypted_message}")
61+
62+
decrypted_message = gronsfeld_decrypt(encrypted_message, key)
63+
print(f"Decrypted: {decrypted_message}")

0 commit comments

Comments
 (0)
Please sign in to comment.