Tokens.php
44 lines
| 1 | <?php |
| 2 | /** |
| 3 | * Token generation + hashing helpers. |
| 4 | * |
| 5 | * @package PrestoPlayer |
| 6 | * @subpackage Services\OAuth\Helpers |
| 7 | */ |
| 8 | |
| 9 | namespace PrestoPlayer\Services\OAuth\Helpers; |
| 10 | |
| 11 | /** |
| 12 | * Small static helpers for opaque token strings. |
| 13 | */ |
| 14 | class Tokens { |
| 15 | |
| 16 | /** |
| 17 | * Generate a cryptographically random base64url-safe opaque token. |
| 18 | * |
| 19 | * @param int $bytes Number of random bytes to draw (default 32 → ~43 char token). |
| 20 | * @return string Base64url-encoded random string with no padding. |
| 21 | */ |
| 22 | public static function generateOpaqueToken( $bytes = 32 ) { |
| 23 | $bytes = (int) $bytes; |
| 24 | if ( $bytes < 16 ) { |
| 25 | $bytes = 16; |
| 26 | } |
| 27 | $raw = random_bytes( $bytes ); |
| 28 | $base64 = base64_encode( $raw ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode |
| 29 | return rtrim( strtr( $base64, '+/', '-_' ), '=' ); |
| 30 | } |
| 31 | |
| 32 | /** |
| 33 | * Hash an opaque token for storage / lookup. |
| 34 | * |
| 35 | * Sha256 hex — fast, deterministic, suitable for indexed primary key lookups. |
| 36 | * |
| 37 | * @param string $token Plaintext token. |
| 38 | * @return string Hex-encoded sha256 digest (64 chars). |
| 39 | */ |
| 40 | public static function hash( $token ) { |
| 41 | return hash( 'sha256', (string) $token ); |
| 42 | } |
| 43 | } |
| 44 |