|
| 1 | +""" |
| 2 | +This is an implementation of the 'Atbash' cipher, an ancient |
| 3 | +encryption system created in the Middle East. |
| 4 | +""" |
| 5 | + |
| 6 | +import string |
| 7 | + |
| 8 | +alphabet: str = string.ascii_lowercase |
| 9 | + |
| 10 | + |
| 11 | +def encode(plain_text: str) -> str: |
| 12 | + """ |
| 13 | + Encode text using the Atbash cipher. |
| 14 | +
|
| 15 | + Letters are mirrored in the lowercase Latin alphabet; digits are preserved. |
| 16 | + Punctuation characters '.,!?;:-' and spaces are removed. The result is grouped |
| 17 | + into 5-character blocks separated by spaces for readability. |
| 18 | +
|
| 19 | + :param plain_text: Input text to encode. |
| 20 | + :type plain_text: str |
| 21 | + :returns: Encoded text (grouped in 5-character blocks when length >= 5). |
| 22 | + :rtype: str |
| 23 | + """ |
| 24 | + temp_txt: list[str] = [ |
| 25 | + _replace(char.lower()) for char in plain_text if char.isalnum() |
| 26 | + ] |
| 27 | + return " ".join( |
| 28 | + "".join(temp_txt[i : i + 5]) for i in range(0, len(temp_txt), 5) |
| 29 | + ) |
| 30 | + |
| 31 | + |
| 32 | +def _replace(char: str) -> str: |
| 33 | + """ |
| 34 | + Apply Atbash mapping to a single character. |
| 35 | +
|
| 36 | + Alphabetic characters are lowercased and mirrored in the alphabet; |
| 37 | + non-letters are returned unchanged. |
| 38 | +
|
| 39 | + :param char: Character to transform. |
| 40 | + :type char: str |
| 41 | + :returns: Transformed character. |
| 42 | + :rtype: str |
| 43 | + """ |
| 44 | + if char.isalpha(): |
| 45 | + return alphabet[-(alphabet.index(char) + 1)] |
| 46 | + return char |
| 47 | + |
| 48 | + |
| 49 | +def decode(ciphered_text: str) -> str: |
| 50 | + """ |
| 51 | + Decode an Atbash-encoded string. |
| 52 | +
|
| 53 | + Atbash is symmetric; decoding reuses encoding and removes grouping spaces. |
| 54 | +
|
| 55 | + :param ciphered_text: Encoded text, optionally grouped with spaces. |
| 56 | + :type ciphered_text: str |
| 57 | + :returns: Decoded text without grouping spaces. |
| 58 | + :rtype: str |
| 59 | + """ |
| 60 | + return encode(ciphered_text).replace(" ", "") |
0 commit comments