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

Simple Cryptographic Bundle Laravel Package

assistenzde/simple-cryptographic-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require assistenzde/simple-cryptographic-bundle
    

    The bundle auto-registers in bundles.php (Symfony) or is manually instantiable in non-Symfony projects.

  2. First Use Case: Inject the service into a controller/service and encrypt/decrypt data:

    use Assistenzde\SimpleCryptographicBundle\Service\SimpleCryptographicService;
    
    class MyController {
        public function __construct(private SimpleCryptographicService $crypto) {}
    
        public function store(Request $request) {
            $encrypted = $this->crypto->encrypt($request->input('sensitive_data'));
            // Store $encrypted in DB or cache
        }
    }
    
  3. Verify Configuration: Check config/packages/simple-cryptographic-bundle.yaml for custom cipher settings (default: aes-256-ctr with APP_SECRET key).


Implementation Patterns

Dependency Injection Workflow

  • Primary Use: Inject SimpleCryptographicService into services/controllers handling sensitive data (e.g., tokens, PII).

    class UserService {
        public function __construct(private SimpleCryptographicService $crypto) {}
    
        public function hashPassword(string $plain): string {
            return $this->crypto->encrypt($plain);
        }
    }
    
  • Static Methods for Contextual Overrides: Use encryptWithMethod()/decryptWithMethod() for temporary cipher changes (e.g., legacy system compatibility):

    $legacyData = SimpleCryptographicService::decryptWithMethod(
        $encryptedLegacyData,
        'blowfish',
        'legacy_key'
    );
    

Integration Tips

  1. Database Storage: Encrypt sensitive fields before saving to DB (e.g., Laravel Eloquent observers):

    protected static function boot() {
        static::saving(function ($model) {
            if (isset($model->secret_field)) {
                $model->secret_field = app(SimpleCryptographicService::class)->encrypt($model->secret_field);
            }
        });
    }
    
  2. API Requests: Decrypt incoming encrypted payloads (e.g., API middleware):

    public function handle(Request $request, Closure $next) {
        $request->merge([
            'decrypted_data' => $this->crypto->decrypt($request->input('encrypted_data'))
        ]);
        return $next($request);
    }
    
  3. Configuration-Driven Ciphers: Dynamically switch ciphers based on environment (e.g., config/ciphers.php):

    $cipher = config('ciphers.'.env('APP_ENV'));
    $service = new SimpleCryptographicService(config('app.key'), $cipher);
    

Gotchas and Tips

Pitfalls

  1. Key Management:

    • Never hardcode keys in source. Use environment variables (APP_SECRET) or a secure vault.
    • Key Rotation: Re-encrypt data with new keys during migrations (use openssl_reencrypt or manual re-processing).
  2. Cipher Compatibility:

    • Avoid aes-256-cbc: Requires manual IV handling (this bundle auto-generates IVs for CTR/OFB modes).
    • Test Legacy Data: Some ciphers (e.g., blowfish) may fail with modern OpenSSL versions. Validate decryption of existing data post-upgrade.
  3. Error Handling:

    • Silent Failures: decrypt() returns false on failure. Always validate:
      $decrypted = $this->crypto->decrypt($data);
      if ($decrypted === false) {
          throw new \RuntimeException('Decryption failed');
      }
      

Debugging

  • Verify OpenSSL Support:

    php -m | grep openssl
    

    Ensure openssl extension is enabled.

  • Check Cipher Availability:

    var_dump(openssl_get_cipher_methods()); // List supported ciphers
    

Extension Points

  1. Custom Initialization Vectors (IV): Override SimpleCryptographicService to inject fixed IVs (not recommended for security):

    class CustomCryptoService extends SimpleCryptographicService {
        public function __construct(string $key, string $cipher, private string $iv = 'fixed_iv_16') {
            parent::__construct($key, $cipher);
        }
    }
    
  2. Logging Encryption Events: Decorate the service to log operations (e.g., for audit trails):

    class LoggingCryptoService implements \Assistenzde\SimpleCryptographicBundle\Service\CryptographicServiceInterface {
        public function __construct(private SimpleCryptographicService $decorated) {}
    
        public function encrypt(string $data): string {
            $logger->info('Encrypting data', ['length' => strlen($data)]);
            return $this->decorated->encrypt($data);
        }
        // Implement decrypt() similarly
    }
    
  3. Performance:

    • Batch Processing: For large datasets, encrypt/decrypt in chunks to avoid memory issues.
    • Caching: Cache decrypted results if data is read frequently (e.g., user sessions).

Configuration Quirks

  • YAML Path: Ensure config/packages/simple-cryptographic-bundle.yaml exists (create if missing).
  • Symfony Kernel Secret: The default key (%kernel.secret%) is not the same as APP_SECRET. Use:
    key: '%env(APP_CRYPTO_KEY)%' # Custom env var
    
  • Case Sensitivity: Cipher names in config are case-sensitive (aes-256-ctrAES-256-CTR).
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.
ilhamsyabani/laravel-volt-starter
thethunderturner/filament-latex
ghostcompiler/laravel-querybuilder
webrek/laravel-telescope-mongodb
anousss007/blatui
zatona-eg/zatona-eg-api
cocosmos/filament-sticky-save-bar
patrickbussmann/oauth2-apple
3brs/enterprise-security-bundle
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat