PHP Luminova: Generating and Validating Encryption Keys
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
| Constant | Type | Value | Description |
|---|---|---|---|
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:
| Parameter | Type | Description |
|---|---|---|
$type | string | Type of key to generate (e.g, Key::TYPE_*) (default self::TYPE_PUBLIC). |
$handler | ?string | Crypto handler (Key::OPENSSL or Key::SODIUM).If null, defaults to the configured handler. |
$passphrase | ?string | Optional passphrase for OpenSSL private keys, or for generating new ones (default null). |
$options | array<string,mixed> | Options for deriving or generating keys: - private_key string: existing private/secret key.- Other key options (default []). |
Key Type Options:
For
randomtype:length: Requested OpenSSL hex length before rounding to full bytes. Pass the handler as a constructor argument.
For
publictype:private_key: Use this private key to derive the public key or provide optional private key options to generate new private key.
For
privatetype: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|nullReturn:
string|array<string,mixed>|null - Returns a key string, a key pair, or null if no result is available.
| Key | Type | Description |
|---|---|---|
private | string | Encoded private key. |
public | string|false | Encoded public key, or false if extraction fails. |
getPublic
Get the generated public key.
public function getPublic(): ?stringReturn:
string|null - Public key string, or null if not available.
getPrivate
Get the generated private key.
public function getPrivate(): ?stringReturn:
string|null - Private key string (PEM format), or null if not available.
getRandom
Get the generated random key.
public function getRandom(bool $toHex = true): ?stringParameters:
| Parameter | Type | Description |
|---|---|---|
$toHex | bool | Whether 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): intParameters:
| Parameter | Type | Description |
|---|---|---|
$method | ?string | Cipher 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): ?arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$method | ?string | Cipher method name (default: App\Config\Encryption->method). |
Return:
array<string,int>|null - Returns the cipher entry, or null if the method is unlisted.
| Key | Type | Description |
|---|---|---|
key | int | Size 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'): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$default | string | The 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|boolParameters:
| Parameter | Type | Description |
|---|---|---|
$assert | bool | If true, throws an exception on invalid handler. |
Return:
string|bool - Return handler name (self::OPENSSL|self::SODIUM) or false if unavailable.
Throws:
- Luminova\Exceptions\EncryptionException - If $assert is true and the handler is invalid or unsupported.
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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | The encryption key to validate. |
$method | ?string | Optional 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$key | mixed | Key in PEM format (OpenSSL) or Base64-encoded string (Sodium). |
$passphrase | ?string | Passphrase for OpenSSL private keys (default null). |
$handler | ?string | Encryption 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$key | mixed | Key in PEM format (OpenSSL) or Base64-encoded string (Sodium). |
$handler | ?string | Encryption 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
): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$privateKey | mixed | Private key (PEM for OpenSSL or Base64 for Sodium). |
$publicKey | mixed | Public key (PEM for OpenSSL or Base64 for Sodium). |
$algo | int | OpenSSL algorithm (default: OPENSSL_ALGO_SHA256). |
$data | ?string | Optional data to sign (default: 'test_message'). |
$passphrase | ?string | Passphrase for OpenSSL private keys (default null). |
$handler | ?string | Encryption 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|boolParameters:
| Parameter | Type | Description |
|---|---|---|
$handler | ?string | Crypto handler (Key::OPENSSL or Key::SODIUM).If null, defaults to the configured handler. |
$passphrase | ?string | Optional passphrase for OpenSSL private keys, or for generating new ones (default null). |
$options | array<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|boolParameters:
| Parameter | Type | Description |
|---|---|---|
$handler | ?string | Encryption handler (Key::OPENSSL or Key::SODIUM) (default null). |
$passphrase | ?string | Optional key passphrase (OpenSSL only) (default null). |
$options | array<string,mixed>|null | Options 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
nullto 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|boolParameters:
| Parameter | Type | Description |
|---|---|---|
$handler | ?string | Crypto handler (Key::OPENSSL or Key::SODIUM).If null, defaults to the configured handler. |
$passphrase | ?string | Optional passphrase for OpenSSL private key generation (default null). |
$options | array<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.
| Key | Type | Description |
|---|---|---|
private | string | PEM-encoded private key. |
public | string|false | PEM-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
): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$handler | ?string | Encryption handler (Key::OPENSSL or Key::SODIUM) (default null). |
$length | ?int | OpenSSL generates ceil($length / 2) bytes. Sodium uses its fixed 32-byte key size. |
$toHex | bool | If 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).