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 Encrypt Model Laravel Package

jetiradoro/laravel-encrypt-model

Laravel trait to transparently encrypt specified Eloquent model attributes before saving to the database and automatically decrypt them when accessed. Install via Composer, add the Encryptable trait, and list encrypted fields in the $encryptable array.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Pros:
    • Aligns with Laravel’s Eloquent model architecture, leveraging traits for modularity.
    • Encryption logic is scoped to specific fields (via $encryptable), reducing scope creep.
    • Transparent decryption on retrieval avoids application-layer encryption/decryption boilerplate.
  • Cons:
    • Tight coupling to Laravel: Not framework-agnostic; may complicate adoption in non-Laravel PHP stacks.
    • Limited encryption strategy: Uses a single, undocumented encryption method (likely Laravel’s default encrypt()). No support for custom algorithms (e.g., AES-256-GCM, PGP) or key management.
    • No field-level granularity: All encrypted fields share the same encryption key (Laravel’s default APP_KEY). Risk of key rotation or compliance issues (e.g., GDPR, HIPAA).
    • No query-level encryption: Encrypted fields cannot be queried directly (e.g., where('cc', 'LIKE', '%123%')), limiting use cases for sensitive searchable data.

Integration Feasibility

  • Low effort for basic use cases: Drop-in trait usage with minimal configuration.
  • High effort for advanced needs:
    • Custom encryption backends (e.g., AWS KMS, HashiCorp Vault) would require forking or extending the package.
    • Indexing encrypted fields (e.g., for partial searches) would need additional logic (e.g., searchable encrypted indexes like OpenFHE).
  • Database compatibility: Assumes Laravel’s default encryption (likely OpenSSL-based), which may not work with all database drivers or edge cases (e.g., large binary blobs).

Technical Risk

  • Security risks:
    • Key management: Relies on Laravel’s APP_KEY; no support for per-field keys or hardware-backed keys (HSMs).
    • Side-channel attacks: Encrypted data stored as encrypted:... in JSON fields (visible in logs, dumps, or debug tools) unless explicitly masked.
    • No integrity checks: No HMAC or digital signatures to detect tampering.
  • Performance:
    • Encryption/decryption overhead on every save()/find() call. Benchmarking required for high-write workloads.
    • Potential database bloat if encrypted fields are large (e.g., base64-encoded blobs).
  • Data loss:
    • No fallback for corrupted encrypted data (e.g., if APP_KEY changes post-encryption).
    • No versioning or audit trail for encrypted field modifications.

Key Questions

  1. Compliance Requirements:
    • Does the application need field-level encryption keys (e.g., for GDPR’s "right to erasure")?
    • Are there regulatory constraints on encryption algorithms (e.g., FIPS 140-2)?
  2. Query Patterns:
    • Will encrypted fields need to be searchable (e.g., partial matches, ranges)? If so, is a dedicated search solution (e.g., Elasticsearch with encrypted fields) viable?
  3. Key Management:
    • How is APP_KEY secured and rotated? Is it stored in a secrets manager (e.g., AWS Secrets Manager)?
    • What’s the recovery plan if APP_KEY is lost?
  4. Performance:
    • What’s the expected throughput for encrypted operations? Has the package been stress-tested?
  5. Alternatives:
    • Would a database-level solution (e.g., PostgreSQL’s pgcrypto, Transparent Data Encryption) or a dedicated library (e.g., Defuse/PHP-Encryption) be more suitable?
  6. Testing:
    • Are there unit tests for edge cases (e.g., malformed encrypted data, key rotation)?
    • How would you test decryption after APP_KEY rotation?

Integration Approach

Stack Fit

  • Best for:
    • Laravel applications where sensitive PII (e.g., credit cards, SSNs) is stored but rarely queried.
    • Teams already using Laravel’s built-in encryption and comfortable with its limitations.
  • Poor fit for:
    • Multi-framework PHP stacks (e.g., Symfony, Lumen).
    • Applications requiring fine-grained encryption (e.g., per-user keys, hardware-backed keys).
    • Systems needing encrypted search or analytics on sensitive fields.

Migration Path

  1. Pilot Phase:
    • Start with non-critical models (e.g., User profile fields) to validate performance and security.
    • Monitor encryption/decryption latency and database size impact.
  2. Incremental Adoption:
    • Add $encryptable to models in phases, prioritizing high-sensitivity fields.
    • Use feature flags to toggle encryption for specific fields during testing.
  3. Database Schema:
    • No schema changes required, but document encrypted fields in a schema_migrations table or comments.
    • Consider adding a is_encrypted column if dynamic field encryption is needed later.

Compatibility

  • Laravel Version: Tested with Laravel 8+ (assumed based on trait usage). Verify compatibility with your Laravel version.
  • Database Drivers: Works with any Laravel-supported database, but performance may vary (e.g., MySQL vs. PostgreSQL).
  • Caching: Encrypted data won’t be cacheable via Laravel’s cache drivers (e.g., Redis) unless explicitly handled.
  • Replication: Encrypted data will replicate normally, but key management must be synchronized across replicas.

Sequencing

  1. Pre-requisites:
    • Ensure Laravel’s APP_KEY is securely stored (e.g., environment variables, secrets manager).
    • Back up the database before enabling encryption on production data.
  2. Implementation Steps:
    • Install the package via Composer.
    • Add Encryptable trait and $encryptable to target models.
    • Test with trait and factory tests for encryption/decryption.
    • Gradually enable in staging, monitoring logs for decryption errors.
  3. Post-Deployment:
    • Update documentation to reflect encrypted fields (e.g., "CC numbers are stored encrypted").
    • Train support teams on handling decryption failures (e.g., lost keys).

Operational Impact

Maintenance

  • Pros:
    • Minimal maintenance: No need to manually encrypt/decrypt fields.
    • Centralized logic reduces duplication across models.
  • Cons:
    • Vendor lock-in: Tied to Laravel’s encryption methods; upgrading the package may require data migration if encryption changes.
    • Debugging complexity: Encrypted data appears as gibberish in logs, dumps, and IDEs (e.g., Laravel Debugbar).
    • Key rotation: Changing APP_KEY will break decryption for existing data unless a migration strategy is implemented.

Support

  • Common Issues:
    • Decryption failures due to APP_KEY changes or corruption.
    • Performance bottlenecks in high-traffic endpoints.
    • Misconfigured $encryptable arrays (e.g., forgetting to include a field).
  • Tooling Gaps:
    • No built-in CLI for bulk encryption/decryption or key rotation.
    • No observability into encryption failures (e.g., metrics for decryption errors).
  • Recommendations:
    • Implement a support runbook for decryption failures (e.g., "If APP_KEY changes, re-encrypt data via a migration").
    • Add logging for encryption/decryption events (e.g., monolog channel).

Scaling

  • Performance:
    • Encryption/decryption adds ~1–10ms per operation (benchmark locally). For 10K RPS, this could add 10–100ms latency.
    • Consider offloading encryption to a queue (e.g., Laravel Queues) for non-critical fields.
  • Database:
    • Encrypted fields increase storage size (base64 inflation: ~33% overhead).
    • No impact on read replicas, but all replicas must share the same APP_KEY.
  • Horizontal Scaling:
    • Stateless encryption means no additional load balancer configuration, but ensure all app servers have access to APP_KEY.

Failure Modes

Failure Scenario Impact Mitigation
APP_KEY lost/corrupted Permanent data loss for encrypted fields Regular backups + key rotation documentation.
Database corruption in encrypted fields Decryption failures Use database backups + checksums.
Key rotation without re-encryption Data becomes unreadable Automate re-encryption via migrations.
High write load Increased latency Queue encryption tasks.
Dependency vulnerability Security breach Monitor for CVE updates (low stars = low visibility).

Ramp-Up

  • Developer Onboarding:
    • Document the $encryptable convention and encryption behavior (e.g., "fields are encrypted at rest and decrypted on access").
    • Provide examples for common use cases (e.g., encrypting API payloads).
  • Security Training:
    • Educate teams on risks of exposing APP_KEY (e.g., in Git, logs).
    • Clarify that encrypted fields cannot be queried directly.
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.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver