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
75 changes: 38 additions & 37 deletions doc/code/converters/0_converters.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@
"metadata": {},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"output_type": "stream",
"text": [
" Input Modality Output Modality Converter\n",
"0 audio_path audio_path AudioEchoConverter\n",
Expand Down Expand Up @@ -113,42 +113,43 @@
"69 text text NegationTrapConverter\n",
"70 text text NoiseConverter\n",
"71 text text PersuasionConverter\n",
"72 text text PinyinConverter\n",
"73 text text PolicyPuppetryConverter\n",
"74 text text PromptTemplateConverter\n",
"75 text text PuzzledConverter\n",
"76 text text ROT13Converter\n",
"77 text text RandomCapitalLettersConverter\n",
"78 text text RandomTranslationConverter\n",
"79 text text RepeatTokenConverter\n",
"80 text text RolePlayToolCallConverter\n",
"81 text text SATAMaskingConverter\n",
"82 text text ScientificTranslationConverter\n",
"83 text text SearchReplaceConverter\n",
"84 text text SelectiveTextConverter\n",
"85 text text SneakyBitsSmugglerConverter\n",
"86 text text StringJoinConverter\n",
"87 text text SuffixAppendConverter\n",
"88 text text SuperscriptConverter\n",
"89 text text TaskFramingConverter\n",
"90 text text TatweelConverter\n",
"91 text text TemplateSegmentConverter\n",
"92 text text TenseConverter\n",
"93 text text TextJailbreakConverter\n",
"94 text text TokenBijectionConverter\n",
"95 text text ToneConverter\n",
"96 text text ToxicSentenceGeneratorConverter\n",
"97 text text TranslationConverter\n",
"98 text text UnicodeConfusableConverter\n",
"99 text text UnicodeReplacementConverter\n",
"100 text text UnicodeSubstitutionConverter\n",
"101 text text UrlConverter\n",
"102 text text VariationConverter\n",
"103 text text VariationSelectorSmugglerConverter\n",
"104 text text VigenereConverter\n",
"105 text text ZalgoConverter\n",
"106 text text ZeroWidthConverter\n",
""
"72 text text PigpenConverter\n",
"73 text text PinyinConverter\n",
"74 text text PolicyPuppetryConverter\n",
"75 text text PromptTemplateConverter\n",
"76 text text PuzzledConverter\n",
"77 text text ROT13Converter\n",
"78 text text RandomCapitalLettersConverter\n",
"79 text text RandomTranslationConverter\n",
"80 text text RepeatTokenConverter\n",
"81 text text RolePlayToolCallConverter\n",
"82 text text SATAMaskingConverter\n",
"83 text text ScientificTranslationConverter\n",
"84 text text SearchReplaceConverter\n",
"85 text text SelectiveTextConverter\n",
"86 text text SneakyBitsSmugglerConverter\n",
"87 text text StringJoinConverter\n",
"88 text text SuffixAppendConverter\n",
"89 text text SuperscriptConverter\n",
"90 text text TapCodeConverter\n",
"91 text text TaskFramingConverter\n",
"92 text text TatweelConverter\n",
"93 text text TemplateSegmentConverter\n",
"94 text text TenseConverter\n",
"95 text text TextJailbreakConverter\n",
"96 text text TokenBijectionConverter\n",
"97 text text ToneConverter\n",
"98 text text ToxicSentenceGeneratorConverter\n",
"99 text text TranslationConverter\n",
"100 text text UnicodeConfusableConverter\n",
"101 text text UnicodeReplacementConverter\n",
"102 text text UnicodeSubstitutionConverter\n",
"103 text text UrlConverter\n",
"104 text text VariationConverter\n",
"105 text text VariationSelectorSmugglerConverter\n",
"106 text text VigenereConverter\n",
"107 text text ZalgoConverter\n",
"108 text text ZeroWidthConverter\n"
]
}
],
Expand Down
3 changes: 3 additions & 0 deletions doc/code/converters/1_text_to_text_converters.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@
"ROT13: text: gryy zr ubj gb phg qbja n gerr\n",
"Base64: text: dGVsbCBtZSBob3cgdG8gY3V0IGRvd24gYSB0cmVl\n",
"Base2048: text: ԽțƘΕฦ৩ଌဦǃଞ൪ഹыŁ৷ဦԊÕϐ࿌Dzȥ\n",
"Tap code: text: .... .... . ..... ... . ... . ... .. . ..... .. ... ... .... ..... .. .... .... ... .... . ... .... ..... .... .... . .... ... .... ..... .. ... ... . . .... .... .... .. . ..... . .....\n",
"Binary: text: 0000000001110100 0000000001100101 0000000001101100 0000000001101100 0000000000100000 0000000001101101 0000000001100101 0000000000100000 0000000001101000 0000000001101111 0000000001110111 0000000000100000 0000000001110100 0000000001101111 0000000000100000 0000000001100011 0000000001110101 0000000001110100 0000000000100000 0000000001100100 0000000001101111 0000000001110111 0000000001101110 0000000000100000 0000000001100001 0000000000100000 0000000001110100 0000000001110010 0000000001100101 0000000001100101\n",
"BinAscii: text: 74656C6C206D6520686F7720746F2063757420646F776E20612074726565\n",
"Morse: text: - . .-.. .-.. / -- . / .... --- .-- / - --- / -.-. ..- - / -.. --- .-- -. / .- / - .-. . .\n",
Expand Down Expand Up @@ -129,6 +130,7 @@
" NatoConverter,\n",
" NegationTrapConverter,\n",
" ROT13Converter,\n",
" TapCodeConverter,\n",
" TokenBijectionConverter,\n",
" VigenereConverter,\n",
")\n",
Expand All @@ -148,6 +150,7 @@
"print(\"ROT13:\", await ROT13Converter().convert_async(prompt=prompt)) # type: ignore\n",
"print(\"Base64:\", await Base64Converter().convert_async(prompt=prompt)) # type: ignore\n",
"print(\"Base2048:\", await Base2048Converter().convert_async(prompt=prompt)) # type: ignore\n",
"print(\"Tap code:\", await TapCodeConverter().convert_async(prompt=prompt)) # type: ignore\n",
"print(\"Binary:\", await BinaryConverter().convert_async(prompt=prompt)) # type: ignore\n",
"print(\"BinAscii:\", await BinAsciiConverter().convert_async(prompt=prompt)) # type: ignore\n",
"print(\"Morse:\", await MorseConverter().convert_async(prompt=prompt)) # type: ignore\n",
Expand Down
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
Comment thread
romanlutz marked this conversation as resolved.
Resolved
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
4 changes: 2 additions & 2 deletions doc/scanner/garak.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -303,9 +303,9 @@
"pyrit_scan run garak.encoding --target openai_chat --techniques base64 --max-total 1\n",
"```\n",
"\n",
"**Available techniques** (22 encodings): Base64, Base2048, Base16, Base32, ASCII85, Hex,\n",
"**Available techniques** (23 encodings): Base64, Base2048, Base16, Base32, ASCII85, Hex,\n",
"QuotedPrintable, UUencode, ROT13, Braille, Atbash, MorseCode, NATO, Ecoji, Zalgo, LeetSpeak,\n",
"AsciiSmuggler, Bifid, ColumnarTransposition, UbbiDubbi, Disemvowel, Pigpen\n",
"AsciiSmuggler, Bifid, ColumnarTransposition, UbbiDubbi, Disemvowel, Pigpen, TapCode\n",
"\n",
"**Aggregate techniques:** `ALL` (every encoding, exhaustive) and `DEFAULT` (a broad curated subset\n",
"spanning every encoding family — base-N, byte-encodings, substitution ciphers, and symbolic\n",
Expand Down
4 changes: 2 additions & 2 deletions doc/scanner/garak.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,9 +136,9 @@
# pyrit_scan run garak.encoding --target openai_chat --techniques base64 --max-total 1
# ```
#
# **Available techniques** (22 encodings): Base64, Base2048, Base16, Base32, ASCII85, Hex,
# **Available techniques** (23 encodings): Base64, Base2048, Base16, Base32, ASCII85, Hex,
# QuotedPrintable, UUencode, ROT13, Braille, Atbash, MorseCode, NATO, Ecoji, Zalgo, LeetSpeak,
# AsciiSmuggler, Bifid, ColumnarTransposition, UbbiDubbi, Disemvowel, Pigpen
# AsciiSmuggler, Bifid, ColumnarTransposition, UbbiDubbi, Disemvowel, Pigpen, TapCode
#
# **Aggregate techniques:** `ALL` (every encoding, exhaustive) and `DEFAULT` (a broad curated subset
# spanning every encoding family — base-N, byte-encodings, substitution ciphers, and symbolic
Expand Down
2 changes: 2 additions & 0 deletions pyrit/converter/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,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 @@ -254,6 +255,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
125 changes: 125 additions & 0 deletions pyrit/converter/tap_code_converter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.


