Repository navigation
FEAT: Add Base58/Base62 converters on a shared encode_base_n helper #4454
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
2
commits into
microsoft:main
Choose a base branch
from
romanlutz:gap1-base-n
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.
+425
−1
Open
Changes from all commits
Commits
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
| 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) |
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,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") |
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,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") |
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,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" |
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.
Please also refresh the stored modality table in
doc/code/converters/0_converters.ipynbwhen synchronizing the examples. The table says it lists all available converters, but its output jumps fromBase2048ConvertertoBase64Converterand omits both new encoders. Both classes are exported and declare text input/output, so the existingget_converter_modalities()code already supplies the rows; no manual converter list is needed..github/instructions/converters.instructions.md:112requires this reference update. Keep the paired code synchronized and retain the new example and table outputs.