Prng Chilkat2 PHP Reference Documentation

Prng

Current Version: 11.7.0

Markdown version of this page for AI tools (v 11.7.0) · all AI docs

Chilkat.Prng

Generate random bytes, encoded values, passwords, and application identifiers.

Use Chilkat.Prng when an application needs random bytes or random text values for cryptographic or application-level purposes. The class can seed itself automatically from the system entropy source, accept additional entropy from the application, and produce random data as raw bytes, encoded strings, passwords, integers, booleans, GUID-style values, or higher-level identifiers such as Firebase Push IDs.

Random bytes

Generate random byte data for keys, IVs, nonces, salts, tokens, test data, or protocol-specific binary values.

Encoded random strings

Produce random values encoded as Base64, hex, URL-safe text, or other supported encodings when binary data must be represented as text.

Password generation

Create random passwords using configurable character sets and length requirements.

Entropy input

Allow the PRNG to seed from the system entropy source and optionally add application-provided entropy.

Random application values

Generate random integers, booleans, GUID-style values, and other convenient random outputs for application logic.

Firebase Push IDs

Create Firebase-style push IDs for applications that need sortable, client-generated identifiers.

Common pattern: Use Prng to create random material in the form required by the caller: bytes for cryptographic inputs, encoded strings for tokens or API values, passwords for user-facing credentials, or Firebase Push IDs for sortable identifiers. For cryptographic workflows, generate enough random bytes for the algorithm or protocol and avoid reducing randomness by truncating or reformatting values incorrectly.

Object Creation

use Chilkat2\Prng;

try {
    $prng = new Prng();
    // ... use $prng ...
} catch (\Chilkat2\Exception $e) {
    echo $e->getClass(), '::', $e->getMethod(), " failed\n";
    echo $e->getMessage(), "\n";              // the LastErrorText of the failed call
}
public function __construct(array $properties = [])

Creates the object. The optional array sets properties in order, as if assigned one by one (new Prng(['VerboseLogging' => true, 'RaiseError' => false])); an unknown or read-only name throws Error. The class is defined by the chilkat2 extension (extension=chilkat2 in php.ini): there is no PHP file to include.

There is no close(): PHP frees the object when its last reference goes (unset($prng), $prng = null, or the end of the function or request). Objects returned by methods are independent and freed the same way. The class may be extended (class MyPrng extends \Chilkat2\Prng); objects cannot be cloned or serialized.

public bool $RaiseError;

When true (the default), a method that fails throws Chilkat2\Exception. When false, it returns false (or null) instead, and the reason is in LastErrorText. Objects returned by a method inherit the value of the object that returned them.

Errors

Chilkat2\Exception extends RuntimeException: getMessage() is the failed call's full LastErrorText, getClass() its class ('Chilkat2\Prng') and getMethod() the method name. The object remains usable. Methods that look something up and find nothing return null without throwing (each such method says so), methods that answer a question (HasMember, IsUnlocked, ...) return a plain bool, and property reads and writes do not throw for Chilkat reasons.

Misuse always throws, whatever RaiseError is: a wrong argument type is a TypeError (exact types under declare(strict_types=1)), a missing or extra argument an ArgumentCountError, a string containing a NUL byte or an out-of-range integer a ValueError, and an unknown property (properties are case-sensitive) or a write to a read-only one an Error. Named arguments work with the parameter names shown.

Strings are passed and returned as UTF-8; binary data is a PHP string of bytes. Unlocking: call (new \Chilkat2\GlobalSettings())->UnlockBundle('...') once at startup.

Properties

DebugLogFilePath
public string $DebugLogFilePath;

If set to a file path, this property logs the LastErrorText of each Chilkat method or property call to the specified file. This logging helps identify the context and history of Chilkat calls leading up to any crash or hang, aiding in debugging.

Enabling the VerboseLogging property provides more detailed information. This property is mainly used for debugging rare instances where a Chilkat method call causes a hang or crash, which should generally not happen.

Possible causes of hangs include:

  • A timeout property set to 0, indicating an infinite timeout.
  • A hang occurring within an event callback in the application code.
  • An internal bug in the Chilkat code causing the hang.

More Information and Examples
top
LastErrorHtml
public readonly string $LastErrorHtml;

Provides HTML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.

top
LastErrorText
public readonly string $LastErrorText;

Provides plain text information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.

top
LastErrorXml
public readonly string $LastErrorXml;

Provides XML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.

top
LastMethodSuccess
public bool $LastMethodSuccess;

Indicates the success or failure of the most recent method call: true means success, false means failure. This property remains unchanged by property setters or getters. This method is present to address challenges in checking for null or Nothing returns in certain programming languages. Note: This property does not apply to methods that return integer values or to boolean-returning methods where the boolean does not indicate success or failure.

top
PrngName
public string $PrngName;
Introduced in version 9.5.0.52

