|
1 | 1 | def gronsfeld_encrypt(plaintext, key):
|
2 | 2 | """
|
3 | 3 | Encrypts a plaintext using the Gronsfeld cipher.
|
4 |
| - |
| 4 | +
|
5 | 5 | Parameters:
|
6 | 6 | plaintext (str): The message to be encrypted.
|
7 | 7 | key (str): A numeric key used for encryption (e.g., "31415").
|
8 |
| - |
| 8 | +
|
9 | 9 | Returns:
|
10 | 10 | str: The encrypted message.
|
11 | 11 | """
|
12 | 12 | ciphertext = ""
|
13 | 13 | key = [int(k) for k in key]
|
14 | 14 | key_length = len(key)
|
15 |
| - |
| 15 | + |
16 | 16 | for i, letter in enumerate(plaintext):
|
17 | 17 | if letter.isalpha():
|
18 | 18 | shift = key[i % key_length]
|
19 |
| - base = ord('A') if letter.isupper() else ord('a') |
| 19 | + base = ord("A") if letter.isupper() else ord("a") |
20 | 20 | # Shift and wrap around the alphabet
|
21 | 21 | ciphertext += chr((ord(letter) - base + shift) % 26 + base)
|
22 | 22 | else:
|
23 | 23 | ciphertext += letter
|
24 |
| - |
| 24 | + |
25 | 25 | return ciphertext
|
26 | 26 |
|
27 | 27 |
|
28 | 28 | def gronsfeld_decrypt(ciphertext, key):
|
29 | 29 | """
|
30 | 30 | Decrypts a ciphertext using the Gronsfeld cipher.
|
31 |
| - |
| 31 | +
|
32 | 32 | Parameters:
|
33 | 33 | ciphertext (str): The message to be decrypted.
|
34 | 34 | key (str): A numeric key used for decryption (e.g., "31415").
|
35 |
| - |
| 35 | +
|
36 | 36 | Returns:
|
37 | 37 | str: The decrypted message.
|
38 | 38 | """
|
39 | 39 | plaintext = ""
|
40 | 40 | key = [int(k) for k in key]
|
41 | 41 | key_length = len(key)
|
42 |
| - |
| 42 | + |
43 | 43 | for i, letter in enumerate(ciphertext):
|
44 | 44 | if letter.isalpha():
|
45 | 45 | shift = key[i % key_length]
|
46 |
| - base = ord('A') if letter.isupper() else ord('a') |
| 46 | + base = ord("A") if letter.isupper() else ord("a") |
47 | 47 | # Reverse the shift to decrypt
|
48 | 48 | plaintext += chr((ord(letter) - base - shift) % 26 + base)
|
49 | 49 | else:
|
50 | 50 | plaintext += letter
|
51 |
| - |
| 51 | + |
52 | 52 | return plaintext
|
53 | 53 |
|
54 | 54 |
|
|
0 commit comments