VOOZH about

URL: https://deepwiki.com/hypervel/encryption/5.1-key-generation-command

⇱ Key Generation Command | hypervel/encryption | DeepWiki


Loading...
Menu

Key Generation Command

This document describes the key:generate console command provided by the hypervel/encryption package. The command generates cryptographically secure encryption keys, stores them in the application's .env file, and updates the runtime configuration.

For information about using generated keys with key rotation strategies, see Key Rotation and Previous Keys. For details on how the generated keys are used by the encryption system, see The Encrypter Implementation.


Command Overview

The KeyGenerateCommand class implements the key:generate console command, which is the primary administrative tool for encryption key management in Hyperf and Hypervel applications.

AspectDetails
Command Namekey:generate
ClassHypervel\Encryption\Commands\KeyGenerateCommand
Base ClassHyperf\Command\Command
ExtendsHyperfCommand
Uses TraitsHyperf\Command\Concerns\Confirmable
RegistrationAuto-registered via ConfigProvider

The command serves two primary functions:

  1. Generate cryptographically secure encryption keys appropriate for the configured cipher
  2. Safely persist keys to the application's .env file with production safeguards

Sources: src/Commands/KeyGenerateCommand.php1-118


Command Execution Flow


Sources: src/Commands/KeyGenerateCommand.php25-43 src/Commands/KeyGenerateCommand.php68-82 src/Commands/KeyGenerateCommand.php87-104


Command Options

The command accepts two optional flags that modify its behavior:

--show Option

PropertyValue
Flag--show
TypeInputOption::VALUE_OPTIONAL
PurposeDisplay generated key without modifying files
Use CaseGenerate keys for external systems or manual configuration

When --show is specified, the command generates a key and outputs it to the console without making any changes to the .env file or runtime configuration src/Commands/KeyGenerateCommand.php29-31

--force Option

PropertyValue
Flag--force
TypeInputOption::VALUE_OPTIONAL
PurposeBypass production environment confirmation prompts
Use CaseAutomated deployments and CI/CD pipelines

The --force flag is consumed by the Confirmable trait to skip confirmation prompts when replacing existing keys in production environments src/Commands/KeyGenerateCommand.php49

Sources: src/Commands/KeyGenerateCommand.php45-50


Key Generation Process

Cipher Detection and Key Length


The key generation process follows these steps:

  1. Cipher Resolution: The command checks app.cipher first, falling back to encryption.cipher if not found src/Commands/KeyGenerateCommand.php57-58

  2. Random Key Generation: Calls Encrypter::generateKey($cipher) which generates cryptographically secure random bytes using PHP's random_bytes() function

  3. Base64 Encoding: The raw binary key is base64-encoded for safe storage in environment files src/Commands/KeyGenerateCommand.php60-61

  4. Prefix Convention: The encoded key is prefixed with base64: to indicate to the EncryptionFactory that decoding is required src/Commands/KeyGenerateCommand.php60

Sources: src/Commands/KeyGenerateCommand.php55-63


Environment File Updates

Regex Pattern Generation

The command uses a sophisticated regex-based approach to safely update the .env file:


The pattern generation handles several edge cases:

  1. Empty Keys: When no key exists, matches APP_KEY= with any value or no value
  2. Special Characters: Uses preg_quote() to escape regex metacharacters in existing keys src/Commands/KeyGenerateCommand.php114
  3. Multiline Mode: The /m flag ensures the pattern matches at the start of lines, not just the start of the file src/Commands/KeyGenerateCommand.php116

Sources: src/Commands/KeyGenerateCommand.php109-117

File Writing Process

StepActionError Handling
1. Readfile_get_contents(BASE_PATH . '/.env')N/A (will throw PHP error)
2. Replacepreg_replace($pattern, 'APP_KEY=' . $key, $input)Checks for $replaced === $input or $replaced === null
3. ValidateEnsure replacement occurredError message if APP_KEY not found
4. Writefile_put_contents($envPath, $replaced)N/A (will throw PHP error)

The validation step src/Commands/KeyGenerateCommand.php95-98 ensures that:

  • The replacement actually changed the file content
  • The regex pattern successfully matched an APP_KEY line
  • The operation wasn't silently ignored due to pattern mismatch

Sources: src/Commands/KeyGenerateCommand.php87-104


Production Safety Mechanisms

Confirmable Trait Integration


The safety mechanism implements multiple layers of protection:

  1. Existing Key Check: Only triggers confirmation if a non-empty key already exists src/Commands/KeyGenerateCommand.php73

  2. Confirmable Trait: The confirmToProceed() method from Hyperf\Command\Concerns\Confirmable checks:

    • Current environment setting
    • Presence of --force flag
    • User confirmation response
  3. Abort Path: If confirmation is declined, returns false and the command exits without making changes src/Commands/KeyGenerateCommand.php74

Sources: src/Commands/KeyGenerateCommand.php16 src/Commands/KeyGenerateCommand.php68-82


Runtime Configuration Update

After successfully writing to the .env file, the command updates the runtime configuration:


The dual-update strategy ensures:

Update TargetTimingScope
.env filePersistentAll future application boots
Runtime configImmediateCurrent running process

The runtime update via $this->config->set('app.key', $key) src/Commands/KeyGenerateCommand.php40 ensures that any Encrypter instances created after the command completes will use the new key, even within the same process execution.

Sources: src/Commands/KeyGenerateCommand.php36-42


Configuration Resolution Strategy

The command accesses configuration through two namespaces:































OperationPrimary ConfigFallback ConfigWrite Target
Get cipherapp.cipherencryption.cipherN/A
Get current keyapp.keyencryption.keyapp.key
Set new keyN/AN/Aapp.key

This resolution strategy provides backward compatibility with Hyperf applications (which use app namespace) while supporting the newer Hypervel convention of a dedicated encryption namespace.

Sources: src/Commands/KeyGenerateCommand.php57-58 src/Commands/KeyGenerateCommand.php70-71 src/Commands/KeyGenerateCommand.php111-112


Common Usage Patterns

Standard Key Generation


Behavior:

  • Generates a new key for the configured cipher
  • Prompts for confirmation if a key already exists and in production
  • Updates both .env file and runtime configuration
  • Outputs success message

Display-Only Mode


Behavior:

  • Generates a key and displays it to console
  • Makes no changes to .env or configuration
  • Useful for generating keys for external systems or manual configuration

Forced Replacement


Behavior:

  • Bypasses confirmation prompts even in production
  • Suitable for automated deployment scripts
  • Should be used cautiously to avoid unintended key replacement

CI/CD Pipeline Usage


Pattern: Check if a valid key exists before generating, using --force to avoid interactive prompts in automated environments.

Sources: src/Commands/KeyGenerateCommand.php25-43


Constructor Dependencies

The command is instantiated with two critical dependencies injected via constructor:

DependencyTypeUsage
$containerPsr\Container\ContainerInterfacePSR-11 container (currently unused in implementation)
$configHyperf\Contract\ConfigInterfaceConfiguration access for reading and writing keys

The command name 'key:generate' is passed to the parent HyperfCommand constructor src/Commands/KeyGenerateCommand.php22 which registers the command with the console system.

Sources: src/Commands/KeyGenerateCommand.php18-23


Integration with Encrypter Class

The key generation logic delegates to the static Encrypter::generateKey() method:


This separation of concerns ensures:

  • The Encrypter class owns the cipher-to-length mapping logic
  • The command is responsible only for encoding and storage
  • Changes to supported ciphers automatically affect key generation

Sources: src/Commands/KeyGenerateCommand.php61


Error Scenarios

ScenarioDetectionResponseExit Code
No APP_KEY in .env$replaced === $input after preg_replace()Error message: "Unable to set application key..."Non-zero
Regex error$replaced === nullError message: "Unable to set application key..."Non-zero
User declines confirmationconfirmToProceed() returns falseSilent exit, no error messageZero (graceful)
Invalid cipher configurationN/A (handled by Encrypter::generateKey())Would throw exception from EncrypterNon-zero

The most common error occurs when the .env file doesn't contain an APP_KEY line at all src/Commands/KeyGenerateCommand.php95-98 The command explicitly checks for this and provides a clear error message.

Sources: src/Commands/KeyGenerateCommand.php87-104