Selects the pseudo-random number generator used by this object. The only supported value is fortuna, which is also the default. Chilkat's Fortuna implementation uses AES-256 for generation and SHA-256 in its entropy-processing and reseeding design.

Compatibility note: Assigning any value other than fortuna is ignored. Applications should normally leave this property unchanged.

More Information and Examples
top
VerboseLogging
public bool $VerboseLogging;

If set to true, then the contents of LastErrorText (or LastErrorXml, or LastErrorHtml) may contain more verbose information. The default value is false. Verbose logging should only be used for debugging. The potentially large quantity of logged information may adversely affect peformance.

top
Version
public readonly string $Version;

Version of the component/library, such as "10.1.0"

More Information and Examples
top

Methods

AddEntropy
public function AddEntropy(string $entropy, string $encoding): bool
Introduced in version 9.5.0.52

Adds caller-supplied seed material to the PRNG. $entropy contains the bytes in the text encoding named by $encoding, such as hex, base64, or ascii. For Fortuna, the decoded bytes are incorporated into the internal entropy pools and become available to later reseeding.

This method is optional and is not the normal way an application obtains entropy for the PRNG. It may be called more than once and at any point during the lifetime of the object. It returns true when the input is decoded and accepted, or false if the encoding is invalid or another error occurs.

Automatic system seeding: If no entropy has been added before the first request for random output, Chilkat automatically obtains 32 bytes from the platform's cryptographic system entropy source to seed the PRNG. This is the normal and recommended mode of operation. Call AddEntropy only when the application has additional trustworthy entropy to contribute or deliberately needs deterministic seeding for testing.
Repeatable tests: A fresh Prng object can be seeded with the same deterministic values to reproduce the same output sequence, provided the same entropy calls and random-generation calls occur in the same order. Predictable seed material is appropriate only for tests and debugging. Do not use it for real keys, nonces, passwords, or tokens.

Returns true on success. On failure it throws Chilkat2\Exception (or, with RaiseError set to false, returns false). $e->getMessage() (or the object's LastErrorText) explains why, and the object remains usable.

top
ExportEntropy
public function ExportEntropy(): ?string
Introduced in version 9.5.0.52

Exports a Base64-encoded value derived from the PRNG's accumulated entropy pools. The internal pools are rehashed for export so the returned value is not a direct disclosure of the generator state.

The returned value can be persisted and supplied to ImportEntropy when a later process starts. For language bindings in which this method directly returns a string, check LastMethodSuccess before using the result.

Seed-file guidance: Imported entropy can improve startup behavior, but it should not be the only seed used indefinitely. After importing, also allow Chilkat to obtain fresh operating-system entropy. Protect persisted entropy from unauthorized modification and accidental reuse across cloned systems.

On failure it throws Chilkat2\Exception (or, with RaiseError set to false, returns null). $e->getMessage() (or the object's LastErrorText) explains why, and the object remains usable.

More Information and Examples
top
FirebasePushId
public function FirebasePushId(): ?string
Introduced in version 9.5.0.58

Generates a Firebase-compatible push ID. A push ID is a 20-character identifier built from a 48-bit millisecond timestamp followed by 72 bits of randomness, encoded with Firebase's ordered 64-character alphabet.

The timestamp prefix makes push IDs sort approximately by creation time, while the random portion makes collisions highly unlikely across independent clients. For language bindings in which this method directly returns a string, check LastMethodSuccess before using the result.

Not a secret: A push ID is an identifier, not an authentication token. Its prefix reveals approximate creation time, and uniqueness is probabilistic rather than an absolute guarantee.

On failure it throws Chilkat2\Exception (or, with RaiseError set to false, returns null). $e->getMessage() (or the object's LastErrorText) explains why, and the object remains usable.

More Information and Examples
top
GenRandom
public function GenRandom(int $numBytes, string $encoding): ?string
Introduced in version 9.5.0.52

Generates $numBytes random bytes and returns those bytes as text using the encoding named by $encoding, such as hex, base64, or base64url. $numBytes is the number of binary bytes before text encoding; it is not the number of output characters.

If no entropy has been added before the first request for random output, Chilkat automatically obtains 32 bytes from the platform's cryptographic system entropy source to seed the PRNG.

For language bindings in which this method directly returns a string, check LastMethodSuccess before using the result.

Encoding does not add entropy: Hex, Base64, and other encodings represent the same random bytes in different textual forms. Choose numBytes from the security requirement of the key, nonce, salt, or token—not from the desired text length.

On failure it throws Chilkat2\Exception (or, with RaiseError set to false, returns null). $e->getMessage() (or the object's LastErrorText) explains why, and the object remains usable.

top
GenRandomBd
public function GenRandomBd(int $numBytes, BinData $bd): bool
Introduced in version 9.5.0.66

Generates $numBytes random bytes and appends them to the existing contents of the BinData object passed in $bd. The destination is not cleared before the bytes are added.

If no entropy has been added before the first request for random output, Chilkat automatically obtains 32 bytes from the platform's cryptographic system entropy source to seed the PRNG.

Returns true on success or false on failure.

Appending behavior: Call BinData.Clear first when the destination should contain only the newly generated bytes.

Returns true on success. On failure it throws Chilkat2\Exception (or, with RaiseError set to false, returns false). $e->getMessage() (or the object's LastErrorText) explains why, and the object remains usable.

More Information and Examples
top
GetEntropy
public function GetEntropy(int $numBytes, string $encoding): ?string
Introduced in version 9.5.0.52

Requests $numBytes bytes from the platform's cryptographic system entropy source and returns them using the text encoding named by $encoding. This obtains system-provided random seed material directly; it is different from asking the Fortuna generator to expand its current state with GenRandom.

For seeding this PRNG, 32 bytes normally provide the full 256-bit seed input expected by the implementation. Applications may request another amount when a protocol specifically requires raw bytes from the system source.

For language bindings in which this method directly returns a string, check LastMethodSuccess before using the result.

Usually unnecessary: The simplest secure use is to call a random-generation method directly. If no entropy was added explicitly, Chilkat automatically obtains 32 bytes of system entropy on the first generation request.

On failure it throws Chilkat2\Exception (or, with RaiseError set to false, returns null). $e->getMessage() (or the object's LastErrorText) explains why, and the object remains usable.

top
ImportEntropy
public function ImportEntropy(string $entropy): bool
Introduced in version 9.5.0.52

Imports the Base64-encoded entropy value previously returned by ExportEntropy. The imported material is supplied to the PRNG for use in its entropy and reseeding process.

Returns true if the value is valid and imported successfully. Returns false if it cannot be decoded or imported; check LastErrorText for details.

Recommended startup sequence: Import persisted entropy before the first random-generation call, then mix in fresh system entropy or allow the first generation call to perform Chilkat's automatic system seeding.

Returns true on success. On failure it throws Chilkat2\Exception (or, with RaiseError set to false, returns false). $e->getMessage() (or the object's LastErrorText) explains why, and the object remains usable.

More Information and Examples
top
RandomInt
public function RandomInt(int $low, int $high): int
Introduced in version 9.5.0.52

Returns a pseudorandom integer in the inclusive range from $low through $high. For example, RandomInt(4, 8) can return 4, 5, 6, 7, or 8.

The caller should ensure that $low is less than or equal to $high.

Cryptographic material: Use GenRandom, GenRandomBytes, or GenRandomBd when a protocol requires an exact number of random bytes. Do not assemble keys or nonces from decimal random integers unless the protocol explicitly defines that representation.
More Information and Examples
top
RandomPassword
public function RandomPassword(int $length, bool $mustIncludeDigit, bool $upperAndLowercase, string $mustHaveOneOf, string $excludeChars): ?string
Introduced in version 9.5.0.52

Generates a password of exactly $length characters while applying the requested composition rules:

ArgumentEffect
$mustIncludeDigitWhen true, require at least one digit from 0-9.
$upperAndLowercaseWhen true, require at least one lowercase and at least one uppercase US-ASCII letter.
$mustHaveOneOfWhen nonempty, require at least one character from this supplied set, such as !@#$%.
$excludeCharsExclude every listed character from the generated password. This is useful for ambiguous characters such as iIlL1oO0.

The requested length must be large enough to satisfy all enabled requirements, and exclusions must not remove every usable character from a required category. For language bindings in which this method directly returns a string, check LastMethodSuccess before using the result.

Password policy note: Longer randomly generated passwords generally provide more security than short passwords with many composition rules. Also ensure the receiving system accepts every character that may be generated.

On failure it throws Chilkat2\Exception (or, with RaiseError set to false, returns null). $e->getMessage() (or the object's LastErrorText) explains why, and the object remains usable.

More Information and Examples
top
RandomString
public function RandomString(int $length, bool $bDigits, bool $bLower, bool $bUpper): ?string
Introduced in version 9.5.0.52

Generates a string of exactly $length characters. The remaining arguments select the character categories placed in the source alphabet:

ArgumentWhen true
$bDigitsInclude digits 0-9.
$bLowerInclude lowercase ASCII letters a-z.
$bUpperInclude uppercase ASCII letters A-Z.

At least one character category must be enabled. The flags define the pool from which each character is chosen; they do not guarantee that every enabled category appears in a particular result.

Requirement-aware passwords: Use RandomPassword instead when the result must contain at least one digit, both uppercase and lowercase letters, or a required special character.

On failure it throws Chilkat2\Exception (or, with RaiseError set to false, returns null). $e->getMessage() (or the object's LastErrorText) explains why, and the object remains usable.

More Information and Examples
top