from pyrit.converter.converter import Converter, ConverterResult
from pyrit.models import 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"

# The rendering is fixed so the output is uniquely decodable: a single tap symbol, a single space
# between the row-tap and column-tap group of a letter, and two spaces between letters.
_TAP_SYMBOL = "."
_GROUP_SEPARATOR = " "
_LETTER_SEPARATOR = " "

def __init__(self) -> None:
"""Initialize the converter and precompute the tap-code coordinate of each letter."""
# 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"]
Comment thread
romanlutz marked this conversation as resolved.
Resolved

@classmethod
def to_ascii_equivalent(cls, *, text: str) -> str:
"""
Return ``text`` with every ``K`` folded to ``C`` to match what a faithful tap-code decode yields.

The grid has no cell for ``K`` (it shares ``C``'s cell), so a target that decodes the taps correctly
answers with ``C`` wherever the seed had ``K``. The Encoding scenario attaches this value to the seed
copies as ``decoded_text`` so ``DecodingScorer`` accepts the correct decode instead of failing it.

Args:
text (str): The original seed text.

Returns:
str: ``text`` with ``K``/``k`` replaced by ``C``/``c``.
"""
return text.replace("K", "C").replace("k", "c")

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 a single
space; encoded letters are joined by two spaces. 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:
# Only ASCII letters have a tap-code cell. Guarding on ``isascii`` before uppercasing keeps
# non-ASCII characters whose upper-case form is an ASCII letter (e.g. Turkish ``ı`` -> ``I``,
# ``ſ`` -> ``S``) in the verbatim branch, so multilingual prompts are not silently re-encoded.
coordinate = self._coordinates.get(char.upper()) if char.isascii() else None
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 @@ -25,6 +25,7 @@
PigpenConverter,
ROT13Converter,
SearchReplaceConverter,
TapCodeConverter,
ZalgoConverter,
)
from pyrit.executor.attack import AttackConverterConfig, AttackScoringConfig, PromptSendingAttack
Expand Down Expand Up @@ -131,6 +132,7 @@ class EncodingTechnique(ScenarioTechnique):
AsciiSmuggler = ("ascii_smuggler", set[str]())
Bifid = ("bifid", set[str]())
ColumnarTransposition = ("columnar_transposition", set[str]())
TapCode = ("tap_code", set[str]())
Comment thread
romanlutz marked this conversation as resolved.
Resolved
Pigpen = ("pigpen", set[str]())
Disemvowel = ("disemvowel", set[str]())
UbbiDubbi = ("ubbi_dubbi", set[str]())
Expand Down Expand Up @@ -322,6 +324,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"),
([PigpenConverter()], "pigpen", "pigpen"),
# "disemvowel": remove all vowels ("disemvoweling"), a comment-moderation technique
# popularized on the Making Light blog (https://nielsenhayden.com/makinglight/).
Expand Down
Loading
Loading