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 @@ -64,6 +64,7 @@
MorseConverter,
NatoConverter,
NegationTrapConverter,
RailFenceConverter,
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("Rail fence:", await RailFenceConverter().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 @@ -94,6 +94,7 @@
from pyrit.converter.prompt_template_converter import PromptTemplateConverter
from pyrit.converter.puzzled import PuzzledConverter, PuzzleType
from pyrit.converter.qr_code_converter import QRCodeConverter
from pyrit.converter.rail_fence_converter import RailFenceConverter
from pyrit.converter.random_capital_letters_converter import RandomCapitalLettersConverter
from pyrit.converter.random_translation_converter import RandomTranslationConverter
from pyrit.converter.repeat_token_converter import RepeatTokenConverter
Expand Down Expand Up @@ -232,6 +233,7 @@
"PuzzleType": "pyrit.converter.puzzled",
"PuzzledConverter": "pyrit.converter.puzzled",
"QRCodeConverter": "pyrit.converter.qr_code_converter",
"RailFenceConverter": "pyrit.converter.rail_fence_converter",
"ROT13Converter": "pyrit.converter.rot13_converter",
"RandomCapitalLettersConverter": "pyrit.converter.random_capital_letters_converter",
"RandomTranslationConverter": "pyrit.converter.random_translation_converter",
Expand Down
97 changes: 97 additions & 0 deletions pyrit/converter/rail_fence_converter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.

from pyrit.converter.converter import Converter, ConverterResult
from pyrit.models import ComponentIdentifier, PromptDataType


class RailFenceConverter(Converter):
"""
Encodes text using the Rail Fence transposition cipher with a configurable number of rails.

The Rail Fence cipher writes the plaintext downward and diagonally across a number of
successive "rails" of an imaginary fence, bouncing up and down between the top and bottom
rails, then reads the ciphertext off row by row. For example, with ``rails=3`` the text
'WEAREDISCOVEREDFLEEATONCE' is laid out as::

W . . . E . . . C . . . R . . . L . . . T . . . E
. E . R . D . S . O . E . E . F . E . A . O . C .
. . A . . . I . . . V . . . D . . . E . . . N . .

and read off by row to produce 'WECRLTEERDSOEEFEAOCAIVDEN'. Every character (including
spaces, digits, and punctuation) participates in the zigzag, so the transformation is a
pure permutation of the input and is fully reversible given the number of rails.

References:
Rail Fence cipher (public domain classical cipher):
https://en.wikipedia.org/wiki/Rail_fence_cipher

CipherChat jailbreak framing (encoding harmful prompts with classical ciphers to
evade safety alignment): Yuan et al., "GPT-4 Is Too Smart To Be Safe: Stealthy Chat
with LLMs via Cipher", arXiv:2308.06463, https://arxiv.org/abs/2308.06463
"""

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

def __init__(self, *, rails: int = 3) -> None:
"""
Initialize the converter with a number of rails.

Args:
rails (int): The number of rails (rows) of the fence. Must be an integer greater
than or equal to 2. Defaults to 3.

Raises:
ValueError: If ``rails`` is less than 2.
"""
if rails < 2:
raise ValueError("rail fence rails value invalid, must be an integer greater than or equal to 2.")
self.rails = rails

def _build_identifier(self) -> ComponentIdentifier:
"""
Build the converter identifier with Rail Fence cipher parameters.

Returns:
ComponentIdentifier: The identifier for this converter.
"""
return self._create_identifier(
params={
"rails": self.rails,
},
)

async def convert_async(self, *, prompt: str, input_type: PromptDataType = "text") -> ConverterResult:
"""
Convert the given prompt using the Rail Fence cipher.

Args:
prompt (str): The input prompt to be converted.
input_type (PromptDataType): The type of the input prompt. Must be "text".

Returns:
ConverterResult: The result containing the converted prompt and its type.

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._rail_fence(prompt), output_type="text")

def _rail_fence(self, text: str) -> str:
# A single rail would leave the text unchanged; rails >= 2 is enforced in __init__.
rows: list[list[str]] = [[] for _ in range(self.rails)]
rail = 0
direction = 1
for char in text:
rows[rail].append(char)
# Reverse direction at the top and bottom rails so the path zigzags between them.
if rail == 0:
direction = 1
elif rail == self.rails - 1:
direction = -1
rail += direction
return "".join("".join(row) for row in rows)
3 changes: 3 additions & 0 deletions pyrit/scenario/scenarios/garak/encoding.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
LeetspeakConverter,
MorseConverter,
NatoConverter,
RailFenceConverter,
ROT13Converter,
ZalgoConverter,
)
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]())
RailFence = ("rail_fence", 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"),
([RailFenceConverter()], "rail_fence", "rail_fence"),
]

# These are the same as Garak encoding attacks
Expand Down
75 changes: 75 additions & 0 deletions tests/unit/converter/test_rail_fence_converter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.

import pytest

from pyrit.converter import ConverterResult, RailFenceConverter


async def test_rail_fence_converter_known_vector():
# Canonical Wikipedia Rail Fence example: 3 rails.
converter = RailFenceConverter(rails=3)
result = await converter.convert_async(prompt="WEAREDISCOVEREDFLEEATONCE", input_type="text")
assert isinstance(result, ConverterResult)
assert result.output_text == "WECRLTEERDSOEEFEAOCAIVDEN"
assert result.output_type == "text"


async def test_rail_fence_converter_two_rails():
# Two rails split into even-index characters followed by odd-index characters.
converter = RailFenceConverter(rails=2)
result = await converter.convert_async(prompt="WEAREDISCOVERED", input_type="text")
assert result.output_text == "WAEICVRDERDSOEE"


async def test_rail_fence_converter_default_rails_is_three():
converter = RailFenceConverter()
assert converter.rails == 3
result = await converter.convert_async(prompt="WEAREDISCOVEREDFLEEATONCE", input_type="text")
assert result.output_text == "WECRLTEERDSOEEFEAOCAIVDEN"


async def test_rail_fence_converter_preserves_all_characters():
converter = RailFenceConverter(rails=3)
prompt = "Hello, World! 123"
result = await converter.convert_async(prompt=prompt, input_type="text")
# A transposition cipher is a permutation: length is preserved and it is a rearrangement.
assert len(result.output_text) == len(prompt)
assert sorted(result.output_text) == sorted(prompt)


async def test_rail_fence_converter_more_rails_than_characters():
# With more rails than characters, no rail reaches the bottom, so output equals input.
converter = RailFenceConverter(rails=10)
result = await converter.convert_async(prompt="abc", input_type="text")
assert result.output_text == "abc"


async def test_rail_fence_converter_empty():
converter = RailFenceConverter(rails=3)
result = await converter.convert_async(prompt="", input_type="text")
assert isinstance(result, ConverterResult)
assert result.output_text == ""
assert result.output_type == "text"


def test_rail_fence_converter_invalid_rails_too_few():
with pytest.raises(ValueError, match="rail fence rails value invalid"):
RailFenceConverter(rails=1)


def test_rail_fence_converter_invalid_rails_zero():
with pytest.raises(ValueError, match="rail fence rails value invalid"):
RailFenceConverter(rails=0)


def test_rail_fence_converter_identifier_includes_rails():
converter = RailFenceConverter(rails=4)
identifier = converter.get_identifier()
assert identifier.params["rails"] == 4


async def test_rail_fence_converter_input_not_supported():
converter = RailFenceConverter(rails=3)
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",
"rail_fence",
}

def test_get_aggregate_tags_includes_default(self):
Expand Down
Loading