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

Ciphersweet Laravel Package

paragonie/ciphersweet

CipherSweet is a PHP library for field-level encryption with searchable encrypted data. It helps you securely encrypt database columns while still supporting safe, blind-index-based search and sorting, with modern cryptography and key management support.

Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Use Case Alignment: Ideal for Laravel applications requiring field-level encryption (e.g., PII, sensitive data in databases) while enabling search/filtering on encrypted fields. Fits well with Laravel’s Eloquent ORM and query builder.
  • Performance: Leverages ChaCha20-Poly1305 (AES alternative) for speed, reducing CPU overhead compared to traditional AES-GCM. Critical for high-throughput systems.
  • Security Model: Supports deterministic encryption (for searchability) and probabilistic encryption (for uniqueness). Aligns with modern cryptographic best practices (e.g., avoiding ECB mode).
  • Laravel Synergy: Designed for PHP 8.1+, integrates with Laravel’s service container, and can work alongside existing encryption (e.g., config('app.cipher')).

Integration Feasibility

  • Database Agnostic: Works with MySQL, PostgreSQL, SQLite (via paragonie/ciphersweet-db), but requires schema changes (e.g., adding ciphertext, salt, nonce columns).
  • ORM Compatibility: Eloquent integration is partial—requires custom accessors/mutators or a wrapper library (e.g., spatie/laravel-ciphersweet). May need middleware for request/response encryption.
  • Key Management: Relies on environment variables or a key management system (KMS). Laravel’s .env integration is straightforward but lacks built-in rotation.
  • Query Builder Limits: Search/filtering on encrypted fields requires application-layer decryption or database-specific functions (e.g., PostgreSQL’s pgcrypto). Complex joins/aggregations may need workarounds.

Technical Risk

  • Cryptographic Drift: Deterministic encryption risks pattern leakage if keys are compromised. Mitigate with key rotation and probabilistic modes where possible.
  • Database Locks: Heavy encryption/decryption may cause performance bottlenecks in high-concurrency environments. Test with production-like loads.
  • Legacy System Friction: If using older Laravel versions (<8.0) or PHP <8.1, backward compatibility may require polyfills or forks.
  • Searchability Trade-offs: Encrypted fields cannot use native SQL indexes for full-text search. Requires application-side filtering or specialized extensions (e.g., PostgreSQL’s tsvector on decrypted data).

Key Questions

  1. Compliance Requirements:
    • Does the project need audit logs for encryption/decryption events? Ciphersweet lacks built-in logging.
    • Are there regulatory constraints (e.g., GDPR, HIPAA) requiring specific key management or access controls?
  2. Performance Baseline:
    • What is the acceptable latency for encrypted field operations? Benchmark against unencrypted baselines.
  3. Key Management:
    • How will encryption keys be rotated and revoked? Will use a hardware security module (HSM) or cloud KMS (e.g., AWS KMS)?
  4. Database Schema:
    • Can the existing schema accommodate additional columns (ciphertext, salt, nonce) without migrations?
  5. Search Complexity:
    • Are there complex queries (e.g., LIKE, JOIN) on encrypted fields? If so, what’s the fallback strategy?
  6. Fallback Mechanism:
    • How will the system handle decryption failures (e.g., corrupted ciphertext, key loss)? Graceful degradation vs. hard errors.

Integration Approach

Stack Fit

  • PHP/Laravel: Native support for PHP 8.1+; integrates with Laravel’s service container, events, and middleware.
  • Database:
    • PostgreSQL: Best support via paragonie/ciphersweet-db (uses pgcrypto for some operations).
    • MySQL: Limited to application-layer decryption; avoid LIKE or full-text search on encrypted fields.
    • SQLite: Possible but unsupported; requires custom implementations.
  • Caching: Encrypted data cannot be cached in Redis/Memcached (decryption happens at runtime). Consider edge caching only for non-sensitive metadata.
  • APIs: Works with GraphQL (via Laravel GraphQL) and REST, but requires careful handling of encrypted payloads in responses.

Migration Path

  1. Assessment Phase:
    • Audit sensitive fields (e.g., passwords, credit_cards, SSNs) for encryption candidates.
    • Profile current query patterns to identify searchability vs. encryption-only needs.
  2. Schema Migration:
    • Add ciphertext, salt, nonce columns to target tables (use Laravel migrations).
    • Example:
      Schema::table('users', function (Blueprint $table) {
          $table->binary('email_ciphertext')->nullable();
          $table->binary('email_salt')->nullable();
          $table->binary('email_nonce')->nullable();
      });
      
  3. Encryption Layer:
    • Integrate CipherSweet via a service provider:
      $this->app->singleton(CipherSweet::class, function ($app) {
          return new CipherSweet(config('ciphersweet.keys'));
      });
      
    • Create Eloquent accessors/mutators or a wrapper trait:
      trait EncryptedEmail {
          public function getEmailAttribute($value) {
              return $this->decrypt($this->attributes['email_ciphertext']);
          }
          public function setEmailAttribute($value) {
              $this->attributes['email_ciphertext'] = $this->encrypt($value);
          }
      }
      
  4. Query Builder Adaptation:
    • Replace direct field access with encrypted equivalents:
      // Before
      $users = User::where('email', 'like', '%@gmail.com%')->get();
      
      // After (application-layer filter)
      $users = User::all()->filter(fn ($user) => str_contains($user->email, '@gmail.com'));
      
    • For PostgreSQL, use custom SQL with pgcrypto where possible.
  5. API/Response Handling:
    • Use middleware to decrypt sensitive fields before returning to clients:
      public function handle($request, Closure $next) {
          $response = $next($request);
          $response->getData()->transform(function ($data) {
              return collect($data)->mapWithKeys(function ($value, $key) {
                  return $this->decryptIfNeeded($key, $value);
              });
          });
          return $response;
      }
      

Compatibility

  • Laravel Packages:
    • Spatie Laravel Ciphersweet: Provides Eloquent integration but may lag behind upstream. Evaluate for stability.
    • Laravel Scout: Encrypted fields cannot be indexed for search. Use application-side filtering or a hybrid approach (e.g., encrypt in DB but index a hash).
  • Third-Party Services:
    • Stripe/PayPal: Encrypt sensitive data before sending to APIs (avoid exposing ciphertext).
    • Auth Systems: Integrate with Laravel Sanctum/Passport by encrypting tokens or claims.

Sequencing

  1. Phase 1: Non-Production Validation
    • Implement on a subset of fields (e.g., email, phone) in a staging environment.
    • Test read/write performance, query patterns, and edge cases (e.g., corrupted data).
  2. Phase 2: Core Encryption
    • Roll out to high-priority tables (e.g., users, orders).
    • Update API contracts to reflect encrypted responses.
  3. Phase 3: Search Optimization
    • Implement application-layer filtering for complex queries.
    • Explore database-specific optimizations (e.g., PostgreSQL tsvector on decrypted data).
  4. Phase 4: Key Management
    • Integrate with a KMS (e.g., AWS KMS, HashiCorp Vault) for key rotation.
    • Add monitoring for decryption failures.
  5. Phase 5: Full Rollout
    • Migrate remaining sensitive fields.
    • Deprecate old, unencrypted fields in favor of encrypted ones.

Operational Impact

Maintenance

  • Key Rotation:
    • Requires database migrations to re-encrypt data with new keys. Use CipherSweet::reencrypt().
    • Schedule rotations during low-traffic periods to avoid performance spikes.
  • Dependency Updates:
    • Monitor paragonie/ciphersweet for security patches (e.g., new ChaCha20 variants).
    • PHP 8.2+ may require adjustments for new type system features.
  • Backup Strategy:
    • Ensure database backups include encrypted fields (no special handling needed).
    • Document key backup procedures (e.g., offline HSM backups).

Support

  • Debugging:
    • Decryption failures
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
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
twbs/bootstrap4
php-http/client-implementation
phpcr/phpcr-implementation
cucumber/gherkin-monorepo
haydenpierce/class-finder
psr/simple-cache-implementation
uri-template/tests