Skip to content
Merged
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
34 changes: 34 additions & 0 deletions src/Base64.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,16 @@ public static function encode(
#[\SensitiveParameter]
string $binString
): string {
if (extension_loaded('sodium')) {
$variant = match(static::class) {
Base64::class => SODIUM_BASE64_VARIANT_ORIGINAL,
Base64UrlSafe::class => SODIUM_BASE64_VARIANT_URLSAFE,
default => 0,
};
if ($variant > 0) {
return sodium_bin2base64($binString, $variant);
}
}
return static::doEncode($binString, true);
}

Expand All @@ -68,6 +78,16 @@ public static function encodeUnpadded(
#[\SensitiveParameter]
string $src
): string {
if (extension_loaded('sodium')) {
$variant = match(static::class) {
Base64::class => SODIUM_BASE64_VARIANT_ORIGINAL_NO_PADDING,
Base64UrlSafe::class => SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING,
default => 0,
};
if ($variant > 0) {
return sodium_bin2base64($src, $variant);
}
}
return static::doEncode($src, false);
}

Expand Down Expand Up @@ -167,6 +187,20 @@ public static function decode(
'Incorrect padding'
);
}
if (extension_loaded('sodium')) {
$variant = match(static::class) {
Base64::class => SODIUM_BASE64_VARIANT_ORIGINAL_NO_PADDING,
Base64UrlSafe::class => SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING,
default => 0,
};
if ($variant > 0) {
try {
return sodium_base642bin($encodedString, $variant);
} catch (\SodiumException $ex) {
throw new RangeException($ex->getMessage(), $ex->getCode(), $ex);
}
}
}
} else {
$encodedString = \rtrim($encodedString, '=');
$srcLen = Binary::safeStrlen($encodedString);
Expand Down
6 changes: 6 additions & 0 deletions src/Hex.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ public static function encode(
#[\SensitiveParameter]
string $binString
): string {
if (extension_loaded('sodium')) {
return sodium_bin2hex($binString);
}
$hex = '';
$len = Binary::safeStrlen($binString);
for ($i = 0; $i < $len; ++$i) {
Expand Down Expand Up @@ -107,6 +110,9 @@ public static function decode(
string $encodedString,
bool $strictPadding = false
): string {
if (extension_loaded('sodium')) {
return sodium_hex2bin($encodedString);
}
$hex_pos = 0;
$bin = '';
$c_acc = 0;
Expand Down
5 changes: 3 additions & 2 deletions tests/Base64Test.php
Original file line number Diff line number Diff line change
Expand Up @@ -105,10 +105,11 @@ public function testDecodeNoPadding()
/**
* @dataProvider canonicalDataProvider
*/
public function testNonCanonical(string $input)
public function testNonCanonical(string $input): void
{
$w = Base64::encodeUnpadded($input);
Base64::decode($w);
$decoded = Base64::decode($w);
$this->assertSame($input, $decoded);
Base64::decode($w, true);

// Mess with padding:
Expand Down