|
| 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: [str] = [ |
| 25 | + _replace(char) for char in plain_text if char not in ".,!? " |
| 26 | + ] |
| 27 | + if len(temp_txt) > 4: |
| 28 | + step: int = 5 |
| 29 | + i_start: int = 0 |
| 30 | + i_end: int = i_start + step |
| 31 | + txt: list[str] = [] |
| 32 | + while i_start <= len(temp_txt): |
| 33 | + tmp: str = "".join(temp_txt[i_start:i_end]) |
| 34 | + if tmp: |
| 35 | + txt.append(tmp) |
| 36 | + i_start, i_end = i_end, i_end + step |
| 37 | + return " ".join(txt) |
| 38 | + return "".join(temp_txt) |
| 39 | + |
| 40 | + |
| 41 | +def _replace(char: str) -> str: |
| 42 | + """ |
| 43 | + Apply Atbash mapping to a single character. |
| 44 | +
|
| 45 | + Alphabetic characters are lowercased and mirrored in the alphabet; |
| 46 | + non-letters are returned unchanged. |
| 47 | +
|
| 48 | + :param char: Character to transform. |
| 49 | + :type char: str |
| 50 | + :returns: Transformed character. |
| 51 | + :rtype: str |
| 52 | + """ |
| 53 | + if char.lower().isalpha(): |
| 54 | + return alphabet[-(alphabet.index(char.lower()) + 1)] |
| 55 | + return char |
| 56 | + |
| 57 | + |
| 58 | +def decode(ciphered_text: str) -> str: |
| 59 | + """ |
| 60 | + Decode an Atbash-encoded string. |
| 61 | +
|
| 62 | + Atbash is symmetric; decoding reuses encoding and removes grouping spaces. |
| 63 | +
|
| 64 | + :param ciphered_text: Encoded text, optionally grouped with spaces. |
| 65 | + :type ciphered_text: str |
| 66 | + :returns: Decoded text without grouping spaces. |
| 67 | + :rtype: str |
| 68 | + """ |
| 69 | + return encode(ciphered_text).replace(" ", "") |
0 commit comments