Verifier.php
51 lines
| 1 | <?php |
| 2 | /** |
| 3 | * PKCE S256 verifier. |
| 4 | * |
| 5 | * @package PrestoPlayer |
| 6 | * @subpackage Services\OAuth\PKCE |
| 7 | */ |
| 8 | |
| 9 | namespace PrestoPlayer\Services\OAuth\PKCE; |
| 10 | |
| 11 | /** |
| 12 | * Static helpers for verifying PKCE code challenges (RFC 7636). |
| 13 | */ |
| 14 | class Verifier { |
| 15 | |
| 16 | /** |
| 17 | * Verify a code_verifier against a stored S256 challenge. |
| 18 | * |
| 19 | * Per RFC 7636 §4.6: base64url(sha256(verifier)) == challenge. |
| 20 | * Comparison is timing-safe. |
| 21 | * |
| 22 | * @param string $challenge Stored code_challenge. |
| 23 | * @param string $verifier Client-supplied code_verifier. |
| 24 | * @return bool True when the verifier matches the challenge. |
| 25 | */ |
| 26 | public static function verifyS256( string $challenge, string $verifier ): bool { |
| 27 | if ( '' === $challenge || '' === $verifier ) { |
| 28 | return false; |
| 29 | } |
| 30 | |
| 31 | if ( ! preg_match( '/^[A-Za-z0-9\-._~]{43,128}$/', $verifier ) ) { |
| 32 | return false; |
| 33 | } |
| 34 | |
| 35 | $computed = self::base64UrlEncode( hash( 'sha256', $verifier, true ) ); |
| 36 | |
| 37 | return hash_equals( $challenge, $computed ); |
| 38 | } |
| 39 | |
| 40 | /** |
| 41 | * Encode bytes as base64url without padding. |
| 42 | * |
| 43 | * @param string $input Raw binary input. |
| 44 | * @return string Base64url-encoded string. |
| 45 | */ |
| 46 | public static function base64UrlEncode( string $input ): string { |
| 47 | $base64 = base64_encode( $input ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode |
| 48 | return rtrim( strtr( $base64, '+/', '-_' ), '=' ); |
| 49 | } |
| 50 | } |
| 51 |