Skip to content
Merged
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
33 changes: 27 additions & 6 deletions src/Library/Core/Util/Base64UrlSafe.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@
* SOFTWARE.
*/

use InvalidArgumentException;
use RangeException;
use SodiumException;

/**
* @readonly
Expand All @@ -36,11 +38,25 @@ final class Base64UrlSafe
{
public static function encode(string $binString): string
{
if (extension_loaded('sodium')) {
try {
return sodium_bin2base64($binString, SODIUM_BASE64_VARIANT_URLSAFE);
} catch (SodiumException $ex) {
throw new RangeException($ex->getMessage(), $ex->getCode(), $ex);
}
}
return static::doEncode($binString, true);
}

public static function encodeUnpadded(string $src): string
{
if (extension_loaded('sodium')) {
try {
return sodium_bin2base64($src, SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING);
} catch (SodiumException $ex) {
throw new RangeException($ex->getMessage(), $ex->getCode(), $ex);
}
}
return static::doEncode($src, false);
}

Expand All @@ -66,6 +82,16 @@ public static function decode(string $encodedString, bool $strictPadding = false
if ($encodedString[$srcLen - 1] === '=') {
throw new RangeException('Incorrect padding');
}
if (extension_loaded('sodium')) {
try {
return sodium_base642bin(
self::safeSubstr($encodedString, 0, $srcLen),
SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING
);
} catch (SodiumException $ex) {
throw new RangeException($ex->getMessage(), $ex->getCode(), $ex);
}
}
} else {
$encodedString = rtrim($encodedString, '=');
$srcLen = self::safeStrlen($encodedString);
Expand Down Expand Up @@ -128,14 +154,9 @@ public static function decodeNoPadding(string $encodedString): string
return '';
}
if (($srcLen & 3) === 0) {
if ($encodedString[$srcLen - 1] === '=') {
if ($encodedString[$srcLen - 1] === '=' || $encodedString[$srcLen - 2] === '=') {
throw new InvalidArgumentException("decodeNoPadding() doesn't tolerate padding");
}
if (($srcLen & 3) > 1) {
if ($encodedString[$srcLen - 2] === '=') {
throw new InvalidArgumentException("decodeNoPadding() doesn't tolerate padding");
}
}
}
return static::decode($encodedString, true);
}
Expand Down
Loading