| 1 |
<?php |
| 2 |
// phpcs:disable Yoast.NamingConventions.NamespaceName.TooLong -- Needed in the folder structure. |
| 3 |
|
| 4 |
namespace Yoast\WP\SEO\MyYoast_Client\Infrastructure\Encoding; |
| 5 |
|
| 6 |
/** |
| 7 |
* Base64url encoding and decoding per RFC 7515 / RFC 4648 Section 5. |
| 8 |
* |
| 9 |
* Provides URL-safe, unpadded Base64 encoding as required by JWTs, JWKs, |
| 10 |
* PKCE challenges, and other OAuth/OIDC constructs. |
| 11 |
*/ |
| 12 |
class Base64url { |
| 13 |
|
| 14 |
/** |
| 15 |
* Encodes data using base64url (URL-safe, no padding). |
| 16 |
* |
| 17 |
* @param string $data The data to encode. |
| 18 |
* |
| 19 |
* @return string The base64url-encoded string. |
| 20 |
*/ |
| 21 |
public static function encode( string $data ): string { |
| 22 |
// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- Base64URL encoding per RFC 7515. |
| 23 |
return \rtrim( \strtr( \base64_encode( $data ), '+/', '-_' ), '=' ); |
| 24 |
} |
| 25 |
|
| 26 |
/** |
| 27 |
* Decodes a base64url-encoded string. |
| 28 |
* |
| 29 |
* @param string $data The base64url-encoded string. |
| 30 |
* |
| 31 |
* @return string|false The decoded data, or false on failure. |
| 32 |
*/ |
| 33 |
public static function decode( string $data ) { |
| 34 |
$remainder = ( \strlen( $data ) % 4 ); |
| 35 |
if ( $remainder !== 0 ) { |
| 36 |
$data .= \str_repeat( '=', ( 4 - $remainder ) ); |
| 37 |
} |
| 38 |
|
| 39 |
// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode -- Base64URL decoding per RFC 7515. |
| 40 |
return \base64_decode( \strtr( $data, '-_', '+/' ), true ); |
| 41 |
} |
| 42 |
} |
| 43 |
|