2727 * SOFTWARE.
2828 */
2929
30+ use InvalidArgumentException ;
3031use RangeException ;
32+ use SodiumException ;
3133
3234/**
3335 * @readonly
@@ -36,11 +38,25 @@ final class Base64UrlSafe
3638{
3739 public static function encode (string $ binString ): string
3840 {
41+ if (extension_loaded ('sodium ' )) {
42+ try {
43+ return sodium_bin2base64 ($ binString , SODIUM_BASE64_VARIANT_URLSAFE );
44+ } catch (SodiumException $ ex ) {
45+ throw new RangeException ($ ex ->getMessage (), $ ex ->getCode (), $ ex );
46+ }
47+ }
3948 return static ::doEncode ($ binString , true );
4049 }
4150
4251 public static function encodeUnpadded (string $ src ): string
4352 {
53+ if (extension_loaded ('sodium ' )) {
54+ try {
55+ return sodium_bin2base64 ($ src , SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING );
56+ } catch (SodiumException $ ex ) {
57+ throw new RangeException ($ ex ->getMessage (), $ ex ->getCode (), $ ex );
58+ }
59+ }
4460 return static ::doEncode ($ src , false );
4561 }
4662
@@ -66,6 +82,16 @@ public static function decode(string $encodedString, bool $strictPadding = false
6682 if ($ encodedString [$ srcLen - 1 ] === '= ' ) {
6783 throw new RangeException ('Incorrect padding ' );
6884 }
85+ if (extension_loaded ('sodium ' )) {
86+ try {
87+ return sodium_base642bin (
88+ self ::safeSubstr ($ encodedString , 0 , $ srcLen ),
89+ SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING
90+ );
91+ } catch (SodiumException $ ex ) {
92+ throw new RangeException ($ ex ->getMessage (), $ ex ->getCode (), $ ex );
93+ }
94+ }
6995 } else {
7096 $ encodedString = rtrim ($ encodedString , '= ' );
7197 $ srcLen = self ::safeStrlen ($ encodedString );
@@ -128,14 +154,9 @@ public static function decodeNoPadding(string $encodedString): string
128154 return '' ;
129155 }
130156 if (($ srcLen & 3 ) === 0 ) {
131- if ($ encodedString [$ srcLen - 1 ] === '= ' ) {
157+ if ($ encodedString [$ srcLen - 1 ] === '= ' || $ encodedString [ $ srcLen - 2 ] === ' = ' ) {
132158 throw new InvalidArgumentException ("decodeNoPadding() doesn't tolerate padding " );
133159 }
134- if (($ srcLen & 3 ) > 1 ) {
135- if ($ encodedString [$ srcLen - 2 ] === '= ' ) {
136- throw new InvalidArgumentException ("decodeNoPadding() doesn't tolerate padding " );
137- }
138- }
139160 }
140161 return static ::decode ($ encodedString , true );
141162 }
0 commit comments