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

Mcrypt Compat Laravel Package

phpseclib/mcrypt_compat

PHP 5.x–8.x polyfill for the deprecated mcrypt extension. Provides common ciphers (Rijndael/AES variants, DES, Blowfish, RC2, 3DES, ARCFOUR) and modes (CBC, CFB, CTR, ECB, OFB, stream). Can emulate older PHP mcrypt behavior.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Installation:

    composer require phpseclib/mcrypt_compat
    

    Add this to your composer.json under require to ensure it’s included in your project.

  2. Basic Usage: Replace any mcrypt_* function calls with the polyfill’s namespace:

    use phpseclib\mcrypt_compat as mcrypt;
    
    $key = 'my-secret-key';
    $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND);
    $data = 'Sensitive data';
    
    $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv);
    $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $encrypted, MCRYPT_MODE_CBC, $iv);
    
  3. First Use Case:

    • Legacy Migration: Replace mcrypt calls in a Laravel controller or service handling encrypted data (e.g., API responses, database fields).
    • Example:
      // Before (fails in PHP 8.x without mcrypt extension)
      $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $data, MCRYPT_MODE_CBC, $iv);
      
      // After (works with polyfill)
      $encrypted = \phpseclib\mcrypt_compat\mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $data, MCRYPT_MODE_CBC, $iv);
      
  4. Verify Compatibility:

    • Test with a known plaintext/ciphertext pair to ensure decryption matches the original output.
    • Check for warnings in PHP logs (e.g., deprecation notices in PHP 8.2+).

Implementation Patterns

Usage Patterns

  1. Facade Pattern for Laravel: Create a facade to abstract the polyfill and maintain consistency:

    // app/Facades/McryptFacade.php
    namespace App\Facades;
    use Illuminate\Support\Facades\Facade;
    class McryptFacade extends Facade {
        protected static function getFacadeAccessor() {
            return 'mcrypt';
        }
    }
    

    Register the polyfill in a service provider:

    // app/Providers/AppServiceProvider.php
    public function register() {
        $this->app->bind('mcrypt', function() {
            return new class {
                public function encrypt($algorithm, $key, $data, $mode, $iv) {
                    return \phpseclib\mcrypt_compat\mcrypt_encrypt($algorithm, $key, $data, $mode, $iv);
                }
                // Add other mcrypt functions as needed...
            };
        });
    }
    

    Usage:

    use App\Facades\McryptFacade;
    $encrypted = McryptFacade::encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv);
    
  2. Configuration Management:

    • Store encryption keys, IVs, and algorithms in Laravel’s config:
      // config/mcrypt.php
      return [
          'default_algorithm' => MCRYPT_RIJNDAEL_256,
          'default_mode' => MCRYPT_MODE_CBC,
          'key' => env('MCRYPT_KEY'),
      ];
      
    • Use the config in services:
      $algorithm = config('mcrypt.default_algorithm');
      $mode = config('mcrypt.default_mode');
      $key = config('mcrypt.key');
      
  3. Encryption Service Class: Encapsulate logic in a service for reusability:

    // app/Services/EncryptionService.php
    namespace App\Services;
    use phpseclib\mcrypt_compat as mcrypt;
    class EncryptionService {
        public function encrypt($data, $key = null) {
            $key = $key ?: config('mcrypt.key');
            $iv = mcrypt_create_iv(mcrypt_get_iv_size(config('mcrypt.default_algorithm'), config('mcrypt.default_mode')), MCRYPT_RAND);
            return mcrypt_encrypt(
                config('mcrypt.default_algorithm'),
                $key,
                $data,
                config('mcrypt.default_mode'),
                $iv
            );
        }
        public function decrypt($encrypted, $key = null) {
            $key = $key ?: config('mcrypt.key');
            return mcrypt_decrypt(
                config('mcrypt.default_algorithm'),
                $key,
                $encrypted,
                config('mcrypt.default_mode'),
                $iv // Must match the IV used during encryption
            );
        }
    }
    

    Usage:

    $service = new \App\Services\EncryptionService();
    $encrypted = $service->encrypt('Sensitive data');
    $decrypted = $service->decrypt($encrypted);
    
  4. Database Encryption: Use the polyfill to encrypt/decrypt database fields (e.g., with Laravel’s Attribute casting or accessors):

    // app/Models/User.php
    protected $casts = [
        'encrypted_data' => 'encrypted',
    ];
    public function getEncryptedDataAttribute($value) {
        return \phpseclib\mcrypt_compat\mcrypt_decrypt(
            MCRYPT_RIJNDAEL_128,
            config('mcrypt.key'),
            $value,
            MCRYPT_MODE_CBC,
            $this->iv // Store IV alongside encrypted data
        );
    }
    public function setEncryptedDataAttribute($value) {
        $this->iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND);
        $this->attributes['encrypted_data'] = mcrypt_encrypt(
            MCRYPT_RIJNDAEL_128,
            config('mcrypt.key'),
            $value,
            MCRYPT_MODE_CBC,
            $this->iv
        );
    }
    

Workflows

  1. Legacy System Migration:

    • Step 1: Identify all mcrypt calls in the codebase using git grep or IDE search.
    • Step 2: Replace each call with the polyfill (e.g., \phpseclib\mcrypt_compat\mcrypt_encrypt).
    • Step 3: Test each module individually, starting with non-critical paths.
    • Step 4: Update tests to account for behavioral differences (e.g., ncfb mode).
  2. Third-Party Library Integration:

    • If a library expects the mcrypt extension, wrap its calls in a compatibility layer:
      // app/Services/ThirdPartyLibraryService.php
      public function processWithLegacyLib($data) {
          $encrypted = \phpseclib\mcrypt_compat\mcrypt_encrypt(
              MCRYPT_BLOWFISH,
              $this->key,
              $data,
              MCRYPT_MODE_CFB,
              $this->iv
          );
          return $legacyLibrary->process($encrypted); // Library expects mcrypt output
      }
      
  3. Performance Optimization:

    • Cache IVs or encrypted data where possible to reduce repeated calls to mcrypt_create_iv or encryption functions.
    • Example:
      $cache = [];
      $cacheKey = md5($data);
      if (!isset($cache[$cacheKey])) {
          $cache[$cacheKey] = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv);
      }
      return $cache[$cacheKey];
      
  4. PHP Version Emulation:

    • For legacy systems requiring PHP 5.3 behavior, define the target version before autoloading:
      // bootstrap/app.php or similar entry point
      define('PHPSECLIB_MCRYPT_TARGET_VERSION', '5.3.0');
      require __DIR__.'/vendor/autoload.php';
      

Integration Tips

  1. Avoid Mixing with Native mcrypt:

    • Ensure the polyfill is the only source of mcrypt functions. Remove extension=mcrypt from php.ini to prevent conflicts.
  2. Handle IV Management:

    • Store IVs securely alongside encrypted data (e.g., in a database or encrypted config). Never reuse IVs for the same key.
  3. Error Handling:

    • Wrap polyfill calls in try-catch blocks to handle edge cases (e.g., invalid keys, unsupported modes):
      try {
          $decrypted = mcrypt_decrypt($algorithm, $key, $encrypted, $mode, $iv);
      } catch
      
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