Oihana PHP

randomHex.php

Table of Contents

Functions

randomHex()  : string
Generates a cryptographically secure random token, encoded as a lowercase hexadecimal string.

Functions

randomHex()

Generates a cryptographically secure random token, encoded as a lowercase hexadecimal string.

randomHex([int $bytes = 32 ]) : string

The function reads $bytes of entropy from random_bytes() (a CSPRNG) and encodes the result with bin2hex(). The output is safe to use in URLs, logs, filenames, correlation/request IDs, JWT jti, refresh tokens and similar contexts.

Output length is exactly 2 * $bytes characters. Default $bytes = 32 yields 256 bits of entropy → 64 characters.

For shorter URL-friendly tokens at equivalent entropy, prefer randomBase64Url().

Parameters
$bytes : int = 32

Number of random bytes to generate. Must be >= 1. Defaults to 32 (256 bits of entropy).

Tags
throws
InvalidArgumentException

If $bytes is less than 1.

RandomException

If no source of randomness is available (propagated from random_bytes()).

example
use function oihana\core\encoding\randomHex;

$requestId     = randomHex( 8  ) ; // 16 hex chars  ( 64 bits)
$correlationId = randomHex( 16 ) ; // 32 hex chars  (128 bits)
$refreshToken  = randomHex()      ; // 64 hex chars (256 bits, default)

// Always lowercase hex
preg_match( '/^[0-9a-f]+$/' , $refreshToken ) ; // 1
see
hexEncode()

Encoder used internally.

randomBase64Url()

Base64url variant (shorter at equivalent entropy).

author

Marc Alcaraz (ekameleon)

since
1.0.8
Return values
string

Lowercase hexadecimal string of length 2 * $bytes.

On this page

Search results