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

Openssl Encryption Laravel Package

ranabd36/openssl-encryption

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require ranabd36/openssl-encryption:1.0.0
    

    The package auto-registers, but verify config/app.php includes:

    'providers' => [
        OpenSSLEncryption\Providers\OpenSSLEncryptionServiceProvider::class,
    ],
    'aliases' => [
        'OpenSSL' => OpenSSLEncryption\OpenSSL::class,
    ]
    
  2. Generate Keys: Run the Artisan command to create a public.pem and private.pem in storage/app/openssl/:

    php artisan openssl:key-generate
    
  3. First Use Case: Encrypt a message with a recipient’s public key:

    $encrypted = OpenSSL::encrypt('Sensitive data', 'path/to/recipient_public.pem');
    

    Decrypt with your private key:

    $decrypted = OpenSSL::decrypt($encrypted, 'path/to/your_private.pem');
    

Implementation Patterns

Core Workflows

  1. Key Management:

    • Store keys in storage/app/openssl/ (or configure via config/openssl.php).
    • Use openssl:key-generate for new keys; avoid hardcoding keys in code.
    • For multi-user systems, generate keys per user and store paths in a database.
  2. Encryption/Decryption:

    • Encrypt for external parties:
      $encrypted = OpenSSL::encrypt($data, 'public_key_path');
      // Send $encrypted via API/email.
      
    • Decrypt incoming messages:
      $decrypted = OpenSSL::decrypt($encryptedData, 'private_key_path');
      
    • Sign data (authentication):
      $signature = OpenSSL::sign($data, 'private_key_path');
      $isValid = OpenSSL::verify($data, $signature, 'public_key_path');
      
  3. Integration with Laravel:

    • Requests/Responses: Encrypt sensitive payloads before sending to clients:
      return response()->json(['data' => OpenSSL::encrypt($data, $clientPublicKey)]);
      
    • Jobs/Queues: Encrypt serialized jobs for secure storage/transit:
      $job->handle(OpenSSL::encrypt($jobData, $recipientKey));
      
  4. Configuration:

    • Publish the config to customize:
      php artisan vendor:publish --provider="OpenSSLEncryption\Providers\OpenSSLEncryptionServiceProvider"
      
      Adjust key_directory, key_prefix, or openssl_config as needed.

Gotchas and Tips

Pitfalls

  1. Key Paths:

    • Hardcoding paths (e.g., '/absolute/path') breaks portability. Use relative paths from storage/ or config.
    • Fix: Store key paths in a database or config:
      config(['openssl.keys' => [
          'user1' => 'storage/app/openssl/user1_public.pem',
      ]]);
      
  2. Key Permissions:

    • Private keys must have strict permissions (chmod 600). OpenSSL fails silently if permissions are too loose.
    • Debug: Check storage/logs/laravel.log for OpenSSL errors like error:0906A068:PEM routines:PEM_do_header:bad password read.
  3. Data Size Limits:

    • OpenSSL has a 4GB plaintext limit. For larger data, chunk and encrypt separately or use hybrid encryption (e.g., AES for bulk data + OpenSSL for keys).
  4. Key Rotation:

    • No built-in rotation logic. Manually replace keys and re-encrypt old data.
    • Tip: Log key changes and notify dependents (e.g., via database events).
  5. Error Handling:

    • OpenSSL throws exceptions for invalid keys/data. Wrap calls in try-catch:
      try {
          $decrypted = OpenSSL::decrypt($data, $keyPath);
      } catch (\OpenSSLEncryption\Exceptions\OpenSSLErrorException $e) {
          Log::error("Decryption failed: " . $e->getMessage());
          // Handle gracefully (e.g., retry with fallback key).
      }
      

Tips

  1. Testing:

    • Use openssl:key-generate in tests to avoid polluting storage/:
      $this->artisan('openssl:key-generate')->expectsQuestion('Key name', 'test_key')->run();
      
  2. Performance:

    • Encryption/decryption is CPU-intensive. Cache public keys in memory (e.g., via Laravel’s cache) if reused frequently:
      $key = Cache::remember("public_key_{$userId}", now()->addHours(1), fn() => file_get_contents($keyPath));
      
  3. Security:

    • Never commit private keys to version control (add to .gitignore).
    • Use environment variables for sensitive paths:
      OPENSSL_PRIVATE_KEY_PATH=storage/app/openssl/private.pem
      
      $path = env('OPENSSL_PRIVATE_KEY_PATH');
      
  4. Extending:

    • Override the OpenSSL facade to add logging or metrics:
      class CustomOpenSSL extends \OpenSSLEncryption\OpenSSL {
          public function encrypt($data, $publicKey) {
              Log::debug("Encrypting data for key: " . basename($publicKey));
              return parent::encrypt($data, $publicKey);
          }
      }
      
      Bind it in AppServiceProvider:
      $this->app->bind(\OpenSSLEncryption\OpenSSL::class, CustomOpenSSL::class);
      
  5. Debugging:

    • Enable OpenSSL debug output in config/openssl.php:
      'openssl_config' => [
          'config' => '/path/to/openssl.cnf',
          'debug' => true, // Adds verbose output to logs
      ]
      
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
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