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

Encryption Laravel Package

al-saloul/encryption

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require al-saloul/encryption
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="AlSaloul\Encryption\EncryptionServiceProvider"
    
  2. Basic Usage: Encrypt a number:

    use AlSaloul\Encryption\Facades\Encryption;
    
    $encrypted = Encryption::encrypt(12345);
    // Output: e.g., "x9#kL2$pQ7"
    

    Decrypt a string:

    $decrypted = Encryption::decrypt($encrypted);
    // Output: 12345
    
  3. First Use Case: Securely store sensitive numeric data (e.g., credit card last 4 digits, user IDs) in logs, URLs, or databases without exposing raw values.


Implementation Patterns

Core Workflows

  1. Data Storage:

    • Encrypt before saving to a database or cache:
      $user->secure_id = Encryption::encrypt($user->id);
      $user->save();
      
    • Decrypt when retrieving:
      $id = Encryption::decrypt($user->secure_id);
      
  2. API Responses:

    • Mask numeric data in API responses:
      return response()->json([
          'user_id' => Encryption::encrypt($user->id),
          'last_four' => Encryption::encrypt($payment->last_four),
      ]);
      
  3. URL Parameters:

    • Safely pass numeric IDs in URLs:
      $encryptedId = Encryption::encrypt($order->id);
      route('order.show', ['id' => $encryptedId]);
      
    • Decrypt in the controller:
      $order = Order::find(Encryption::decrypt(request('id')));
      
  4. Validation:

    • Validate encrypted strings before decryption:
      if (Encryption::isEncrypted($input)) {
          $decrypted = Encryption::decrypt($input);
          // Proceed with $decrypted
      }
      

Integration Tips

  • Middleware: Create middleware to auto-decrypt encrypted IDs in routes:

    public function handle($request, Closure $next) {
        $request->merge([
            'id' => Encryption::decrypt($request->id)
        ]);
        return $next($request);
    }
    
  • Eloquent Accessors/Mutators:

    public function getSecureIdAttribute($value) {
        return Encryption::encrypt($this->attributes['id']);
    }
    
    public function setSecureIdAttribute($value) {
        $this->attributes['id'] = Encryption::decrypt($value);
    }
    
  • Logging: Use the logging feature to track encryption/decryption:

    Encryption::enableLogging();
    Encryption::encrypt(123); // Logs the operation
    

Gotchas and Tips

Pitfalls

  1. Input Validation:

    • Always validate input before decryption to avoid exceptions:
      if (!Encryption::isEncrypted($string)) {
          throw new \InvalidArgumentException("Invalid encrypted string");
      }
      
  2. Config Overrides:

    • Custom mappings/padding in config/encryption.php may break decryption if not symmetric:
      'mappings' => [
          '0' => 'a', '1' => 'b', // Custom mappings
      ],
      'padding' => [
          'prefix_length' => 3,
          'suffix_length' => 3,
      ],
      
  3. Edge Cases:

    • Large numbers may exceed string limits; test with max values (e.g., PHP_INT_MAX).
    • Floating-point numbers are not supported (use integers only).
  4. Security:

    • Encrypted strings are not secure for sensitive data (e.g., passwords). Use Laravel’s built-in encryption (encrypt()) for such cases.
    • Avoid storing encryption keys in version control (though this package uses PHP’s random_int() internally).

Debugging

  • Failed Decryption:

    • Check if the encrypted string matches the config’s mappings and padding.
    • Verify the string was generated by the same package version/config.
  • Logging: Enable logging to trace operations:

    Encryption::enableLogging();
    // Check Laravel logs for entries like:
    // "[Encryption] Encrypted '123' to 'x9#kL2$pQ7'"
    

Extension Points

  1. Custom Mappings: Override mappings in the config or dynamically:

    Encryption::setMappings(['0' => 'X', '1' => 'Y']);
    
  2. Custom Padding: Extend the Encryption facade to add dynamic padding:

    Encryption::setPadding(5, 5); // 5-char prefix/suffix
    
  3. Event Listeners: Listen for encryption/decryption events (if the package supports them):

    Encryption::onEncrypted(function ($original, $encrypted) {
        // Custom logic
    });
    
  4. Testing: Mock the facade for unit tests:

    $this->partialMock(Encryption::class, function ($mock) {
        $mock->shouldReceive('decrypt')->andReturn(123);
    });
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope