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
4 changes: 4 additions & 0 deletions doc/code/converters/1_text_to_text_converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@
AsciiArtConverter,
AskToDecodeConverter,
AtbashConverter,
Base58Converter,
Base62Converter,
Base64Converter,
Base2048Converter,
BifidConverter,
Expand Down Expand Up @@ -84,6 +86,8 @@
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("Base58:", await Base58Converter().convert_async(prompt=prompt)) # type: ignore
print("Base62:", await Base62Converter().convert_async(prompt=prompt)) # type: ignore
Comment on lines +89 to +90

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please also refresh the stored modality table in doc/code/converters/0_converters.ipynb when synchronizing the examples. The table says it lists all available converters, but its output jumps from Base2048Converter to Base64Converter and omits both new encoders. Both classes are exported and declare text input/output, so the existing get_converter_modalities() code already supplies the rows; no manual converter list is needed. .github/instructions/converters.instructions.md:112 requires this reference update. Keep the paired code synchronized and retain the new example and table outputs.

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: 4 additions & 0 deletions pyrit/converter/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@
from pyrit.converter.audio_white_noise_converter import AudioWhiteNoiseConverter
from pyrit.converter.azure_speech_audio_to_text_converter import AzureSpeechAudioToTextConverter
from pyrit.converter.azure_speech_text_to_audio_converter import AzureSpeechTextToAudioConverter
from pyrit.converter.base58_converter import Base58Converter
from pyrit.converter.base62_converter import Base62Converter
from pyrit.converter.base64_converter import Base64Converter
from pyrit.converter.base2048_converter import Base2048Converter
from pyrit.converter.bidi_converter import BidiConverter
Expand Down Expand Up @@ -169,6 +171,8 @@
"AzureSpeechAudioToTextConverter": "pyrit.converter.azure_speech_audio_to_text_converter",
"AzureSpeechTextToAudioConverter": "pyrit.converter.azure_speech_text_to_audio_converter",
"Base2048Converter": "pyrit.converter.base2048_converter",
"Base58Converter": "pyrit.converter.base58_converter",
"Base62Converter": "pyrit.converter.base62_converter",
"Base64Converter": "pyrit.converter.base64_converter",
"BidiConverter": "pyrit.converter.bidi_converter",
"BifidConverter": "pyrit.converter.bifid_converter",
Expand Down
50 changes: 50 additions & 0 deletions pyrit/converter/_base_n.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.

"""
Shared big-integer binary-to-text encoder for the Base-N converters (Base58, Base62).

Base58 and Base62 are not simple block transforms like Base64: the whole input is treated as a
single big-endian integer and repeatedly divided by the radix. Because that integer conversion
drops leading ``0x00`` bytes, each one is re-emitted as the first alphabet character so the
encoding round-trips losslessly. Both converters share this exact algorithm; only their alphabet
differs. Base91 uses a different bit-buffer algorithm and is intentionally not built on this.

This module is intentionally private (underscore prefix): it is an internal helper shared by the
base-N converters, not part of the public ``pyrit.converter`` API.
"""


def encode_base_n(data: bytes, *, alphabet: str) -> str:
"""
Encode bytes as a base-``len(alphabet)`` string using the big-integer scheme.

Args:
data (bytes): The bytes to encode.
alphabet (str): The ordered alphabet; its length is the radix and ``alphabet[0]`` is the
character used for leading zero bytes.

Returns:
str: The base-N encoded representation (empty string for empty input).
"""
if not data:
return ""

radix = len(alphabet)

# Each leading zero byte (which the big-integer conversion would drop) becomes alphabet[0].
leading_zeros = 0
for byte in data:
if byte == 0:
leading_zeros += 1
else:
break

value = int.from_bytes(data, byteorder="big")
digits: list[str] = []
while value > 0:
value, remainder = divmod(value, radix)
digits.append(alphabet[remainder])
digits.reverse()

return alphabet[0] * leading_zeros + "".join(digits)
109 changes: 109 additions & 0 deletions pyrit/converter/base58_converter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.

from typing import Literal

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

# Base58 alphabets. The default is the Bitcoin alphabet, which omits the four
# visually ambiguous characters 0 (zero), O (capital o), I (capital i) and
# l (lowercase L). The Flickr alphabet is the same 58 characters re-ordered so
# that lowercase letters precede uppercase letters.
# See: https://en.wikipedia.org/wiki/Binary-to-text_encoding#Base58 and the
# Bitcoin Base58Check reference (https://en.bitcoin.it/wiki/Base58Check_encoding).
_BITCOIN_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
_FLICKR_ALPHABET = "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"

