PHPackages                             tourze/tls-crypto-random - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. tourze/tls-crypto-random

ActiveLibrary

tourze/tls-crypto-random
========================

Cryptographically secure random number generator for TLS protocol implementation

0.0.1(11mo ago)0901MITPHPPHP ^8.1CI passing

Since May 23Pushed 6mo agoCompare

[ Source](https://github.com/tourze/tls-crypto-random)[ Packagist](https://packagist.org/packages/tourze/tls-crypto-random)[ RSS](/packages/tourze-tls-crypto-random/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (3)Versions (2)Used By (1)

TLS-Crypto-Random
=================

[](#tls-crypto-random)

[![PHP Version](https://camo.githubusercontent.com/6f61c16385e121f1009c477296e9a88d9352813581b8b66a97fed5237b222457/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e312d3838393242462e7376673f7374796c653d666c61742d737175617265)](https://www.php.net/)[![License](https://camo.githubusercontent.com/6c711032aff1ca0eb6b211aa6cb3649ce7fd64a7714e1181d4bb457f9680e7cf/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE)[![Build Status](https://camo.githubusercontent.com/3c75cbf80739d3f42836bab035102123295320544fd5b4157e0fec7fc34b2780/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f746f75727a652f7068702d6d6f6e6f7265706f2f63692e796d6c3f6272616e63683d6d6173746572267374796c653d666c61742d737175617265)](https://github.com/tourze/php-monorepo/actions)[![Code Coverage](https://camo.githubusercontent.com/6ce0146325478eb7cebae4cc6139b2af2c161735dd0e3c6ff6802f2c5a708179/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f746f75727a652f7068702d6d6f6e6f7265706f3f7374796c653d666c61742d737175617265)](https://codecov.io/gh/tourze/php-monorepo)

[English](README.md) | [中文](README.zh-CN.md)

A cryptographically secure random number generator library for TLS protocol implementation, providing secure random bytes and integers generation using PHP's built-in cryptographic functions.

Features
--------

[](#features)

- **Cryptographically Secure**: Uses PHP's `random_bytes()` and `random_int()` functions
- **Simple Interface**: Clean API with comprehensive error handling
- **Exception Safety**: Proper exception handling for all edge cases
- **Type Safety**: Full PHP 8.1+ type declarations
- **Performance**: Efficient random number generation with minimal overhead

Installation
------------

[](#installation)

```
composer require tourze/tls-crypto-random
```

Requirements
------------

[](#requirements)

- PHP 8.1 or higher
- OpenSSL extension (for secure random number generation)

Usage
-----

[](#usage)

### Basic Usage

[](#basic-usage)

```
use Tourze\TLSCryptoRandom\CryptoRandom;

$random = new CryptoRandom();

// Generate random bytes
$randomBytes = $random->getRandomBytes(32); // 32 bytes
echo bin2hex($randomBytes); // Output: e.g., "a1b2c3d4e5f6..."

// Generate random integer
$randomInt = $random->getRandomInt(1, 100); // Integer between 1 and 100
echo $randomInt; // Output: e.g., 42
```

### Interface Implementation

[](#interface-implementation)

```
use Tourze\TLSCryptoRandom\Contract\RandomInterface;
use Tourze\TLSCryptoRandom\CryptoRandom;

function useRandomGenerator(RandomInterface $random): void
{
    // Generate a session ID
    $sessionId = bin2hex($random->getRandomBytes(16));

    // Generate a random port number
    $port = $random->getRandomInt(1024, 65535);

    echo "Session ID: {$sessionId}\n";
    echo "Port: {$port}\n";
}

$random = new CryptoRandom();
useRandomGenerator($random);
```

### Error Handling

[](#error-handling)

```
use Tourze\TLSCryptoRandom\CryptoRandom;
use Tourze\TLSCryptoRandom\Exception\RandomException;

$random = new CryptoRandom();

try {
    // Invalid length
    $random->getRandomBytes(0);
} catch (RandomException $e) {
    echo "Error: " . $e->getMessage(); // "随机字节长度必须大于0"
}

try {
    // Invalid range
    $random->getRandomInt(100, 1);
} catch (RandomException $e) {
    echo "Error: " . $e->getMessage(); // "最小值不能大于最大值"
}
```

API Reference
-------------

[](#api-reference)

### CryptoRandom Class

[](#cryptorandom-class)

Implements `RandomInterface` and provides cryptographically secure random number generation.

#### Methods

[](#methods)

##### `getRandomBytes(int $length): string`

[](#getrandombytesint-length-string)

Generates cryptographically secure random bytes.

- **Parameters:**
    - `$length` (int): Number of bytes to generate (must be &gt; 0)
- **Returns:** string - Random bytes
- **Throws:** `RandomException` - If length is invalid or generation fails

##### `getRandomInt(int $min, int $max): int`

[](#getrandomintint-min-int-max-int)

Generates cryptographically secure random integer within specified range.

- **Parameters:**
    - `$min` (int): Minimum value (inclusive)
    - `$max` (int): Maximum value (inclusive)
- **Returns:** int - Random integer
- **Throws:** `RandomException` - If range is invalid or generation fails

### RandomInterface

[](#randominterface)

Interface for random number generators.

```
interface RandomInterface
{
    public function getRandomBytes(int $length): string;
    public function getRandomInt(int $min, int $max): int;
}
```

### Exceptions

[](#exceptions)

#### RandomException

[](#randomexception)

Thrown when random number generation fails or invalid parameters are provided.

#### CryptoException

[](#cryptoexception)

Base exception class for cryptographic operations.

Security Considerations
-----------------------

[](#security-considerations)

- Uses PHP's cryptographically secure `random_bytes()` and `random_int()` functions
- Suitable for generating session tokens, salts, and other security-sensitive values
- No fallback to insecure random number generators
- Proper error handling prevents silent failures

Performance
-----------

[](#performance)

- Efficient direct usage of PHP's built-in functions
- No additional entropy collection overhead
- Suitable for high-performance applications
- Tested with large data generation (100KB+ in under 1 second)

Testing
-------

[](#testing)

The package includes comprehensive tests covering:

- Basic functionality
- Edge cases and error conditions
- Performance characteristics
- Cryptographic quality (basic entropy testing)
- Concurrent usage scenarios

Run tests with:

```
./vendor/bin/phpunit packages/tls-crypto-random/tests
```

License
-------

[](#license)

MIT License - see LICENSE file for details.

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance64

Regular maintenance activity

Popularity9

Limited adoption so far

Community5

Small or concentrated contributor base

Maturity35

Early-stage or recently created project

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

351d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e354fdb316da535dfa8ba2e9193a473c403b6bc6fb9170778d1dc50e304c6e9d?d=identicon)[tourze](/maintainers/tourze)

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tourze-tls-crypto-random/health.svg)

```
[![Health](https://phpackages.com/badges/tourze-tls-crypto-random/health.svg)](https://phpackages.com/packages/tourze-tls-crypto-random)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
