From 18aa91d4c70fdf50a0fa56ba3e20c2804618f68c Mon Sep 17 00:00:00 2001 From: Roman Lutz Date: Thu, 19 Nov 2026 15:38:44 -0800 Subject: [PATCH] FEAT: Add Base58/Base62 converters on a shared encode_base_n helper Adds Base58Converter and Base62Converter (pure-Python, no third-party dependency) built on a shared big-integer encode_base_n helper, registered as ALL-only garak Encoding techniques. Base91 stays separate (different bit-buffer algorithm). Co-Authored-By: Claude Opus 4.8 --- .../converters/1_text_to_text_converters.py | 4 + pyrit/converter/__init__.py | 4 + pyrit/converter/_base_n.py | 50 ++++++++ pyrit/converter/base58_converter.py | 109 ++++++++++++++++++ pyrit/converter/base62_converter.py | 64 ++++++++++ pyrit/scenario/scenarios/garak/encoding.py | 6 + tests/unit/converter/test_base58_converter.py | 87 ++++++++++++++ tests/unit/converter/test_base62_converter.py | 98 ++++++++++++++++ tests/unit/scenario/garak/test_encoding.py | 4 +- 9 files changed, 424 insertions(+), 2 deletions(-) create mode 100644 pyrit/converter/_base_n.py create mode 100644 pyrit/converter/base58_converter.py create mode 100644 pyrit/converter/base62_converter.py create mode 100644 tests/unit/converter/test_base58_converter.py create mode 100644 tests/unit/converter/test_base62_converter.py diff --git a/doc/code/converters/1_text_to_text_converters.py b/doc/code/converters/1_text_to_text_converters.py index 578a90c251..6743762ea0 100644 --- a/doc/code/converters/1_text_to_text_converters.py +++ b/doc/code/converters/1_text_to_text_converters.py @@ -50,6 +50,8 @@ AsciiArtConverter, AskToDecodeConverter, AtbashConverter, + Base58Converter, + Base62Converter, Base64Converter, Base2048Converter, BifidConverter, @@ -83,6 +85,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 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 diff --git a/pyrit/converter/__init__.py b/pyrit/converter/__init__.py index 1c8722e5b2..ac5f1b3b57 100644 --- a/pyrit/converter/__init__.py +++ b/pyrit/converter/__init__.py @@ -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 @@ -168,6 +170,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", diff --git a/pyrit/converter/_base_n.py b/pyrit/converter/_base_n.py new file mode 100644 index 0000000000..aa16f67832 --- /dev/null +++ b/pyrit/converter/_base_n.py @@ -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) diff --git a/pyrit/converter/base58_converter.py b/pyrit/converter/base58_converter.py new file mode 100644 index 0000000000..0bf3e6e907 --- /dev/null +++ b/pyrit/converter/base58_converter.py @@ -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") diff --git a/pyrit/converter/base62_converter.py b/pyrit/converter/base62_converter.py new file mode 100644 index 0000000000..fb019d86c6 --- /dev/null +++ b/pyrit/converter/base62_converter.py @@ -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") diff --git a/pyrit/scenario/scenarios/garak/encoding.py b/pyrit/scenario/scenarios/garak/encoding.py index 2540179e26..592129c551 100644 --- a/pyrit/scenario/scenarios/garak/encoding.py +++ b/pyrit/scenario/scenarios/garak/encoding.py @@ -11,6 +11,8 @@ AsciiSmugglerConverter, AskToDecodeConverter, AtbashConverter, + Base58Converter, + Base62Converter, Base64Converter, Base2048Converter, BifidConverter, @@ -127,6 +129,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]()) @classmethod def get_aggregate_tags(cls) -> set[str]: @@ -314,6 +318,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"), ] # These are the same as Garak encoding attacks diff --git a/tests/unit/converter/test_base58_converter.py b/tests/unit/converter/test_base58_converter.py new file mode 100644 index 0000000000..8349fca9c6 --- /dev/null +++ b/tests/unit/converter/test_base58_converter.py @@ -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" diff --git a/tests/unit/converter/test_base62_converter.py b/tests/unit/converter/test_base62_converter.py new file mode 100644 index 0000000000..32f04ddc75 --- /dev/null +++ b/tests/unit/converter/test_base62_converter.py @@ -0,0 +1,98 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import pytest + +from pyrit.converter import Base62Converter, ConverterResult + +_BASE62_ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + + +def _decode(encoded: str) -> bytes: + """Reference Base62 -> bytes decoder used to verify round-tripping.""" + if encoded == "": + return b"" + leading_zeros = 0 + for char in encoded: + if char == _BASE62_ALPHABET[0]: + leading_zeros += 1 + else: + break + number = 0 + for char in encoded[leading_zeros:]: + number = number * 62 + _BASE62_ALPHABET.index(char) + body = number.to_bytes((number.bit_length() + 7) // 8, "big") if number else b"" + return b"\x00" * leading_zeros + body + + +@pytest.mark.parametrize( + "plaintext, expected", + [ + ("hello", "7tQLFHz"), + ("hi", "6x7"), + ("A", "13"), + ("Hello, World!", "1wJfrzvdbtXUOlUjUf"), + ], +) +async def test_base62_converter_known_vectors(plaintext, expected): + converter = Base62Converter() + result = await converter.convert_async(prompt=plaintext, input_type="text") + assert isinstance(result, ConverterResult) + assert result.output_text == expected + assert result.output_type == "text" + + +async def test_base62_converter_empty(): + converter = Base62Converter() + result = await converter.convert_async(prompt="", input_type="text") + assert result.output_text == "" + + +async def test_base62_converter_only_alphanumeric_chars(): + converter = Base62Converter() + result = await converter.convert_async(prompt="The quick brown fox 123!@#", input_type="text") + assert all(char in _BASE62_ALPHABET for char in result.output_text) + + +@pytest.mark.parametrize( + "plaintext", + [ + "hello", + "A", + "Hello, World!", + "unicode: éà你好 \U0001f600", + "\x00leading null", + "trailing null\x00", + ], +) +async def test_base62_converter_round_trip(plaintext): + converter = Base62Converter() + result = await converter.convert_async(prompt=plaintext, input_type="text") + assert _decode(result.output_text).decode("utf-8") == plaintext + + +async def test_base62_converter_leading_null_bytes_preserved(): + # int.from_bytes drops leading zero bytes; the converter re-adds them as leading "0"s. + converter = Base62Converter() + # "\x00\x00A" -> two leading zeros ("00") + encoding of 0x41 ("13"). + result = await converter.convert_async(prompt="\x00\x00A", input_type="text") + assert result.output_text == "0013" + assert _decode(result.output_text) == b"\x00\x00A" + + +async def test_base62_converter_input_not_supported(): + converter = Base62Converter() + with pytest.raises(ValueError): + await converter.convert_async(prompt="hello", input_type="image_path") + + +def test_base62_converter_input_supported(): + converter = Base62Converter() + assert converter.input_supported("text") is True + assert converter.input_supported("image_path") is False + + +def test_base62_converter_output_supported(): + converter = Base62Converter() + assert converter.output_supported("text") is True + assert converter.output_supported("image_path") is False diff --git a/tests/unit/scenario/garak/test_encoding.py b/tests/unit/scenario/garak/test_encoding.py index 5db1297404..132af0a990 100644 --- a/tests/unit/scenario/garak/test_encoding.py +++ b/tests/unit/scenario/garak/test_encoding.py @@ -253,9 +253,9 @@ 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) == 18 + assert len(all_names) == 20 # The niche/lossy schemes stay ALL-only. - assert all_names - default_names == {"braille", "ecoji", "zalgo", "ascii_smuggler", "bifid"} + assert all_names - default_names == {"braille", "ecoji", "zalgo", "ascii_smuggler", "bifid", "base58", "base62"} def test_get_aggregate_tags_includes_default(self): """The scenario exposes both ``all`` and ``default`` as aggregate tags."""