From 2ca16dde078f32712a8ddf225d8190e3513c129f Mon Sep 17 00:00:00 2001 From: Jacob Dreesen Date: Mon, 17 Nov 2025 15:55:35 +0100 Subject: [PATCH] Add sodium support for Base64 URL safe encoding/decoding --- src/Library/Core/Util/Base64UrlSafe.php | 33 ++++++++++++++++++++----- 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/src/Library/Core/Util/Base64UrlSafe.php b/src/Library/Core/Util/Base64UrlSafe.php index e6a6b368..1ff209f9 100644 --- a/src/Library/Core/Util/Base64UrlSafe.php +++ b/src/Library/Core/Util/Base64UrlSafe.php @@ -27,7 +27,9 @@ * SOFTWARE. */ +use InvalidArgumentException; use RangeException; +use SodiumException; /** * @readonly @@ -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); } @@ -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); @@ -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); }