Skip to content
72 changes: 37 additions & 35 deletions doc/code/converters/0_converters.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -113,41 +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 PolybiusConverter\n",
"76 text text PromptTemplateConverter\n",
"77 text text PuzzledConverter\n",
"78 text text ROT13Converter\n",
"79 text text RandomCapitalLettersConverter\n",
"80 text text RandomTranslationConverter\n",
"81 text text RepeatTokenConverter\n",
"82 text text RolePlayToolCallConverter\n",
"83 text text SATAMaskingConverter\n",
"84 text text ScientificTranslationConverter\n",
"85 text text SearchReplaceConverter\n",
"86 text text SelectiveTextConverter\n",
"87 text text SneakyBitsSmugglerConverter\n",
"88 text text StringJoinConverter\n",
"89 text text SuffixAppendConverter\n",
"90 text text SuperscriptConverter\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",
"Polybius: text: 44 15 31 31 / 32 15 / 23 34 52 / 44 34 / 13 45 44 / 14 34 52 33 / 11 / 44 42 15 15\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 @@ -128,6 +129,7 @@
" MorseConverter,\n",
" NatoConverter,\n",
" NegationTrapConverter,\n",
" PolybiusConverter,\n",
" ROT13Converter,\n",
" TokenBijectionConverter,\n",
" VigenereConverter,\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(\"Polybius:\", await PolybiusConverter().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 @@ -64,6 +64,7 @@
MorseConverter,
NatoConverter,
NegationTrapConverter,
PolybiusConverter,
ROT13Converter,
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("Polybius:", await PolybiusConverter().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, Polybius, UbbiDubbi, Disemvowel, Pigpen\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, Polybius, UbbiDubbi, Disemvowel, Pigpen
#
# **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 @@ -94,6 +94,7 @@
from pyrit.converter.pigpen_converter import PigpenConverter
from pyrit.converter.pinyin_converter import PinyinConverter
from pyrit.converter.policy_puppetry_converter import PolicyPuppetryConverter, PolicyPuppetryTemplate
from pyrit.converter.polybius_converter import PolybiusConverter
from pyrit.converter.prompt_template_converter import PromptTemplateConverter
from pyrit.converter.puzzled import PuzzledConverter, PuzzleType
from pyrit.converter.qr_code_converter import QRCodeConverter
Expand Down Expand Up @@ -231,6 +232,7 @@
"PinyinConverter": "pyrit.converter.pinyin_converter",
"PolicyPuppetryConverter": "pyrit.converter.policy_puppetry_converter",
"PolicyPuppetryTemplate": "pyrit.converter.policy_puppetry_converter",
"PolybiusConverter": "pyrit.converter.polybius_converter",
"PositionSelectionStrategy": "pyrit.converter.text_selection_strategy",
"PromptTemplateConverter": "pyrit.converter.prompt_template_converter",
"Converter": "pyrit.converter.converter",
Expand Down
102 changes: 102 additions & 0 deletions pyrit/converter/polybius_converter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.

from pyrit.converter.word_level_converter import WordLevelConverter

_SQUARE = "ABCDEFGHIKLMNOPQRSTUVWXYZ" # 25 letters, I/J merged (no J)


class PolybiusConverter(WordLevelConverter):
"""
Encodes text using the Polybius square.

The Polybius square is a classical cipher that maps each letter of the alphabet to a
pair of coordinates (row, column) on a 5x5 grid. Because the Latin alphabet has 26
letters but the grid holds only 25 cells, ``I`` and ``J`` are merged into a single cell
(any ``J`` is treated as ``I``). The standard square is::

1 2 3 4 5
1 A B C D E
2 F G H I K (J shares I's cell)
3 L M N O P
4 Q R S T U
5 V W X Y Z

With this square ``A`` encodes to ``11``, ``B`` to ``12``, ``I`` (and ``J``) to ``24``,
and ``Z`` to ``55``. Each ASCII letter is replaced by its two-digit coordinate pair and the
pairs within a word are separated by a single space. A non-letter character (digit,
punctuation, non-ASCII letter) is emitted as its own space-separated token, and word
boundaries are written as ``/`` so that the words and any literal digits stay distinct from
the coordinate pairs (``"AB CD"`` gives ``11 12 / 13 14`` while ``"ABCD"`` gives
``11 12 13 14``). Encoding is case-insensitive.

Reference: https://en.wikipedia.org/wiki/Polybius_square (public domain cipher).

Like other classical cipher converters, this is useful for probing whether a model will
decode and act on obfuscated content, following the cipher-based jailbreak framing of
CipherChat ("GPT-4 Is Too Smart To Be Safe", Yuan et al., arXiv:2308.06463).
"""

SUPPORTED_INPUT_TYPES = ("text",)
SUPPORTED_OUTPUT_TYPES = ("text",)

_WORD_SEPARATOR = "/"

# Each letter -> its two-digit (row, column) coordinate on the 5x5 square; J shares I's cell.
_ENCODING = {letter: f"{index // 5 + 1}{index % 5 + 1}" for index, letter in enumerate(_SQUARE)}
_ENCODING["J"] = _ENCODING["I"]

async def convert_word_async(self, word: str) -> str:
"""
Convert one word into Polybius square coordinates.

Each ASCII letter becomes its two-digit coordinate pair; every other character (digit,
punctuation, non-ASCII letter) passes through unchanged. Tokens are separated by a single
space so that letters, literal digits, and coordinate pairs stay distinguishable.

Args:
word (str): The word to convert.

Returns:
str: The converted word, with per-character tokens separated by spaces.
"""
output = [self._ENCODING.get(char.upper(), char) if char.isascii() else char for char in word]
return " ".join(output)

def join_words(self, words: list[str]) -> str:
"""
Join converted words while preserving every source-space boundary.

Args:
words (list[str]): The converted words.

Returns:
str: The converted words separated by explicit ``/`` word tokens.
"""
output: list[str] = []
for index, word in enumerate(words):
if index:
output.append(self._WORD_SEPARATOR)
if word:
output.append(word)

return " ".join(output)

@classmethod
def to_ascii_equivalent(cls, *, text: str) -> str | None:
"""
Return the text a target reconstructs when it decodes the square correctly.

Because ``J`` shares ``I``'s cell, a correctly decoded prompt answers with ``I`` for each
``J``. The Encoding scenario feeds this value to ``DecodingScorer`` as ``decoded_text`` so a
seed containing ``J`` can still score true.

Args:
text (str): The original (pre-encoding) seed text.

Returns:
str | None: ``text`` with ``J``/``j`` folded to ``I``/``i``, or ``None`` when the text
contains no ``J`` and nothing changes.
"""
folded = text.replace("J", "I").replace("j", "i")
return folded if folded != text else None
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,
PigpenConverter,
PolybiusConverter,
ROT13Converter,
SearchReplaceConverter,
ZalgoConverter,
Expand Down Expand Up @@ -132,6 +133,7 @@ class EncodingTechnique(ScenarioTechnique):
Bifid = ("bifid", set[str]())
ColumnarTransposition = ("columnar_transposition", set[str]())
Pigpen = ("pigpen", set[str]())
Polybius = ("polybius", set[str]())
Comment thread
romanlutz marked this conversation as resolved.
Resolved
Disemvowel = ("disemvowel", set[str]())
UbbiDubbi = ("ubbi_dubbi", set[str]())

Expand Down Expand Up @@ -323,6 +325,7 @@ def _converter_variants() -> list[tuple[list[Converter], str, str]]:
([BifidConverter()], "bifid", "bifid"),
([ColumnarTranspositionConverter(key="ZEBRAS")], "columnar_transposition", "columnar_transposition"),
([PigpenConverter()], "pigpen", "pigpen"),
([PolybiusConverter()], "polybius", "polybius"),
# "disemvowel": remove all vowels ("disemvoweling"), a comment-moderation technique
# popularized on the Making Light blog (https://nielsenhayden.com/makinglight/).
([SearchReplaceConverter(pattern="[AEIOUaeiou]", replace="")], "disemvowel", "disemvowel"),
Expand Down
Loading
Loading