Repository navigation
FEAT: Add PigpenConverter on a shared character-substitution base #4446
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Roman Lutz (romanlutz)
wants to merge
7
commits into
microsoft:main
Choose a base branch
from
romanlutz:gap1-pigpen
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+289
−79
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
194134a
FEAT: Add pigpen Encoding technique via LeetspeakConverter
romanlutz b5c2cc7
Merge latest main into gap1-pigpen
romanlutz 07a661e
FIX: Correct the Pigpen glyph table to match the cipher key
romanlutz e97c8b4
Merge remote-tracking branch 'origin/main' into gap1-pigpen
romanlutz bebf87a
DOC: Update garak scanner technique list to 20 (add Columnar, Pigpen)
romanlutz 18f20c6
Merge remote-tracking branch 'origin/main' into gap1-pigpen
romanlutz 286e88a
REFACTOR: Add PigpenConverter on a shared character-substitution base
romanlutz File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,106 @@ | ||
| # Copyright (c) Microsoft Corporation. | ||
| # Licensed under the MIT license. | ||
|
|
||
| from pyrit.converter.text_selection_strategy import WordSelectionStrategy | ||
| from pyrit.converter.word_level_converter import WordLevelConverter | ||
|
|
||
|
|
||
| class _CharacterSubstitutionConverter(WordLevelConverter): | ||
| """ | ||
| Shared base for converters that replace each character with fixed replacement(s). | ||
|
|
||
| A substitution table maps a (case-folded) character to a non-empty list of replacement strings. | ||
| In deterministic mode the first replacement is always used; otherwise one is chosen at random. | ||
| Characters absent from the table are left unchanged. Word selection is inherited from | ||
| ``WordLevelConverter``. | ||
|
|
||
| Members of this family are ``LeetspeakConverter`` (look-alike leet glyphs) and | ||
| ``PigpenConverter`` (Pigpen cipher glyphs). This base is intentionally *not* for whole-string | ||
| transforms (e.g. mirror/upside-down, which also reverse the text). | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| *, | ||
| substitutions: dict[str, list[str]], | ||
| deterministic: bool = True, | ||
| word_selection_strategy: WordSelectionStrategy | None = None, | ||
| ) -> None: | ||
| """ | ||
| Initialize the converter. | ||
|
|
||
| Args: | ||
| substitutions (dict[str, list[str]]): Map of single characters to a non-empty list of | ||
| replacement strings. Assumed already validated/normalized by the subclass. | ||
| deterministic (bool): If True, always use the first replacement for each character; | ||
| if False, choose one at random. | ||
| word_selection_strategy (WordSelectionStrategy | None): Strategy for selecting which words | ||
| to convert. If None, all words are converted. | ||
| """ | ||
| super().__init__(word_selection_strategy=word_selection_strategy) | ||
| self._substitutions = substitutions | ||
| self._deterministic = deterministic | ||
|
|
||
| @staticmethod | ||
| def _validate_substitutions( | ||
| substitutions: dict[str, list[str]], *, param_name: str = "substitutions" | ||
| ) -> dict[str, list[str]]: | ||
| """ | ||
| Validate a substitution table and key it by lowercase character. | ||
|
|
||
| ``convert_word_async`` looks characters up in lowercase, so an uppercase or multi-character | ||
| key would never match, and an empty replacement list would fail on the first matching character. | ||
|
|
||
| Args: | ||
| substitutions (dict[str, list[str]]): The substitution table to validate. | ||
| param_name (str): Name used in error messages (e.g. ``"custom_substitutions"``). | ||
|
|
||
| Returns: | ||
| dict[str, list[str]]: The substitutions keyed by lowercase character. | ||
|
|
||
| Raises: | ||
| ValueError: If a key is not a single character, two keys differ only in case, or a value | ||
| is not a non-empty list of strings. | ||
| """ | ||
| normalized: dict[str, list[str]] = {} | ||
| for char, replacements in substitutions.items(): | ||
| if not isinstance(char, str) or len(char) != 1: | ||
| raise ValueError(f"{param_name} keys must be single characters, got {char!r}.") | ||
| if ( | ||
| not isinstance(replacements, list) | ||
| or not replacements | ||
| or not all(isinstance(replacement, str) for replacement in replacements) | ||
| ): | ||
| raise ValueError(f"{param_name}[{char!r}] must be a non-empty list of strings, got {replacements!r}.") | ||
| lower_char = char.lower() | ||
| if lower_char in normalized: | ||
| raise ValueError(f"{param_name} has more than one key for {lower_char!r}.") | ||
| normalized[lower_char] = list(replacements) | ||
| return normalized | ||
|
|
||
| def _substitute_word(self, word: str) -> str: | ||
| """ | ||
| Substitute each character in a word per the table. | ||
|
|
||
| Concrete subclasses call this from ``convert_word_async``. This class stays abstract (it does | ||
| not implement ``convert_word_async``) so only the named members (Leetspeak, Pigpen) are | ||
| discoverable converters. | ||
|
|
||
| Args: | ||
| word (str): The word to be converted. | ||
|
|
||
| Returns: | ||
| str: The converted word. | ||
| """ | ||
| converted_word = [] | ||
| rng = self._get_random_generator(stream="character-substitutions") | ||
| for char in word: | ||
| lower_char = char.lower() | ||
| if lower_char in self._substitutions: | ||
| if self._deterministic: | ||
| converted_word.append(self._substitutions[lower_char][0]) | ||
| else: | ||
| converted_word.append(rng.choice(self._substitutions[lower_char])) | ||
| else: | ||
| converted_word.append(char) | ||
| return "".join(converted_word) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| # Copyright (c) Microsoft Corporation. | ||
| # Licensed under the MIT license. | ||
|
|
||
| from pyrit.converter._character_substitution_converter import _CharacterSubstitutionConverter | ||
| from pyrit.converter.text_selection_strategy import WordSelectionStrategy | ||
|
|
||
| # Pigpen (Freemason's / Masonic) cipher: a geometric monoalphabetic substitution of the Latin | ||
| # alphabet; see https://en.wikipedia.org/wiki/Pigpen_cipher . Framing classical ciphers as an | ||
| # LLM jailbreak vector: CipherChat (Yuan et al., 2023, arXiv:2308.06463). | ||
| # | ||
| # Each glyph is the shape the key draws around that letter's grid cell: the tic-tac-toe grid for | ||
| # A-I, the same with a dot for J-R, the saltire (X) for S-V, and the same with a dot for W-Z. | ||
| # Base glyphs are written as explicit code points so each can be checked against its Unicode name. | ||
| _DOT = "̇" # COMBINING DOT ABOVE | ||
| _BASE_GLYPHS = { | ||
| "a": "┘", # ┘ BOX DRAWINGS LIGHT UP AND LEFT | ||
| "b": "⊔", # ⊔ SQUARE CUP | ||
| "c": "└", # └ BOX DRAWINGS LIGHT UP AND RIGHT | ||
| "d": "⊐", # ⊐ SQUARE ORIGINAL OF | ||
| "e": "□", # □ WHITE SQUARE | ||
| "f": "⊏", # ⊏ SQUARE IMAGE OF | ||
| "g": "┐", # ┐ BOX DRAWINGS LIGHT DOWN AND LEFT | ||
| "h": "⊓", # ⊓ SQUARE CAP | ||
| "i": "┌", # ┌ BOX DRAWINGS LIGHT DOWN AND RIGHT | ||
| "s": "▽", # ▽ WHITE DOWN-POINTING TRIANGLE | ||
| "t": "▷", # ▷ WHITE RIGHT-POINTING TRIANGLE | ||
| "u": "◁", # ◁ WHITE LEFT-POINTING TRIANGLE | ||
| "v": "△", # △ WHITE UP-POINTING TRIANGLE | ||
| } | ||
|
|
||
|
|
||
| def _build_pigpen_substitutions() -> dict[str, list[str]]: | ||
| """ | ||
| Build the full A-Z Pigpen table: A-I/S-V as-is, J-R/W-Z the same glyphs with a combining dot. | ||
|
|
||
| Returns: | ||
| dict[str, list[str]]: The Pigpen substitution table keyed by lowercase letter. | ||
| """ | ||
| table = {letter: [glyph] for letter, glyph in _BASE_GLYPHS.items()} | ||
| # J-R repeat the A-I glyphs with the dot; W-Z repeat the S-V glyphs with the dot. | ||
| table.update({chr(ord("j") + i): [_BASE_GLYPHS[chr(ord("a") + i)] + _DOT] for i in range(9)}) | ||
| table.update({chr(ord("w") + i): [_BASE_GLYPHS[chr(ord("s") + i)] + _DOT] for i in range(4)}) | ||
| return table | ||
|
|
||
|
|
||
| _PIGPEN_SUBSTITUTIONS = _build_pigpen_substitutions() | ||
|
|
||
|
|
||
| class PigpenConverter(_CharacterSubstitutionConverter): | ||
| """ | ||
| Encodes text with the Pigpen (Freemason's / Masonic) cipher. | ||
|
|
||
| Pigpen is a geometric monoalphabetic substitution: each letter becomes the fragment of the grid | ||
| that surrounds its cell. This is the geometric member of the character-substitution family | ||
| (see ``_CharacterSubstitutionConverter``); like Leetspeak it is case-folding and not reversible | ||
| (``Hello`` and ``hello`` encode identically). | ||
| """ | ||
|
|
||
| def __init__(self, *, word_selection_strategy: WordSelectionStrategy | None = None) -> None: | ||
| """ | ||
| Initialize the converter. | ||
|
|
||
| Args: | ||
| word_selection_strategy (WordSelectionStrategy | None): Strategy for selecting which words | ||
| to convert. If None, all words are converted. | ||
| """ | ||
| super().__init__( | ||
| substitutions=_PIGPEN_SUBSTITUTIONS, | ||
| deterministic=True, | ||
| word_selection_strategy=word_selection_strategy, | ||
| ) | ||
|
|
||
| async def convert_word_async(self, word: str) -> str: | ||
| """ | ||
| Convert a single word into Pigpen glyphs. | ||
|
|
||
| Args: | ||
| word (str): The word to be converted. | ||
|
|
||
| Returns: | ||
| str: The converted word. | ||
| """ | ||
| return self._substitute_word(word) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[P3] Refresh the published converter modality table
Please refresh the saved Converter Modality Reference Table in
doc/code/converters/0_converters.ipynbto includePigpenConverteras text-to-text. That published table says it lists all converters but still skips from Persuasion to Pinyin. The converter instructions require this update; the paired Python source already generates the table dynamically, so keep its source cells synchronized without adding a second catalog or example.