_ALPHABETS: dict[str, str] = {
"bitcoin": _BITCOIN_ALPHABET,
"flickr": _FLICKR_ALPHABET,
}


class Base58Converter(Converter):
"""
Converter that encodes text to Base58 format.

Base58 is a binary-to-text encoding devised for Bitcoin addresses. It uses an
alphabet of 58 characters, chosen by omitting the four characters that are easy
to confuse visually (``0`` zero, ``O`` capital o, ``I`` capital i and ``l``
lowercase L) as well as the non-alphanumeric ``+`` and ``/`` used by Base64.
Unlike Base64, Base58 is not a simple block transform: the whole input is treated
as a single big-endian integer and repeatedly divided by 58, with each leading
zero byte rendered as the first alphabet character.

This implementation is pure Python (no third-party dependency). It supports the
default Bitcoin alphabet and the Flickr alphabet variant.

References:
- Bitcoin Base58Check encoding: https://en.bitcoin.it/wiki/Base58Check_encoding
- Binary-to-text encoding (Base58): https://en.wikipedia.org/wiki/Binary-to-text_encoding#Base58
"""

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

Alphabet = Literal["bitcoin", "flickr"]

def __init__(self, *, alphabet: Alphabet = "bitcoin") -> None:
"""
Initialize the Base58Converter.

Args:
alphabet: The Base58 alphabet to use, either ``"bitcoin"`` (default) or
``"flickr"``.

Raises:
ValueError: If an unsupported alphabet name is provided.
"""
if alphabet not in _ALPHABETS:
raise ValueError(f"Unsupported alphabet '{alphabet}'. Supported: {sorted(_ALPHABETS)}")
self._alphabet_name = alphabet
self._alphabet = _ALPHABETS[alphabet]

def _build_identifier(self) -> ComponentIdentifier:
"""
Build the converter identifier with the selected alphabet.

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

def _encode(self, data: bytes) -> str:
"""
Encode raw bytes to a Base58 string using the configured alphabet.

Args:
data: The bytes to encode.

Returns:
str: The Base58-encoded representation.
"""
return encode_base_n(data, alphabet=self._alphabet)

async def convert_async(self, *, prompt: str, input_type: PromptDataType = "text") -> ConverterResult:
"""
Convert the given prompt to Base58 encoding.

Args:
prompt: The prompt to be converted.
input_type: Type of data, unused for this converter.

Returns:
The converted text representation of the original prompt in Base58.

Raises:
ValueError: If the input type is not supported.
"""
if not self.input_supported(input_type):
raise ValueError("Input type not supported")

encoded = self._encode(prompt.encode("utf-8"))
return ConverterResult(output_text=encoded, output_type="text")
64 changes: 64 additions & 0 deletions pyrit/converter/base62_converter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.

from pyrit.converter._base_n import encode_base_n
from pyrit.converter.converter import Converter, ConverterResult
from pyrit.models import PromptDataType

# Base62 alphabet (0-9, A-Z, a-z). See https://en.wikipedia.org/wiki/Base62
# This is the most common ("GMP-style") ordering used by Base62 encoders.
_BASE62_ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"


class Base62Converter(Converter):
"""
Converter that encodes text to a Base62 string.

Base62 represents binary data using the 62 alphanumeric characters
(``0-9``, ``A-Z``, ``a-z``), avoiding the ``+``, ``/`` and ``=`` characters of
Base64. See https://en.wikipedia.org/wiki/Base62 for the scheme.

This implementation is pure Python (no third-party dependency). The UTF-8
bytes of the input are interpreted as a single big-endian integer and
repeatedly divided by 62 to produce digits in the alphabet
``0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`` (index 0
maps to ``"0"``, index 61 maps to ``"z"``). Because big-integer encoding does
not preserve leading zero bytes positionally, each leading ``0x00`` byte is
emitted as a leading ``"0"`` so that round-tripping is lossless.
"""

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

@staticmethod
def _encode(data: bytes) -> str:
"""
Encode raw bytes to a Base62 string.

Args:
data: The bytes to encode.

Returns:
The Base62 encoded string.
"""
return encode_base_n(data, alphabet=_BASE62_ALPHABET)

async def convert_async(self, *, prompt: str, input_type: PromptDataType = "text") -> ConverterResult:
"""
Convert the given prompt to a Base62 encoded string.

Args:
prompt: The prompt to be converted.
input_type: Type of data, must be "text".

Returns:
The Base62 encoded representation of the UTF-8 bytes 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")

encoded = self._encode(prompt.encode("utf-8"))
return ConverterResult(output_text=encoded, output_type="text")
6 changes: 6 additions & 0 deletions pyrit/scenario/scenarios/garak/encoding.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
AsciiSmugglerConverter,
AskToDecodeConverter,
AtbashConverter,
Base58Converter,
Base62Converter,
Base64Converter,
Base2048Converter,
BifidConverter,
Expand Down Expand Up @@ -128,6 +130,8 @@ class EncodingTechnique(ScenarioTechnique):
LeetSpeak = ("leet_speak", {"default"})
AsciiSmuggler = ("ascii_smuggler", set[str]())
Bifid = ("bifid", set[str]())
Base58 = ("base58", set[str]())
Base62 = ("base62", set[str]())
ColumnarTransposition = ("columnar_transposition", set[str]())

@classmethod
Expand Down Expand Up @@ -316,6 +320,8 @@ def _converter_variants() -> list[tuple[list[Converter], str, str]]:
([LeetspeakConverter()], "leet_speak", "leet_speak"),
([AsciiSmugglerConverter()], "ascii_smuggler", "ascii_smuggler"),
([BifidConverter()], "bifid", "bifid"),
([Base58Converter()], "base58", "base58"),
([Base62Converter()], "base62", "base62"),
([ColumnarTranspositionConverter(key="ZEBRAS")], "columnar_transposition", "columnar_transposition"),
]

Expand Down
87 changes: 87 additions & 0 deletions tests/unit/converter/test_base58_converter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.

import pytest

from pyrit.converter import Base58Converter, ConverterResult


async def test_base58_converter_default_known_vector():
# Well-known Base58 (Bitcoin alphabet) vector.
converter = Base58Converter()
result = await converter.convert_async(prompt="hello world", input_type="text")
assert isinstance(result, ConverterResult)
assert result.output_text == "StV1DL6CwTryKyV"
assert result.output_type == "text"


async def test_base58_converter_known_vector_with_punctuation():
converter = Base58Converter()
result = await converter.convert_async(prompt="Hello World!", input_type="text")
assert result.output_text == "2NEpo7TZRRrLZSi2U"


async def test_base58_converter_short_inputs():
converter = Base58Converter()
assert (await converter.convert_async(prompt="hello")).output_text == "Cn8eVZg"
assert (await converter.convert_async(prompt="a")).output_text == "2g"
assert (await converter.convert_async(prompt=" ")).output_text == "Z"


async def test_base58_converter_empty():
converter = Base58Converter()
result = await converter.convert_async(prompt="", input_type="text")
assert result.output_text == ""
assert result.output_type == "text"


async def test_base58_converter_leading_null_bytes_become_ones():
# A NUL byte encodes as the first alphabet character ("1"), not folded away.
converter = Base58Converter()
# "\x00" -> "1"; this exercises the leading-zero-byte branch.
result = await converter.convert_async(prompt="\x00")
assert result.output_text == "1"


async def test_base58_converter_flickr_alphabet():
converter = Base58Converter(alphabet="flickr")
result = await converter.convert_async(prompt="hello", input_type="text")
# Same integer as the Bitcoin "Cn8eVZg" but mapped through the Flickr ordering.
assert result.output_text == "cM8DuyF"


async def test_base58_converter_only_uses_alphabet_characters():
converter = Base58Converter()
alphabet = set("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")
result = await converter.convert_async(prompt="The quick brown fox jumps over the lazy dog.")
assert set(result.output_text) <= alphabet
# The ambiguous characters must never appear in the Bitcoin alphabet output.
assert not (set(result.output_text) & set("0OIl"))


def test_base58_converter_rejects_unknown_alphabet():
with pytest.raises(ValueError):
Base58Converter(alphabet="base64") # type: ignore[arg-type]


async def test_base58_converter_input_not_supported():
converter = Base58Converter()
with pytest.raises(ValueError):
await converter.convert_async(prompt="hello", input_type="image_path")


def test_base58_converter_input_supported():
converter = Base58Converter()
assert converter.input_supported("text") is True
assert converter.input_supported("image_path") is False


def test_base58_converter_output_supported():
converter = Base58Converter()
assert converter.output_supported("text") is True
assert converter.output_supported("image_path") is False


def test_base58_converter_identifier_includes_alphabet():
identifier = Base58Converter(alphabet="flickr").get_identifier()
assert identifier.params["alphabet"] == "flickr"
Loading
Loading