VOOZH about

URL: https://deepwiki.com/friendsofhyperf/components/5.3-encryption-and-security-components

⇱ Encryption and Security Components | friendsofhyperf/components | DeepWiki


Loading...
Last indexed: 14 February 2026 (15d5ca)
Menu

Encryption and Security Components

This document covers three security-focused infrastructure components that provide encryption, XSS protection, and bot prevention capabilities:

  • Encryption: AES-based encryption/decryption with support for serializing PHP closures
  • Purifier: HTML sanitization using HTMLPurifier to prevent XSS attacks
  • reCAPTCHA: Google reCAPTCHA integration for bot detection and form protection

For distributed locking mechanisms, see Lock Component. For input validation and type-safe data handling, see Validated DTOs. For rate limiting, see Configuration and Rate Limiting.


Component Overview and Dependencies


Sources: src/encryption/composer.json1-57 src/purifier/composer.json1-56 src/recaptcha/composer.json1-56 src/macros/composer.json32 src/facade/composer.json28


Encryption Component Architecture

The encryption component provides AES-256-CBC and AES-128-CBC encryption with support for serializing PHP closures, enabling secure storage of sensitive data and even callable functions.

Core Classes and Services


Sources: src/encryption/composer.json22-43 CHANGELOG-3.1.md240

Encryption Configuration

The encryption component requires an application key configured in the environment:

Configuration KeyEnvironment VariableDescriptionDefault
app_keyAPP_KEYBase64-encoded encryption keyRequired
cipherAPP_CIPHERCipher algorithmAES-256-CBC

Key Generation: The component provides a key generation method that produces properly formatted base64-encoded keys suitable for AES encryption.

Supported Ciphers:

  • AES-256-CBC - 256-bit AES encryption (recommended)
  • AES-128-CBC - 128-bit AES encryption

Sources: src/encryption/composer.json26-32

Helper Functions and Integration Points

The encryption component provides multiple access patterns:

Global Helper Functions


These functions provide quick access to encryption services from anywhere in the application.

String Macro Integration

As of v3.1.64, the macros component provides encryption methods on the Str and Stringable classes:


This integration allows for fluent encryption operations within string manipulation chains.

Sources: src/encryption/composer.json40-43 CHANGELOG-3.1.md240 src/macros/composer.json32

Closure Serialization Support

When the optional opis/closure library is installed, the encryption component can serialize and encrypt PHP closures:


This capability enables:

  • Storing callbacks in cache or database
  • Queuing closures for async execution
  • Serializing complex callback logic

Implementation Details:

  • Closure serialization is automatically detected when opis/closure is available
  • The Encrypter class uses reflection to determine if closure serialization is supported
  • Serialization happens before encryption, deserialization after decryption

Sources: src/encryption/composer.json34-36

Coroutine Safety and Context Management

The encryption component leverages Hyperf's context system to ensure coroutine safety:


Sources: src/encryption/composer.json27

Exception Handling and Events

The encryption component dispatches events when decryption fails:

Exception Types:

  • DecryptException - Thrown when decryption fails due to invalid payload, MAC mismatch, or unserialization errors

Event Integration: The component uses hyperf/event to dispatch exceptions, allowing applications to:

  • Log decryption failures
  • Track potential security issues
  • Implement custom error handling

Sources: src/encryption/composer.json30


Purifier Component for XSS Protection

The purifier component provides HTML sanitization using the battle-tested HTMLPurifier library to prevent cross-site scripting (XSS) attacks.

Purifier Architecture


Sources: CHANGELOG-3.1.md427 CHANGELOG-3.1.md360

Configuration and Allowed Elements

The purifier component uses HTMLPurifier's configuration system to define:

Common Configuration Options:

  • Allowed Tags: Whitelist of HTML tags (e.g., p, a, strong, em)
  • Allowed Attributes: Per-tag attribute whitelist (e.g., href on <a>, src on <img>)
  • URL Filtering: Protocol whitelist (e.g., http, https, mailto)
  • AutoFormat: Automatic formatting options (e.g., line breaks, paragraphs)
  • Cache: Cache directory for performance optimization

Default Security Settings:

  • Scripts and event handlers removed
  • Dangerous tags (<script>, <iframe>, <object>) stripped
  • CSS filtered for dangerous expressions
  • URL protocols validated

Sources: CHANGELOG-3.1.md427-429

Usage Patterns

Server-Side Purification


Client-Side Purification

As mentioned in the changelog, the component supports client-side output purifying, allowing applications to sanitize HTML before sending it to the browser.

Sources: CHANGELOG-3.1.md360

Performance Considerations

HTMLPurifier is thorough but can be resource-intensive:

