Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Crypto Laravel Package

spatie/crypto

Generate RSA key pairs and encrypt/decrypt (and sign/verify) data using private/public keys in PHP. Provides simple wrappers around OpenSSL for better DX, with support for loading keys from files and writing generated keys to disk.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Use Case Alignment: The package excels in scenarios requiring asymmetric encryption (RSA) for secure data transmission, digital signatures, or key-based authentication (e.g., API keys, user-to-user messaging, or third-party integrations). It is not a replacement for symmetric encryption (e.g., AES) for bulk data storage.
  • Laravel Synergy: Leverages Laravel’s dependency injection and configuration system seamlessly. Can be integrated as a service provider or facade for centralized key management.
  • Key Management: Supports file-based storage (e.g., storage/app/keys/) or environment variables, aligning with Laravel’s conventions for sensitive data.
  • Alternatives: Could complement Laravel’s built-in encrypt() (symmetric) or integrate with packages like spatie/laravel-encryption for hybrid approaches.

Integration Feasibility

  • Low Coupling: Minimal boilerplate; wraps OpenSSL functions with a clean API. No database migrations or schema changes required.
  • Dependency Risks: Relies on PHP’s openssl extension (enabled by default in most Laravel deployments). Critical: Verify openssl is available in staging/production.
  • Key Rotation: Manual process (generate new keys, update references). No built-in revocation or audit logging—must be handled at the application level (e.g., via Laravel’s encrypted column or a custom table).
  • Performance: RSA operations are CPU-intensive. Benchmark for high-throughput systems (e.g., encrypting thousands of messages/sec).

Technical Risk

Risk Area Mitigation Strategy
Key Compromise Store private keys in storage/app/keys/ with strict file permissions (e.g., chmod 600). Use Laravel’s filesystem disk for encryption.
OpenSSL Misconfig Test with openssl_get_error() and log failures. Fallback to a symmetric cipher (e.g., openssl_encrypt) if RSA is unavailable.
Key Size Limitations Defaults to 2048-bit RSA. For high-security needs, configure via KeyPair::generate(4096) but expect slower performance.
Serialization Encrypted data is base64-encoded strings. Ensure downstream systems (e.g., databases, APIs) can handle binary-safe storage.
Nonce/IV Handling Uses OpenSSL’s defaults. For custom security policies, extend the KeyPair class.

Key Questions

  1. Use Case Clarity:
    • Is this for data confidentiality (encrypt with public, decrypt with private) or authentication (sign with private, verify with public)?
    • Do we need hybrid encryption (RSA for key exchange + AES for bulk data)?
  2. Key Lifecycle:
    • How will keys be rotated? Who manages revocation? (e.g., Laravel policies + a key_revocations table).
  3. Performance:
    • What’s the expected volume of encrypted operations? Test with KeyPair::generate(4096) if needed.
  4. Compliance:
    • Does this meet regulatory requirements (e.g., FIPS 140-2 for RSA)? If not, consider libsodium alternatives.
  5. Error Handling:
    • How will failed decryption (e.g., tampered data) be logged/audited?

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • Service Provider: Register keys as a singleton (e.g., config/crypto.php for key paths).
    • Facades: Expose encrypt()/decrypt() globally (e.g., Crypto::encrypt($data)).
    • Artisan Commands: Add php artisan crypto:generate for key rotation.
  • Database:
    • Store encrypted data in TEXT columns (PostgreSQL/MySQL support binary-safe base64).
    • Use Laravel’s encrypt() for metadata if mixed modes are needed.
  • APIs:
    • Ideal for JWT payloads, webhook signatures, or PGP-like email encryption.
    • Pair with spatie/laravel-activitylog to audit decryption events.

Migration Path

  1. Pilot Phase:
    • Start with non-critical data (e.g., user preferences, audit logs).
    • Use PrivateKey::fromFile() with keys stored in storage/app/keys/.
  2. Gradual Rollout:
    • Replace plaintext API keys with RSA-encrypted secrets (e.g., config/services.php).
    • Add a decrypted_at timestamp to track usage.
  3. Hybrid Approach:
    • Encrypt sensitive fields with spatie/crypto, others with Laravel’s encrypt().
    • Use middleware to validate signatures on incoming requests.

Compatibility

Component Compatibility Notes
PHP Version Tested on PHP 8.1+. Ensure openssl extension is enabled (`php -m
Laravel No version constraints, but test with Laravel 9+ for facades/service providers.
Databases Base64-encoded data works in all SQL databases, but binary fields may be needed for large payloads.
Cloud Providers AWS KMS/GCP KMS: Consider using these instead for HSM-backed keys.
Legacy Systems If integrating with non-PHP systems, expose keys via a key management API.

Sequencing

  1. Setup:
    • Generate keys: php artisan crypto:generate --path=storage/app/keys.
    • Configure in config/services.php:
      'crypto' => [
          'private_key' => storage_path('app/keys/private_key.pem'),
          'public_key'  => storage_path('app/keys/public_key.pem'),
      ],
      
  2. Core Integration:
    • Create a CryptoService facade:
      use Spatie\Crypto\Rsa\PrivateKey;
      use Spatie\Crypto\Rsa\PublicKey;
      
      class CryptoService {
          public function encrypt(string $data): string {
              return PrivateKey::fromFile(config('crypto.private_key'))->encrypt($data);
          }
      }
      
  3. Validation:
    • Add a CryptoMiddleware to verify signatures on incoming requests.
    • Test edge cases: corrupted data, expired keys, large payloads (>2KB).

Operational Impact

Maintenance

  • Key Rotation:
    • Process: Generate new keys, update references in config/database, and phase out old keys (e.g., via a valid_until column).
    • Automation: Script key generation with KeyPair::generate() and deploy via CI/CD.
  • Monitoring:
    • Log decryption failures (e.g., try-catch blocks around decrypt()).
    • Track key usage (e.g., "private_key.pem used 12 times this month").
  • Backups:
    • Store private keys in a password-protected vault (e.g., Laravel Forge, AWS Secrets Manager).
    • Document recovery procedures for lost keys.

Support

  • Troubleshooting:
    • Common Issues:
      • OpenSSL error: Verify openssl extension is loaded.
      • Decryption failed: Check key paths in config or data corruption.
      • Mitigation: Add a CryptoException handler with detailed error logging.
    • Debugging Tools:
      • Use openssl rsa -check to validate keys manually.
      • Log OpenSSL errors with openssl_error_string().
  • Documentation:
    • Internal runbook for:
      • Key rotation steps.
      • Handling compromised keys.
      • Performance tuning (e.g., key size vs. latency).

Scaling

  • Performance Bottlenecks:
    • RSA Overhead: Each encryption/decryption is ~100ms (2048-bit). Cache keys in memory (e.g., PrivateKey as a singleton).
    • Load Testing: Simulate 1000 RPS with KeyPair::generate(2048) to validate hardware.
  • Distributed Systems:
    • Key Distribution: Use a centralized key management service (e.g., HashiCorp Vault) for microservices.
    • Caching: Store public keys in Redis for low-latency verification.
  • Horizontal Scaling:
    • Keys are stateless; no shared memory needed. However, key revocation requires a shared database or cache.

Failure Modes

Failure Scenario Impact Mitigation Strategy
Private Key Leak Data breach Rotate keys immediately; audit all encrypted data.
OpenSSL Extension Disabled Encryption fails Fallback to openssl_encrypt (symmetric) or alert ops.
Key Corruption Decryption failures Store keys
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport