Php Csprng
## PHP CSPRNG
CSPRNG stands for **Cryptographically Secure Pseudo-Random Number Generator**.
Prior to PHP 7, generating cryptographically secure random values required relying on third-party libraries or platform-specific workarounds (such as reading `/dev/urandom` on Unix-like systems or using mcrypt).
Starting from PHP 7, a native, simple, and platform-independent mechanism was introduced to generate cryptographically strong random numbers and bytes. This is achieved through two primary functions:
* `random_bytes()` - Generates cryptographically secure pseudo-random bytes.
* `random_int()` - Generates cryptographically secure pseudo-random integers.
---
## The `random_bytes()` Function
The `random_bytes()` function generates an arbitrary-length string of raw random bytes, which is highly suitable for generating cryptographic keys, salts, or initialization vectors (IVs).
### Syntax
```php
string random_bytes ( int $length )
```
### Parameters
* **`length`**: The length of the random string that should be returned in bytes. It must be a positive integer.
### Return Value
* Returns a binary string containing the requested number of cryptographically secure random bytes.
### Code Example
Because the output of `random_bytes()` is raw binary data, it often contains non-printable characters. It is common practice to convert the binary string into a readable hexadecimal format using `bin2hex()`.
```php
```
**Possible Output:**
```text
6f36d48a29
```
---
## The `random_int()` Function
The `random_int()` function generates a cryptographically secure random integer within a specified range. This function is ideal for use cases where unbiased distribution is critical, such as rolling virtual dice, picking a winner in a lottery, or generating one-time passwords (OTPs).
### Syntax
```php
int random_int ( int $min , int $max )
```
### Parameters
* **`min`**: The lowest value to be returned. This must be greater than or equal to `PHP_INT_MIN`.
* **`max`**: The highest value to be returned. This must be less than or equal to `PHP_INT_MAX`.
### Return Value
* Returns a cryptographically secure random integer in the closed interval `[$min, $max]` (inclusive).
### Code Example
```php
```
**Possible Output:**
```text
723
-64
```
---
## Important Considerations & Best Practices
### 1. Why use CSPRNG over `rand()` or `mt_rand()`?
Standard random functions like `rand()` and `mt_rand()` use algorithms (like Mersenne Twister) that are fast but **not** cryptographically secure. If an attacker observes a sequence of numbers generated by `mt_rand()`, they can predict future outputs.
Always use `random_bytes()` and `random_int()` for security-sensitive operations, such as:
* Generating CSRF tokens.
* Generating password reset tokens.
* Creating API keys or session IDs.
* Generating salts for hashing.
### 2. Error Handling and Exceptions
If the system cannot find a secure source of randomness (for example, if the operating system's entropy pool is depleted), both functions will throw an **`Exception`** or an **`Error`** (specifically, a `Random\RandomException` in PHP 8.2+ or a generic `Exception` in older PHP 7/8 versions).
It is highly recommended to wrap these calls in a `try-catch` block when building high-security applications:
```php
getMessage());
}
?>
```
YouTip