Optimization Strategies:

  1. Caching: Store sanitized HTML to avoid repeated processing
  2. Async Queue: Purify large content in background jobs
  3. Selective Purification: Only purify user-generated content, not trusted sources
  4. Definition Cache: Enable HTMLPurifier's definition cache

reCAPTCHA Integration Component

The reCAPTCHA component provides Google reCAPTCHA integration for protecting forms and endpoints from automated abuse.

reCAPTCHA Architecture and Verification Flow


Configuration

Configuration KeyEnvironment VariableDescriptionRequired
site_keyRECAPTCHA_SITE_KEYPublic site key for client-side renderingYes
secret_keyRECAPTCHA_SECRET_KEYSecret key for server-side verificationYes
versionRECAPTCHA_VERSIONreCAPTCHA version (v2, v3)Yes
score_thresholdRECAPTCHA_SCORE_THRESHOLDMinimum score for v3 (0.0-1.0)No (v3 only)
timeoutRECAPTCHA_TIMEOUTAPI request timeout in secondsNo

Validation Rule Integration

The component integrates with Hyperf's validation system:


reCAPTCHA v2 vs v3

reCAPTCHA v2:

  • Checkbox-based challenge
  • "I'm not a robot" user interaction
  • Returns true/false verification result

reCAPTCHA v3:

  • Invisible, no user interaction
  • Returns risk score (0.0 = bot, 1.0 = human)
  • Application defines score threshold
  • More seamless user experience

HTTP Client Integration

The reCAPTCHA component uses Guzzle for making verification requests to Google's API:

Verification Endpoint:

POST https://www.google.com/recaptcha/api/siteverify

Request Parameters:

  • secret - The shared secret key
  • response - The token from the client
  • remoteip - Optional user IP address

Response Fields:

  • success - Boolean indicating verification success
  • score - Risk score (v3 only, 0.0-1.0)
  • action - Action name (v3 only)
  • challenge_ts - Timestamp of challenge
  • hostname - Hostname of the site
  • error-codes - Array of error codes if verification failed

Integration with Other Components

Facade Integration

The encryption component provides a facade for convenient static access:


Sources: src/facade/composer.json28

Macro System Integration

The macros component extends Str and Stringable with encryption methods:

MethodDescriptionAdded in Version
Str::encrypt()Encrypt a stringv3.1.64
Str::decrypt()Decrypt a stringv3.1.64

This enables fluent encryption within string manipulation chains:


Sources: CHANGELOG-3.1.md240 src/macros/composer.json32

Helper Functions Integration

The helpers component provides global access to encryption:


Sources: src/encryption/composer.json40-43


Testing Security Components

The monorepo includes test suites for security components:


Test Coverage Areas:

  1. Encryption Tests: AES encryption/decryption, closure serialization, key generation
  2. Purifier Tests: XSS attack prevention, allowed tag filtering, configuration validation
  3. reCAPTCHA Tests: Token verification, score threshold validation, API integration

Sources: tests/Pest.php22


Security Best Practices

Encryption Key Management

  1. Generate Strong Keys: Use Encrypter::generateKey() or php bin/hyperf.php key generation command
  2. Store Securely: Keep APP_KEY in .env file, never commit to version control
  3. Rotate Regularly: Implement key rotation strategy for high-security applications
  4. Backup Keys: Maintain secure backups of encryption keys to prevent data loss

XSS Prevention with Purifier

  1. Default Deny: Use restrictive default configuration, whitelist only necessary tags
  2. Context-Specific: Apply different purifier configs for different content types (comments, articles, etc.)
  3. Cache Purified: Store purified HTML to avoid repeated processing overhead
  4. Trust Boundaries: Only purify untrusted user input, not admin-generated content

reCAPTCHA Implementation

  1. Score Tuning: For v3, tune score threshold based on your traffic patterns (typical: 0.5)
  2. Action Names: Use distinct action names per form to track effectiveness
  3. Fallback: Provide fallback mechanism for users who fail reCAPTCHA
  4. Rate Limiting: Combine with rate limiting (see Configuration and Rate Limiting) for defense in depth

Component Dependencies Summary

ComponentKey DependenciesOptional Dependencies
Encryptionhyperf/di, hyperf/event, hyperf/context, hyperf/stringableopis/closure
Purifierhyperf/di, ezyang/htmlpurifier-
reCAPTCHAhyperf/di, hyperf/validation, guzzlehttp/guzzle-

All three components follow Hyperf's ConfigProvider pattern for dependency injection and service registration.

Sources: src/encryption/composer.json22-36 src/purifier/composer.json1-56 src/recaptcha/composer.json1-56

Refresh this wiki

On this page