-
Notifications
You must be signed in to change notification settings - Fork 0
Add Base32 conversion utilities #1
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
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
1314133
Add Base32 encoding and decoding utilities
kduma 5700a9f
Merge branch 'main' into codex/add-base32-conversion-methods-with-tests
kduma 94ec357
Update src/Base32.php
kduma 7b3755b
Merge branch 'codex/add-base32-conversion-methods-with-tests' of gith…
kduma 784223b
Add missing tests
kduma 51a9c51
Update src/BinaryString.php
kduma efa97e0
Update src/BinaryString.php
kduma e5a79f4
Update tests/Base32Test.php
kduma 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,135 @@ | ||
| <?php declare(strict_types=1); | ||
|
|
||
| namespace KDuma\BinaryTools; | ||
|
|
||
| use InvalidArgumentException; | ||
|
|
||
| /** | ||
| * Base32 encoder/decoder using a configurable alphabet (default RFC 4648 without padding). | ||
| */ | ||
| final class Base32 | ||
| { | ||
| public const DEFAULT_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; | ||
|
|
||
| /** @var array<string, array<string, int>> */ | ||
| private static array $decodeMaps = []; | ||
|
|
||
| /** @var array<string, bool> */ | ||
| private static array $validatedAlphabets = []; | ||
|
|
||
| public static function toBase32(string $binary, string $alphabet = self::DEFAULT_ALPHABET): string | ||
| { | ||
| self::ensureValidAlphabet($alphabet); | ||
|
|
||
| if ($binary === '') { | ||
| return ''; | ||
| } | ||
|
|
||
| $result = ''; | ||
| $buffer = 0; | ||
| $bitsLeft = 0; | ||
| $length = strlen($binary); | ||
|
|
||
| for ($i = 0; $i < $length; $i++) { | ||
| $buffer = ($buffer << 8) | ord($binary[$i]); | ||
| $bitsLeft += 8; | ||
|
|
||
| while ($bitsLeft >= 5) { | ||
| $bitsLeft -= 5; | ||
| $index = ($buffer >> $bitsLeft) & 0x1F; | ||
| $result .= $alphabet[$index]; | ||
| } | ||
| } | ||
|
|
||
| if ($bitsLeft > 0) { | ||
| $index = ($buffer << (5 - $bitsLeft)) & 0x1F; | ||
| $result .= $alphabet[$index]; | ||
| } | ||
|
|
||
| return $result; | ||
| } | ||
|
|
||
| public static function fromBase32(string $base32, string $alphabet = self::DEFAULT_ALPHABET): string | ||
| { | ||
| if ($base32 === '') { | ||
| return ''; | ||
| } | ||
|
|
||
| $map = self::decodeMap($alphabet); | ||
|
|
||
| $buffer = 0; | ||
| $bitsLeft = 0; | ||
| $output = ''; | ||
| $length = strlen($base32); | ||
|
|
||
| for ($i = 0; $i < $length; $i++) { | ||
| $char = $base32[$i]; | ||
|
|
||
| if ($char === '=') { | ||
| break; // padding reached (RFC 4648) | ||
| } | ||
|
|
||
| if (!isset($map[$char])) { | ||
| throw new InvalidArgumentException( | ||
| sprintf( | ||
| "Invalid character '%s' at position %d in Base32 input.", | ||
| $char, | ||
| $i | ||
| ) | ||
| ); | ||
| } | ||
|
|
||
| $buffer = ($buffer << 5) | $map[$char]; | ||
| $bitsLeft += 5; | ||
|
|
||
| if ($bitsLeft >= 8) { | ||
| $bitsLeft -= 8; | ||
| $output .= chr(($buffer >> $bitsLeft) & 0xFF); | ||
| } | ||
| } | ||
|
|
||
| return $output; | ||
| } | ||
|
|
||
| /** | ||
| * @return array<string, int> | ||
| */ | ||
| private static function decodeMap(string $alphabet): array | ||
| { | ||
| if (!isset(self::$decodeMaps[$alphabet])) { | ||
| self::ensureValidAlphabet($alphabet); | ||
|
|
||
| $map = []; | ||
| for ($i = 0; $i < 32; $i++) { | ||
| $char = $alphabet[$i]; | ||
| $map[$char] = $i; | ||
| } | ||
|
|
||
| self::$decodeMaps[$alphabet] = $map; | ||
| } | ||
|
|
||
| return self::$decodeMaps[$alphabet]; | ||
| } | ||
|
|
||
| private static function ensureValidAlphabet(string $alphabet): void | ||
| { | ||
| if (isset(self::$validatedAlphabets[$alphabet])) { | ||
| return; | ||
| } | ||
|
|
||
| if (strlen($alphabet) !== 32) { | ||
| throw new InvalidArgumentException('Base32 alphabet must contain exactly 32 characters.'); | ||
| } | ||
|
|
||
| $characters = []; | ||
| for ($i = 0; $i < 32; $i++) { | ||
| $char = $alphabet[$i]; | ||
| if (isset($characters[$char])) { | ||
| throw new InvalidArgumentException('Base32 alphabet must contain unique characters.'); | ||
| } | ||
| $characters[$char] = true; | ||
| } | ||
|
|
||
| self::$validatedAlphabets[$alphabet] = true; | ||
| } | ||
| } |
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,138 @@ | ||
| <?php declare(strict_types=1); | ||
|
|
||
| namespace KDuma\BinaryTools\Tests; | ||
|
|
||
| use KDuma\BinaryTools\Base32; | ||
| use KDuma\BinaryTools\BinaryString; | ||
| use PHPUnit\Framework\Attributes\CoversClass; | ||
| use PHPUnit\Framework\Attributes\DataProvider; | ||
| use PHPUnit\Framework\TestCase; | ||
|
|
||
| #[CoversClass(Base32::class)] | ||
| class Base32Test extends TestCase | ||
| { | ||
| public function testEmpty(): void | ||
| { | ||
| $this->assertSame('', Base32::toBase32('')); | ||
| $this->assertSame('', Base32::fromBase32('')); | ||
|
|
||
| $binaryString = BinaryString::fromString(''); | ||
| $this->assertSame('', $binaryString->toBase32()); | ||
| $this->assertTrue($binaryString->equals(BinaryString::fromBase32(''))); | ||
| } | ||
|
|
||
| /** | ||
| * RFC 4648 test vectors (uppercase, unpadded form). | ||
| * | ||
| * @return array<string, array{plain: string, base32: string}> | ||
| */ | ||
| public static function vectors(): array | ||
| { | ||
| return [ | ||
| 'f' => ['plain' => 'f', 'base32' => 'MY'], | ||
| 'fo' => ['plain' => 'fo', 'base32' => 'MZXQ'], | ||
| 'foo' => ['plain' => 'foo', 'base32' => 'MZXW6'], | ||
| 'foob' => ['plain' => 'foob', 'base32' => 'MZXW6YQ'], | ||
| 'fooba' => ['plain' => 'fooba', 'base32' => 'MZXW6YTB'], | ||
| 'foobar' => ['plain' => 'foobar', 'base32' => 'MZXW6YTBOI'], | ||
| 'A' => ['plain' => 'A', 'base32' => 'IE'], | ||
| 'AB' => ['plain' => 'AB', 'base32' => 'IFBA'], | ||
| 'ABC' => ['plain' => 'ABC', 'base32' => 'IFBEG'], | ||
| ]; | ||
| } | ||
|
|
||
| #[DataProvider('vectors')] | ||
| public function testToBase32MatchesKnownVectors(string $plain, string $base32): void | ||
| { | ||
| $this->assertSame($base32, Base32::toBase32($plain)); | ||
| $this->assertSame($base32, BinaryString::fromString($plain)->toBase32()); | ||
| } | ||
|
|
||
| #[DataProvider('vectors')] | ||
| public function testFromBase32MatchesKnownVectors(string $plain, string $base32): void | ||
| { | ||
| $this->assertSame($plain, Base32::fromBase32($base32)); | ||
| $this->assertTrue(BinaryString::fromString($plain)->equals(BinaryString::fromBase32($base32))); | ||
| } | ||
|
|
||
| public function testRoundTripRandomBinary(): void | ||
| { | ||
| $lengths = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 31, 32, 33, 64, 100, 256, 1024]; | ||
|
|
||
| foreach ($lengths as $length) { | ||
| $binary = ($length === 0) ? '' : random_bytes($length); | ||
| $encoded = Base32::toBase32($binary); | ||
| $decoded = Base32::fromBase32($encoded); | ||
|
|
||
| $this->assertSame($binary, $decoded, "Failed round-trip at length {$length}"); | ||
| } | ||
| } | ||
|
|
||
| public function testDecodeThenEncodeIsIdempotent(): void | ||
| { | ||
| $original = 'MZXW6YTBOI'; // "foobar" | ||
| $decoded = Base32::fromBase32($original); | ||
| $reEncoded = Base32::toBase32($decoded); | ||
|
|
||
| $this->assertSame($original, $reEncoded); | ||
| } | ||
|
|
||
| public function testLowercaseInputThrowsException(): void | ||
| { | ||
| $lower = 'mzxw6ytboi'; | ||
|
|
||
| $this->expectException(\InvalidArgumentException::class); | ||
| $this->expectExceptionMessage("Invalid character 'm' at position 0 in Base32 input."); | ||
|
|
||
| Base32::fromBase32($lower); | ||
| } | ||
|
|
||
| public function testCustomAlphabet(): void | ||
| { | ||
| $customAlphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUV'; | ||
| $data = 'Hello World'; | ||
|
|
||
| $encoded = Base32::toBase32($data, $customAlphabet); | ||
| $decoded = Base32::fromBase32($encoded, $customAlphabet); | ||
|
|
||
| $this->assertSame($data, $decoded); | ||
| } | ||
|
|
||
| public function testInvalidAlphabetLengthThrowsException(): void | ||
| { | ||
| $shortAlphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ12345'; // 31 chars instead of 32 | ||
|
|
||
| $this->expectException(\InvalidArgumentException::class); | ||
| $this->expectExceptionMessage('Base32 alphabet must contain exactly 32 characters.'); | ||
|
|
||
| Base32::toBase32('test', $shortAlphabet); | ||
| } | ||
|
|
||
| public function testDuplicateCharactersInAlphabetThrowsException(): void | ||
| { | ||
| $duplicateAlphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ23456A'; // 'A' appears twice | ||
|
|
||
| $this->expectException(\InvalidArgumentException::class); | ||
| $this->expectExceptionMessage('Base32 alphabet must contain unique characters.'); | ||
|
|
||
| Base32::toBase32('test', $duplicateAlphabet); | ||
| } | ||
|
|
||
| public function testPaddingIsIgnoredDuringDecoding(): void | ||
| { | ||
| $paddedBase32 = 'MZXW6YTBOI======'; // "foobar" with padding | ||
| $decoded = Base32::fromBase32($paddedBase32); | ||
|
|
||
| $this->assertSame('foobar', $decoded); | ||
| } | ||
|
|
||
| public function testInvalidCharacterInMiddleThrowsException(): void | ||
| { | ||
| $invalidBase32 = 'MZXW@YTBOI'; // '@' is invalid | ||
|
|
||
| $this->expectException(\InvalidArgumentException::class); | ||
| $this->expectExceptionMessage("Invalid character '@' at position 4 in Base32 input."); | ||
|
|
||
| Base32::fromBase32($invalidBase32); | ||
| } | ||
| } |
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
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.
Uh oh!
There was an error while loading. Please reload this page.