From c5819b2e872b8822c67da17b01a2ee1f221c16e9 Mon Sep 17 00:00:00 2001 From: Roman Lutz Date: Thu, 19 Nov 2026 15:23:40 -0800 Subject: [PATCH] FEAT: Add TapCodeConverter (tap_code converter) Co-Authored-By: Claude Opus 4.8 --- .../converters/1_text_to_text_converters.py | 2 + pyrit/converter/__init__.py | 2 + pyrit/converter/tap_code_converter.py | 134 ++++++++++++++++++ pyrit/scenario/scenarios/garak/encoding.py | 3 + .../unit/converter/test_tap_code_converter.py | 84 +++++++++++ tests/unit/scenario/garak/test_encoding.py | 4 +- 6 files changed, 227 insertions(+), 2 deletions(-) create mode 100644 pyrit/converter/tap_code_converter.py create mode 100644 tests/unit/converter/test_tap_code_converter.py diff --git a/doc/code/converters/1_text_to_text_converters.py b/doc/code/converters/1_text_to_text_converters.py index 578a90c251..637af5e54a 100644 --- a/doc/code/converters/1_text_to_text_converters.py +++ b/doc/code/converters/1_text_to_text_converters.py @@ -64,6 +64,7 @@ NatoConverter, NegationTrapConverter, ROT13Converter, + TapCodeConverter, TokenBijectionConverter, VigenereConverter, ) @@ -83,6 +84,7 @@ print("ROT13:", await ROT13Converter().convert_async(prompt=prompt)) # type: ignore print("Base64:", await Base64Converter().convert_async(prompt=prompt)) # type: ignore print("Base2048:", await Base2048Converter().convert_async(prompt=prompt)) # type: ignore +print("Tap code:", await TapCodeConverter().convert_async(prompt=prompt)) # type: ignore print("Binary:", await BinaryConverter().convert_async(prompt=prompt)) # type: ignore print("BinAscii:", await BinAsciiConverter().convert_async(prompt=prompt)) # type: ignore print("Morse:", await MorseConverter().convert_async(prompt=prompt)) # type: ignore diff --git a/pyrit/converter/__init__.py b/pyrit/converter/__init__.py index 1c8722e5b2..b558b1c0fb 100644 --- a/pyrit/converter/__init__.py +++ b/pyrit/converter/__init__.py @@ -105,6 +105,7 @@ from pyrit.converter.string_join_converter import StringJoinConverter from pyrit.converter.suffix_append_converter import SuffixAppendConverter from pyrit.converter.superscript_converter import SuperscriptConverter + from pyrit.converter.tap_code_converter import TapCodeConverter from pyrit.converter.task_framing_converter import TaskFramingConverter from pyrit.converter.tatweel_converter import TatweelConverter from pyrit.converter.template_segment_converter import TemplateSegmentConverter @@ -246,6 +247,7 @@ "StringJoinConverter": "pyrit.converter.string_join_converter", "SuffixAppendConverter": "pyrit.converter.suffix_append_converter", "SuperscriptConverter": "pyrit.converter.superscript_converter", + "TapCodeConverter": "pyrit.converter.tap_code_converter", "TaskFramingConverter": "pyrit.converter.task_framing_converter", "TatweelConverter": "pyrit.converter.tatweel_converter", "TemplateSegmentConverter": "pyrit.converter.template_segment_converter", diff --git a/pyrit/converter/tap_code_converter.py b/pyrit/converter/tap_code_converter.py new file mode 100644 index 0000000000..03a9bfa219 --- /dev/null +++ b/pyrit/converter/tap_code_converter.py @@ -0,0 +1,134 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + + +from pyrit.converter.converter import Converter, ConverterResult +from pyrit.models import ComponentIdentifier, PromptDataType + + +class TapCodeConverter(Converter): + """ + Encodes text using the tap code (also known as the knock code). + + The tap code is a Polybius-style code historically used by prisoners of war to + communicate by tapping on walls or pipes. Each letter is placed on a 5x5 grid and + encoded as two groups of taps giving its ``(row, column)`` coordinate:: + + 1 2 3 4 5 + 1 A B C D E + 2 F G H I J + 3 L M N O P + 4 Q R S T U + 5 V W X Y Z + + Because the grid holds only 25 cells, the letters C and K share a single cell + (row 1, column 3); a ``K`` in the input is encoded exactly like a ``C``. For + example, the letter ``A`` is ``(1, 1)`` -> ``". ."`` and ``W`` is ``(5, 2)`` -> + ``"..... .."``. The code is case-insensitive and any character that is not an + ASCII letter (digits, whitespace, punctuation) is preserved verbatim so the + encoded prompt keeps its structure. + + The tap code is in the public domain. See the standard reference, + Wikipedia, "Tap code" (https://en.wikipedia.org/wiki/Tap_code). Encoding a + prompt into an uncommon cipher to probe a model's safety behavior follows the + CipherChat jailbreak framing (Yuan et al., "GPT-4 Is Too Smart To Be Safe", + arXiv:2308.06463). + + Note: This converter is useful for testing how AI systems handle tap-code-encoded + text, which can be used to obfuscate potentially harmful content. + """ + + SUPPORTED_INPUT_TYPES = ("text",) + SUPPORTED_OUTPUT_TYPES = ("text",) + + # The 25-letter tap-code alphabet laid out row by row (K is omitted and shares C's cell). + _GRID = "ABCDEFGHIJLMNOPQRSTUVWXYZ" + + def __init__( + self, + *, + tap_symbol: str = ".", + group_separator: str = " ", + letter_separator: str = " ", + ) -> None: + """ + Initialize the converter with configurable tap and separator symbols. + + Args: + tap_symbol (str): The symbol used to represent a single tap. Defaults to ".". + group_separator (str): The separator placed between the row-tap group and the + column-tap group of a single letter. Defaults to " " (a single space). + letter_separator (str): The separator placed between encoded letters. Defaults + to " " (two spaces), chosen to stay visually distinct from the + ``group_separator``. + """ + self.tap_symbol = tap_symbol + self.group_separator = group_separator + self.letter_separator = letter_separator + + # Precompute the (row, column) coordinate for each supported letter. + self._coordinates: dict[str, tuple[int, int]] = {} + for index, letter in enumerate(self._GRID): + self._coordinates[letter] = (index // 5 + 1, index % 5 + 1) + # K shares C's cell. + self._coordinates["K"] = self._coordinates["C"] + + def _build_identifier(self) -> ComponentIdentifier: + """ + Build identifier with tap-code converter parameters. + + Returns: + ComponentIdentifier: The identifier for this converter. + """ + return self._create_identifier( + params={ + "tap_symbol": self.tap_symbol, + "group_separator": self.group_separator, + "letter_separator": self.letter_separator, + } + ) + + async def convert_async(self, *, prompt: str, input_type: PromptDataType = "text") -> ConverterResult: + """ + Convert the given prompt to tap code. + + Args: + prompt (str): The prompt to be converted. + input_type (PromptDataType, optional): Type of input data. Defaults to "text". + + Returns: + ConverterResult: The result containing the tap-code representation of the prompt. + + Raises: + ValueError: If the input type is not supported. + """ + if not self.input_supported(input_type): + raise ValueError("Input type not supported") + + return ConverterResult(output_text=self._tap_code(prompt), output_type="text") + + def _tap_code(self, text: str) -> str: + """ + Encode the input text into tap code. + + Each ASCII letter is replaced with its row-tap and column-tap groups joined by the + ``group_separator``; encoded letters are joined by the ``letter_separator``. Any + character that is not an ASCII letter is preserved verbatim so surrounding structure + (spaces, digits, punctuation) survives the transformation. + + Args: + text (str): The input text to encode. + + Returns: + str: The tap-code representation of the input text. + """ + tokens: list[str] = [] + for char in text: + coordinate = self._coordinates.get(char.upper()) + if coordinate is None: + # Preserve non-letters verbatim. + tokens.append(char) + continue + row, column = coordinate + tokens.append(f"{self.tap_symbol * row}{self.group_separator}{self.tap_symbol * column}") + return self.letter_separator.join(tokens) diff --git a/pyrit/scenario/scenarios/garak/encoding.py b/pyrit/scenario/scenarios/garak/encoding.py index 2540179e26..daf5f5062a 100644 --- a/pyrit/scenario/scenarios/garak/encoding.py +++ b/pyrit/scenario/scenarios/garak/encoding.py @@ -22,6 +22,7 @@ MorseConverter, NatoConverter, ROT13Converter, + TapCodeConverter, ZalgoConverter, ) from pyrit.executor.attack import AttackConverterConfig, AttackScoringConfig, PromptSendingAttack @@ -127,6 +128,7 @@ class EncodingTechnique(ScenarioTechnique): LeetSpeak = ("leet_speak", {"default"}) AsciiSmuggler = ("ascii_smuggler", set[str]()) Bifid = ("bifid", set[str]()) + TapCode = ("tap_code", set[str]()) @classmethod def get_aggregate_tags(cls) -> set[str]: @@ -314,6 +316,7 @@ def _converter_variants() -> list[tuple[list[Converter], str, str]]: ([LeetspeakConverter()], "leet_speak", "leet_speak"), ([AsciiSmugglerConverter()], "ascii_smuggler", "ascii_smuggler"), ([BifidConverter()], "bifid", "bifid"), + ([TapCodeConverter()], "tap_code", "tap_code"), ] # These are the same as Garak encoding attacks diff --git a/tests/unit/converter/test_tap_code_converter.py b/tests/unit/converter/test_tap_code_converter.py new file mode 100644 index 0000000000..a8fc2b35d6 --- /dev/null +++ b/tests/unit/converter/test_tap_code_converter.py @@ -0,0 +1,84 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import pytest + +from pyrit.converter import ConverterResult, TapCodeConverter + + +async def test_tap_code_converter_single_letter(): + converter = TapCodeConverter() + result = await converter.convert_async(prompt="A", input_type="text") + assert isinstance(result, ConverterResult) + # A is at (row 1, column 1). + assert result.output_text == ". ." + assert result.output_type == "text" + + +async def test_tap_code_converter_known_example(): + # Standard tap-code worked example: WATER. + # W=(5,2) A=(1,1) T=(4,4) E=(1,5) R=(4,2) + converter = TapCodeConverter() + result = await converter.convert_async(prompt="WATER", input_type="text") + assert result.output_text == "..... .. . . .... .... . ..... .... .." + assert result.output_type == "text" + + +async def test_tap_code_converter_corner_letters(): + converter = TapCodeConverter() + # A=(1,1), E=(1,5), V=(5,1), Z=(5,5) + result = await converter.convert_async(prompt="AEVZ", input_type="text") + assert result.output_text == ". . . ..... ..... . ..... ....." + + +async def test_tap_code_converter_c_and_k_share_cell(): + converter = TapCodeConverter() + c_result = await converter.convert_async(prompt="C", input_type="text") + k_result = await converter.convert_async(prompt="K", input_type="text") + # Both C and K map to (row 1, column 3). + assert c_result.output_text == ". ..." + assert k_result.output_text == ". ..." + assert c_result.output_text == k_result.output_text + + +async def test_tap_code_converter_case_insensitive(): + converter = TapCodeConverter() + lower = await converter.convert_async(prompt="water", input_type="text") + upper = await converter.convert_async(prompt="WATER", input_type="text") + assert lower.output_text == upper.output_text + + +async def test_tap_code_converter_preserves_non_letters(): + converter = TapCodeConverter() + result = await converter.convert_async(prompt="A1!", input_type="text") + # The digit and punctuation pass through verbatim, joined by the letter separator. + assert result.output_text == ". . 1 !" + + +async def test_tap_code_converter_custom_symbols(): + converter = TapCodeConverter(tap_symbol="*", group_separator="-", letter_separator="/") + result = await converter.convert_async(prompt="AB", input_type="text") + # A=(1,1)->"*-*", B=(1,2)->"*-**" + assert result.output_text == "*-*/*-**" + + +async def test_tap_code_converter_empty(): + converter = TapCodeConverter() + result = await converter.convert_async(prompt="", input_type="text") + assert result.output_text == "" + assert result.output_type == "text" + + +async def test_tap_code_converter_identifier_includes_params(): + converter = TapCodeConverter(tap_symbol="*", group_separator="-", letter_separator="/") + identifier = converter.get_identifier() + params = identifier.params + assert params["tap_symbol"] == "*" + assert params["group_separator"] == "-" + assert params["letter_separator"] == "/" + + +async def test_tap_code_converter_input_not_supported(): + converter = TapCodeConverter() + with pytest.raises(ValueError): + await converter.convert_async(prompt="hello", input_type="image_path") diff --git a/tests/unit/scenario/garak/test_encoding.py b/tests/unit/scenario/garak/test_encoding.py index 5db1297404..96dad2939c 100644 --- a/tests/unit/scenario/garak/test_encoding.py +++ b/tests/unit/scenario/garak/test_encoding.py @@ -253,9 +253,9 @@ def test_default_aggregate_curates_representative_subset(self): } all_names = {t.value for t in EncodingTechnique.get_all_techniques()} assert default_names < all_names - assert len(all_names) == 18 + assert len(all_names) == 19 # The niche/lossy schemes stay ALL-only. - assert all_names - default_names == {"braille", "ecoji", "zalgo", "ascii_smuggler", "bifid"} + assert all_names - default_names == {"braille", "ecoji", "zalgo", "ascii_smuggler", "bifid", "tap_code"} def test_get_aggregate_tags_includes_default(self): """The scenario exposes both ``all`` and ``default`` as aggregate tags."""