Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions doc/code/converters/1_text_to_text_converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
NatoConverter,
NegationTrapConverter,
ROT13Converter,
TapCodeConverter,
TokenBijectionConverter,
VigenereConverter,
)
Expand All @@ -84,6 +85,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
Expand Down
2 changes: 2 additions & 0 deletions pyrit/converter/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,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
Expand Down Expand Up @@ -248,6 +249,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",
Expand Down
134 changes: 134 additions & 0 deletions pyrit/converter/tap_code_converter.py
Original file line number Diff line number Diff line change
@@ -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)
3 changes: 3 additions & 0 deletions pyrit/scenario/scenarios/garak/encoding.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
MorseConverter,
NatoConverter,
ROT13Converter,
TapCodeConverter,
ZalgoConverter,
)
from pyrit.executor.attack import AttackConverterConfig, AttackScoringConfig, PromptSendingAttack
Expand Down Expand Up @@ -129,6 +130,7 @@ class EncodingTechnique(ScenarioTechnique):
AsciiSmuggler = ("ascii_smuggler", set[str]())
Bifid = ("bifid", set[str]())
ColumnarTransposition = ("columnar_transposition", set[str]())
TapCode = ("tap_code", set[str]())

@classmethod
def get_aggregate_tags(cls) -> set[str]:
Expand Down Expand Up @@ -317,6 +319,7 @@ def _converter_variants() -> list[tuple[list[Converter], str, str]]:
([AsciiSmugglerConverter()], "ascii_smuggler", "ascii_smuggler"),
([BifidConverter()], "bifid", "bifid"),
([ColumnarTranspositionConverter(key="ZEBRAS")], "columnar_transposition", "columnar_transposition"),
([TapCodeConverter()], "tap_code", "tap_code"),
]

# These are the same as Garak encoding attacks
Expand Down
84 changes: 84 additions & 0 deletions tests/unit/converter/test_tap_code_converter.py
Original file line number Diff line number Diff line change
@@ -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")
3 changes: 2 additions & 1 deletion tests/unit/scenario/garak/test_encoding.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ 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) == 19
assert len(all_names) == 20
# The niche/lossy schemes stay ALL-only.
assert all_names - default_names == {
"braille",
Expand All @@ -262,6 +262,7 @@ def test_default_aggregate_curates_representative_subset(self):
"ascii_smuggler",
"bifid",
"columnar_transposition",
"tap_code",
}

def test_get_aggregate_tags_includes_default(self):
Expand Down
Loading