VOOZH about

URL: https://deepwiki.com/hypervel/encryption/5-key-management

⇱ Key Management | hypervel/encryption | DeepWiki


Loading...
Menu

Key Management

This page documents the encryption key management system, covering key generation, storage, configuration, rotation, and the methods used to access keys. For the CLI command implementation details, see Key Generation Command. For key rotation implementation and the previous keys mechanism, see Key Rotation and Previous Keys.

Key Management Architecture

The key management system consists of three layers: the Encrypter class which holds and validates keys, the KeyGenerateCommand which creates keys, and the EncryptionFactory which parses and configures keys from configuration sources.

Key Storage and Access Methods in Encrypter

The Encrypter class provides four methods for accessing encryption keys:

MethodReturn TypePurposeSource Line
getKey()stringReturns the current encryption keysrc/Encrypter.php283-286
getAllKeys()arrayReturns current key plus all previous keyssrc/Encrypter.php291-294
getPreviousKeys()arrayReturns only the previous keys arraysrc/Encrypter.php299-302
previousKeys(array $keys)staticSets previous keys for key rotationsrc/Encrypter.php307-320

The $key property stores the current encryption key, while $previousKeys stores an array of legacy keys used during decryption for backward compatibility.

Key Generation and Configuration Flow


Sources: src/Commands/KeyGenerateCommand.php25-43 src/Commands/KeyGenerateCommand.php55-63 src/Encrypter.php74-79

Configuration Sources and Resolution

The system reads encryption keys from configuration using a fallback chain. The KeyGenerateCommand and EncryptionFactory both implement this resolution logic.

Configuration KeyPrimary SourceFallback SourceUsed By
Encryption Keyapp.keyencryption.keyKeyGenerateCommand (lines 70-71), EncryptionFactory
Cipher Algorithmapp.cipherencryption.cipherKeyGenerateCommand (lines 57-58), EncryptionFactory
Previous Keysencryption.previous_keysN/AEncryptionFactory

Configuration Resolution Implementation

The KeyGenerateCommand reads configuration in these methods:

generateRandomKey() src/Commands/KeyGenerateCommand.php55-63:

$cipher = $this->config->get('app.cipher') ?: $this->config->get('encryption.cipher');
return 'base64:' . base64_encode(Encrypter::generateKey($cipher));

setKeyInEnvironmentFile() src/Commands/KeyGenerateCommand.php68-82:

$currentKey = $this->config->get('app.key') ?: $this->config->get('encryption.key');
if (strlen($currentKey ?: '') !== 0 && (!$this->confirmToProceed())) {
 return false;
}

The publish/encryption.php configuration file shows the default structure:


Sources: src/Commands/KeyGenerateCommand.php55-63 src/Commands/KeyGenerateCommand.php68-82 publish/encryption.php11-21

Key Format and Encoding

Keys are stored with a base64: prefix format. The Encrypter::generateKey() method creates raw bytes, the KeyGenerateCommand adds the prefix and encoding, and the EncryptionFactory parses it back to raw bytes.

Key Format Specification

Generated Key Format: base64:<base64_encoded_binary_key>

Example: base64:xvKe8z7eDuxzxK8F3VqJ9wQ3pX5vN2sL1mR4tY6uI8o=

Key Size by Cipher

The Encrypter class defines key sizes in the $supportedCiphers array src/Encrypter.php35-40:

CipherKey Size (bytes)AEAD Mode
aes-128-cbc16No
aes-256-cbc32No
aes-128-gcm16Yes
aes-256-gcm32Yes

Key Generation and Parsing Process


The generateKey() static method src/Encrypter.php74-79 uses random_bytes() to create cryptographically secure keys:


Sources: src/Commands/KeyGenerateCommand.php55-63 src/Encrypter.php35-40 src/Encrypter.php74-79

Key Validation and Security

The Encrypter constructor and previousKeys() method validate keys to ensure they match the cipher's requirements.

Key Validation Logic

The supported() static method src/Encrypter.php64-71 performs validation:


This is invoked in two places:

  1. Constructor src/Encrypter.php47-59: Validates the primary key
  2. previousKeys() src/Encrypter.php307-320: Validates each previous key

If validation fails, a RuntimeException is thrown with the message:

"Unsupported cipher or incorrect key length. Supported ciphers are: {$ciphers}."

Environment File Update Safety

The KeyGenerateCommand implements safety checks in setKeyInEnvironmentFile() src/Commands/KeyGenerateCommand.php68-82:


The confirmToProceed() method (from ConfirmableTrait) checks if the application is in production and prompts for confirmation unless --force is specified.

Key Storage Security

The writeNewEnvironmentFileWith() method src/Commands/KeyGenerateCommand.php87-104 uses regex replacement to update the .env file:

  • Pattern: /^APP_KEY{$escaped}/m where $escaped is the properly escaped current key value
  • Prevents accidental key duplication or malformed entries
  • Validates that replacement occurred (checks if output differs from input)

Sources: src/Encrypter.php47-71 src/Encrypter.php307-320 src/Commands/KeyGenerateCommand.php68-82 src/Commands/KeyGenerateCommand.php87-117

Key Usage During Encryption and Decryption

The Encrypter class uses the current key for encryption and attempts all keys (current + previous) during decryption.

Encryption Key Usage

The encrypt() method src/Encrypter.php86-117 uses only $this->key:


Decryption Key Iteration

The decrypt() method src/Encrypter.php134-178 iterates through all keys using getAllKeys():


The getAllKeys() method src/Encrypter.php291-294 returns:


This enables transparent key rotation: data encrypted with old keys can still be decrypted as long as those keys remain in the previousKeys array.

Sources: src/Encrypter.php86-117 src/Encrypter.php134-178 src/Encrypter.php291-294

Key Lifecycle Management

The complete key lifecycle within the hypervel/encryption library follows a structured approach that supports both initial setup and ongoing operational requirements:

  1. Generation: Secure key creation using cryptographic functions
  2. Storage: Safe persistence in environment files with proper encoding
  3. Configuration: Integration with the Hyperf configuration system
  4. Validation: Factory-level key validation and parsing
  5. Usage: Runtime encryption/decryption operations
  6. Rotation: Transition to new keys while maintaining backward compatibility

This lifecycle ensures that encryption keys are properly managed throughout their operational lifespan while maintaining security best practices and supporting complex deployment scenarios.

Sources: src/Commands/KeyGenerateCommand.php25-43