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

Laravel Model Encryption Laravel Package

magros/laravel-model-encryption

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Encryption Scope: The package provides field-level encryption for Eloquent models, aligning well with compliance-driven use cases (e.g., GDPR, HIPAA) where sensitive data (PII, payment details) must be encrypted at rest.
  • Transparency: Encryption is implicit (via getAttribute/setAttribute overrides), reducing boilerplate but requiring careful attribute selection to avoid unintended encryption (e.g., non-sensitive fields like created_at).
  • Database Agnostic: Works with any Laravel-supported database (MySQL, PostgreSQL, SQLite), but performance implications may vary (e.g., encrypted fields cannot use database-level indexing efficiently).
  • Alternatives Considered: Native Laravel encryption (e.g., encrypt()) or database-level encryption (e.g., PostgreSQL’s pgcrypto) may offer more granular control but lack the convenience of model-level automation.

Integration Feasibility

  • Low-Coupling Design: The trait-based approach minimizes invasive changes to existing models. Backward compatibility is preserved if encryption is applied selectively.
  • Configuration Override: Published config/encrypt.php allows customization of encryption keys, algorithms (AES-256-CBC default), and excluded fields, reducing hardcoding risks.
  • Dependency Risks: Relies on Laravel’s Eloquent core and PHP’s openssl extension. Key management (e.g., storing encryption keys securely) is the TPM’s responsibility.

Technical Risk

  • Performance Overhead:
    • Encryption/decryption adds CPU latency per attribute access. Benchmark with production-like data volumes (e.g., 10K encrypted fields/sec).
    • Database bloat: Encrypted fields consume ~33% more storage (Base64 encoding).
  • Debugging Complexity:
    • Encrypted data in logs/queries obscures troubleshooting. Logging strategy must exclude encrypted fields or use placeholders.
    • Race conditions: Concurrent writes to the same model may corrupt data if not handled atomically (package assumes single-threaded operations).
  • Key Rotation:
    • No built-in key rotation mechanism. Migration path for re-encrypting data under new keys must be planned (e.g., double-encrypt during transition).
  • Edge Cases:
    • Casting conflicts: If a model uses casts (e.g., date), the package may interfere. Test with complex attribute types.
    • Serialization: Encrypted models may fail when serialized (e.g., Redis caching). Explicitly exclude from cache or handle via Serializable interface.

Key Questions

  1. Compliance Requirements:
    • Does the encryption meet regulatory standards (e.g., AES-256-CBC with HMAC for integrity)?
    • Are there audit logs for encryption/decryption events?
  2. Key Management:
    • How will encryption keys be stored/rotated? (e.g., AWS KMS, HashiCorp Vault, Laravel’s env).
    • Is key escrow needed for recovery?
  3. Performance Baseline:
    • What’s the acceptable latency for encrypted field access? (Measure with microtime().)
  4. Data Recovery:
    • How will corrupted/lost keys be handled? (e.g., backup encrypted data + keys separately.)
  5. Team Skills:
    • Does the team have experience with cryptographic best practices to avoid pitfalls (e.g., IV reuse)?

Integration Approach

Stack Fit

  • Laravel Ecosystem: Seamless integration with Eloquent, Query Builder, and Laravel’s service container. No framework changes required.
  • PHP Version: Compatible with PHP 7.4+ (Laravel 8+). Deprecation risk if using older PHP versions.
  • Database Compatibility:
    • MySQL/PostgreSQL: Works out-of-the-box. PostgreSQL tip: Use bytea for binary storage to avoid Base64 overhead.
    • SQLite: Avoid if encryption is critical (SQLite lacks native encryption; file-level encryption recommended instead).
  • Caching Layers:
    • Redis/Memcached: Encrypted data cannot be cached directly. Use application-level caching with decrypted values.
    • Query Caching: Disable for models with encrypted fields ($model->useQueryCache = false;).

Migration Path

  1. Pilot Phase:
    • Start with non-critical models (e.g., user profiles) to validate performance and debugging workflows.
    • Use feature flags to toggle encryption for gradual rollout.
  2. Database Schema:
    • No schema changes required, but document encrypted fields in DB diagrams.
    • Consider adding a is_encrypted metadata column for future flexibility.
  3. Code Changes:
    • Apply the Encryptable trait to models:
      use Magros\Encryptable\Encryptable;
      class User extends Model { use Encryptable; }
      
    • Explicitly define encrypted fields in the config:
      'fields' => [
          'ssn' => ['algorithm' => 'AES-256-CBC'],
          'credit_card' => ['exclude_from_search' => true],
      ],
      
  4. Testing Strategy:
    • Unit Tests: Mock getAttribute/setAttribute to verify encryption/decryption.
    • Integration Tests: Test API endpoints, queries, and edge cases (e.g., partial updates).
    • Load Testing: Simulate peak traffic to measure encryption overhead.

Compatibility

  • Third-Party Packages:
    • Laravel Scout: Encrypted fields cannot be indexed. Use exclude_from_search in config.
    • Laravel Nova: May require customization to display encrypted fields securely.
    • API Resources: Ensure encrypted fields are not exposed in responses (use visible/hidden).
  • Legacy Systems:
    • If integrating with legacy systems, ensure they can handle encrypted payloads (e.g., Base64-encoded responses).

Sequencing

  1. Pre-Migration:
    • Audit all models to identify sensitive fields.
    • Design a key management strategy (e.g., environment variables for dev, KMS for prod).
  2. Development:
    • Implement encryption for a subset of models.
    • Update CI/CD pipelines to include encryption tests.
  3. Deployment:
    • Roll out in stages (e.g., 10% of traffic first).
    • Monitor latency spikes and error rates post-deployment.
  4. Post-Migration:
    • Deprecate old, unencrypted data paths.
    • Document the encryption schema for onboarding.

Operational Impact

Maintenance

  • Configuration Drift:
    • Encrypted fields must be documented to avoid misconfigurations (e.g., encrypting non-sensitive data).
    • Tooling: Use static analysis (e.g., PHPStan) to detect models missing the trait or misconfigured fields.
  • Dependency Updates:
    • Monitor for breaking changes in Laravel/Eloquent core (e.g., attribute casting changes).
    • Forking risk: Low (package is lightweight), but consider forking if critical bugs arise.
  • Key Management:
    • Rotation: Plan for key rotation (e.g., re-encrypt data under new keys during maintenance windows).
    • Backup: Store encryption keys in a separate secure system (e.g., HashiCorp Vault) with access controls.

Support

  • Debugging:
    • Encrypted Data in Logs: Use Laravel’s Log::withoutFiles() or custom log filters to exclude encrypted fields.
    • Error Handling: Implement a fallback mechanism (e.g., log decryption failures without exposing data).
  • User Impact:
    • API Consumers: Document that encrypted fields return Base64-encoded strings. Provide decryption guidance if needed.
    • Admin Tools: Ensure Nova/Dashboard views handle encrypted fields gracefully (e.g., masked display).
  • SLA Considerations:
    • Data Recovery: Define SLAs for key loss scenarios (e.g., "Data recoverable within 24 hours if backup keys exist").

Scaling

  • Horizontal Scaling:
    • Stateless Encryption: Keys must be available to all instances (e.g., via shared storage like Redis or KMS).
    • Load Balancing: Ensure all app servers have access to the same encryption keys.
  • Database Scaling:
    • Read Replicas: Encrypted data can be read from replicas, but write performance may bottleneck if keys are centralized.
    • Sharding: Encryption adds complexity to sharding strategies (e.g., key distribution across shards).
  • Performance Tuning:
    • Caching: Cache decrypted values in memory (e.g., static properties) for frequently accessed fields.
    • Batch Operations: Avoid encrypting/decrypting in loops (e.g., use chunk() for large datasets).

Failure Modes

Failure Scenario Impact Mitigation
Key Loss Permanent data loss Backup keys offline; implement key escrow.
Corrupted Encrypted Data Inconsistent
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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle