Luminova Framework

PHP Luminova: Generating and Validating Encryption Keys

Last updated: 2026-11-28 20:57:12

A Comprehensive Guide to the luminova's Encryption Interface Class for PHP Framework Integration with OpenSSL and Sodium Libraries.

Luminova Encryption Key


Class Definition

  • Full namespace: \Luminova\Security\Encryption\Key
  • This class is marked as final and can't be subclassed
  • This class is a Final class

Constants

ConstantTypeValueDescription
TYPE_PUBLIC'public'Flag to generate a public key.
TYPE_PRIVATE'private'Flag to generate a private key.
TYPE_PAIR'pair'Flag to generate a public and private key-pair.
TYPE_RANDOM'random'Flag to generate a random key.
OPENSSL'openssl'Flag for openssl key handler.
SODIUM'sodium'Flag for sodium key handler.

Properties

ciphers

Supported AES encryption methods with their corresponding key sizes.

/**
 * @var array<string, array{key: int}>
 */
public static array $ciphers = [
  'AES-128-CBC' => ['key' => 16],
  'AES-192-CBC' => ['key' => 24],
  // ...
];

Each cipher entry specifies the size of the encryption key in bytes.

  • AES-128-CBC - 128-bit key (16 bytes)
  • AES-192-CBC - 192-bit key (24 bytes)
  • AES-256-CBC - 256-bit key (32 bytes)
  • AES-128-CBC-HMAC-SHA1 - 128-bit key (16 bytes)
  • AES-256-CBC-HMAC-SHA1 - 256-bit key (32 bytes)
  • AES-128-CBC-HMAC-SHA256 - 128-bit key (16 bytes)
  • AES-256-CBC-HMAC-SHA256 - 256-bit key (32 bytes)
  • AES-128-CFB - 128-bit key (16 bytes)
  • AES-192-CFB - 192-bit key (24 bytes)
  • AES-256-CFB - 256-bit key (32 bytes)
  • AES-128-CFB1 - 128-bit key (16 bytes)
  • AES-192-CFB1 - 192-bit key (24 bytes)
  • AES-256-CFB1 - 256-bit key (32 bytes)
  • AES-128-CFB8 - 128-bit key (16 bytes)
  • AES-192-CFB8 - 192-bit key (24 bytes)
  • AES-256-CFB8 - 256-bit key (32 bytes)
  • AES-128-CTR - 128-bit key (16 bytes)
  • AES-192-CTR - 192-bit key (24 bytes)
  • AES-256-CTR - 256-bit key (32 bytes)
  • AES-128-ECB - 128-bit key (16 bytes)
  • AES-192-ECB - 192-bit key (24 bytes)
  • AES-256-ECB - 256-bit key (32 bytes)
  • AES-128-OFB - 128-bit key (16 bytes)
  • AES-192-OFB - 192-bit key (24 bytes)
  • AES-256-OFB - 256-bit key (32 bytes)
  • AES-128-XTS - 128-bit key (16 bytes)
  • AES-256-XTS - 256-bit key (32 bytes)

Methods

constructor

Key generator for public, private, or random keys.

The constructor creates a key based on the given type:

  • Key::TYPE_PUBLIC: Generates a public key from an existing private key, or creates a new key pair.
  • Key::TYPE_PRIVATE: Generates a new private key.
  • Key::TYPE_PAIR: Generates a key-pair (private and public key).
  • Key::TYPE_RANDOM: Generates a random key string.
public function __construct(
    string $type = self::TYPE_PUBLIC,
    ?string $handler = null,
    ?string $passphrase = null,
    array $options = []
)

Parameters:

ParameterTypeDescription
$typestringType of key to generate (e.g, Key::TYPE_*) (default self::TYPE_PUBLIC).
$handler?stringCrypto handler (Key::OPENSSL or Key::SODIUM).
If null, defaults to the configured handler.
$passphrase?stringOptional passphrase for OpenSSL private keys, or for generating new ones (default null).
$optionsarray<string,mixed>Options for deriving or generating keys:
- private_key string: existing private/secret key.
- Other key options (default []).

Key Type Options:

  • For random type:

    • length: Requested OpenSSL hex length before rounding to full bytes. Pass the handler as a constructor argument.
  • For public type:

    • private_key: Use this private key to derive the public key or provide optional private key options to generate new private key.
  • For private type:

    • private_key_bits: Bit length for new private key (default: 2048).
    • private_key_type: Key type (default: OPENSSL_KEYTYPE_RSA).

See reference for more information https://php.net/manual/en/function.openssl-pkey-new.php

Examples:

Generate a random key string:

use Luminova\Security\Encryption\Key;

$key = new Key(Key::TYPE_RANDOM, handler: Key::OPENSSL, options: ['length' => 32]);

$randomKey = $key->getRandom();

Generate a private key:

use Luminova\Security\Encryption\Key;

$key = new Key(Key::TYPE_PRIVATE, handler: Key::OPENSSL, options: [
  'private_key_bits' => 2048,
  'private_key_type' => OPENSSL_KEYTYPE_RSA
]);

$privateKey = $key->getPrivate();

Generate a public key from an existing private key:

use Luminova\Security\Encryption\Key;

// Get private key from file.
$private = file_get_contents('/path/to/private.pem');
if ($private === false) {
    throw new RuntimeException('Unable to read the private key.');
}

$key = new Key(Key::TYPE_PUBLIC, handler: Key::OPENSSL, options: ['private_key' => $private]);

$publicKey = $key->getPublic();

// Or $key->getResult()

getResult

Get the generated key value.

public function getResult(): string|array|null

Return:

string|array<string,mixed>|null - Returns a key string, a key pair, or null if no result is available.

KeyTypeDescription
privatestringEncoded private key.
publicstring&#124;falseEncoded public key, or false if extraction fails.

getPublic

Get the generated public key.

public function getPublic(): ?string

Return:

string|null - Public key string, or null if not available.


getPrivate

Get the generated private key.

public function getPrivate(): ?string

Return:

string|null - Private key string (PEM format), or null if not available.


getRandom

Get the generated random key.

public function getRandom(bool $toHex = true): ?string

Parameters:

ParameterTypeDescription
$toHexboolWhether to return the key in hex format (default: true).

Return:

string|null - Random key string in hex or raw bytes, or null if not available.


size

Retrieve the key size based on cipher method.

public static function size(?string $method = null): int

Parameters:

ParameterTypeDescription
$method?stringCipher method name (default: App\Config\Encryption->method).

Return:

int - Return the key size in bytes.


cipher

Retrieve cipher information by method.

public static function cipher(?string $method = null): ?array

Parameters:

ParameterTypeDescription
$method?stringCipher method name (default: App\Config\Encryption->method).

Return:

array<string,int>|null - Returns the cipher entry, or null if the method is unlisted.

KeyTypeDescription
keyintSize recorded for the cipher. See size() for the value used by the helper.

method

Retrieve encryption method from default configuration.

public static function method(string $default = 'AES-128-CBC'): string

Parameters:

ParameterTypeDescription
$defaultstringThe default cipher method if not found.

Return:

string - Return the cipher method or default.


handler

Determine the application encryption handler from configuration.

Checks if the required PHP extension is loaded and optionally asserts that the handler is valid, throwing exceptions if not.

public static function handler(bool $assert = false): string|bool

Parameters:

ParameterTypeDescription
$assertboolIf true, throws an exception on invalid handler.

Return:

string|bool - Return handler name (self::OPENSSL|self::SODIUM) or false if unavailable.

Throws:


isSupported

Verify that the given key length matches the expected size for the cipher method.

If no cipher method is provided, the default from App\Config\Encryption->methodwill be used.

public static function isSupported(string $key, ?string $method = null): bool

Parameters:

ParameterTypeDescription
$keystringThe encryption key to validate.
$method?stringOptional cipher method (default: App\Config\Encryption->method).

Return:

bool - Return true if the key length is valid for the cipher, false otherwise.


isPrivate

Validate if a given key is private.

public static function isPrivate(mixed $key, ?string $passphrase = null, ?string $handler = null): bool

Parameters:

ParameterTypeDescription
$keymixedKey in PEM format (OpenSSL) or Base64-encoded string (Sodium).
$passphrase?stringPassphrase for OpenSSL private keys (default null).
$handler?stringEncryption handler (e.g, Key::OPENSSL or Key::SODIUM) (default: auto-detects).

Return:

bool - Return true if valid private key, false otherwise.


isPublic

Validate if a given key is public.

public static function isPublic(mixed $key, ?string $handler = null): bool

Parameters:

ParameterTypeDescription
$keymixedKey in PEM format (OpenSSL) or Base64-encoded string (Sodium).
$handler?stringEncryption handler (e.g, Key::OPENSSL or Key::SODIUM) (default: auto-detects).

Return:

bool - Return true if valid public key, false otherwise.


isMatch

Validate whether a private and public key pair match.

public static function isMatch(
    mixed $privateKey,
    mixed $publicKey,
    int $algo = OPENSSL_ALGO_SHA256,
    ?string $data = null,
    ?string $passphrase = null,
    ?string $handler = null
): bool

Parameters:

ParameterTypeDescription
$privateKeymixedPrivate key (PEM for OpenSSL or Base64 for Sodium).
$publicKeymixedPublic key (PEM for OpenSSL or Base64 for Sodium).
$algointOpenSSL algorithm (default: OPENSSL_ALGO_SHA256).
$data?stringOptional data to sign (default: 'test_message').
$passphrase?stringPassphrase for OpenSSL private keys (default null).
$handler?stringEncryption handler (e.g., Key::OPENSSL or Key::SODIUM) (default: auto-detects).

Return:

bool - Return true if keys match, false otherwise.


newPublic

Generate a public key from an existing private key, or create a new key pair.

If a private key is provided, the public key will be derived from it.If not, a new private/public key pair will be generated using Openssl.

Derive or generate a public key using the chosen crypto handler.

  • For OpenSSL:If a private key is provided, the public key is derived from it.If not, a new private key is created and its public key is extracted.

  • For Sodium:If a secret (private) key is provided, the corresponding public key is derived.If not, a new key-pair is generated and the public key is returned.

public static function newPublic(
    ?string $handler = null,
    ?string $passphrase = null,
    array $options = []
): string|bool

Parameters:

ParameterTypeDescription
$handler?stringCrypto handler (Key::OPENSSL or Key::SODIUM).
If null, defaults to the configured handler.
$passphrase?stringOptional passphrase for OpenSSL private keys,
or for generating new ones (default null).
$optionsarray<string,mixed>Options for deriving or generating keys:
- private_key string: existing private/secret key (default []).

Return:

string|bool - Return the generated/derived public key (PEM for OpenSSL, base64 for Sodium), or false on failure.

or false on failure.


newPrivate

Generate a new private key.

Creates a private key using OpenSSL asymmetric encryption. If no options are given, a default 2048-bit RSA key is generated.

Creates a private key using the given handler.

  • Openssl: generates a PEM-encoded RSA key (default 2048-bit).
  • Sodium: generates an Ed25519 private key (Base64-encoded).
public static function newPrivate(
    ?string $handler = null,
    ?string $passphrase = null,
    ?array $options = []
): string|bool

Parameters:

ParameterTypeDescription
$handler?stringEncryption handler (Key::OPENSSL or Key::SODIUM) (default null).
$passphrase?stringOptional key passphrase (OpenSSL only) (default null).
$optionsarray<string,mixed>&#124;nullOptions for key generation (OpenSSL only) (default []).

Return:

string|bool - Return a private key string (PEM or Base64) or false on failure.

Note:

  • If an empty options array is passed, the options default to:

    • private_key_bits: Number of bits (default: 2048).
    • private_key_type: Key type (default: OPENSSL_KEYTYPE_RSA).
  • Pass null to fall back to the Openssl default configuration.


newKeyPair

Generate an OpenSSL private and public key pair.

  • For OpenSSL:A PEM-encoded private key is generated (optionally protected with a passphrase),and the corresponding public key is extracted.
public static function newKeyPair(
    ?string $handler = null,
    ?string $passphrase = null,
    array $options = []
): array|bool

Parameters:

ParameterTypeDescription
$handler?stringCrypto handler (Key::OPENSSL or Key::SODIUM).
If null, defaults to the configured handler.
$passphrase?stringOptional passphrase for OpenSSL private key generation (default null).
$optionsarray<string,mixed>Options for generating the key pair:
- For OpenSSL: key size, type, etc (default []).

Return:

array<string,mixed>|false - Returns the generated OpenSSL pair, or false if private-key generation fails.

KeyTypeDescription
privatestringPEM-encoded private key.
publicstring&#124;falsePEM-encoded public key, or false if extraction fails.

Example:

use Luminova\Security\Encryption\Key;

$pair = Key::newKeyPair(Key::OPENSSL);
if ($pair !== false && $pair['public'] !== false) {
    $matches = Key::isMatch($pair['private'], $pair['public'], handler: Key::OPENSSL);
}

newRandom

Generate a random encryption key.

This method creates a random key using the selected encryption handler. If no handler or key length is provided, it falls back to the application’s default handler and cipher size.

Uses the specified handler:

  • Sodium: generates a secretbox key (32 bytes).
  • OpenSSL: generates random bytes using half the requested length, rounded up. If omitted, the requested length comes from size().
public static function newRandom(
    ?string $handler = null,
    ?int $length = null,
    bool $toHex = true
): string

Parameters:

ParameterTypeDescription
$handler?stringEncryption handler (Key::OPENSSL or Key::SODIUM) (default null).
$length?intOpenSSL generates ceil($length / 2) bytes. Sodium uses its fixed 32-byte key size.
$toHexboolIf true, return the key as a hex-encoded string. If false, return raw bytes (default: true).

Return:

string - Return random key string (hex or raw).