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 Bundle Laravel Package

cleverage/encryption-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require cleverage/encryption-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        Clevage\EncryptionBundle\ClevageEncryptionBundle::class => ['all' => true],
    ];
    
  2. Configure the Bundle Add encryption settings to config/packages/cleverage_encryption.yaml:

    cleverage_encryption:
        cipher: AES-256-CBC
        cipher_key: '%env(ENCRYPTION_KEY)%'  # Generate a secure key (e.g., 32-byte hex string)
        cipher_iv: '%env(ENCRYPTION_IV)%'    # Generate a secure IV (e.g., 16-byte hex string)
    
  3. First Use Case: Encrypting a Field Annotate a Doctrine entity field with encrypt_string or encrypt_text:

    use Doctrine\ORM\Mapping as ORM;
    
    class User {
        /**
         * @ORM\Column(type="encrypt_string")
         */
        private string $creditCardNumber;
    
        /**
         * @ORM\Column(type="encrypt_text")
         */
        private string $personalNotes;
    }
    

    Run migrations (php bin/console doctrine:migrations:diff and php bin/console doctrine:migrations:migrate).


Implementation Patterns

Workflows

  1. Encrypting Data The bundle handles encryption/decryption transparently. Just set/get properties as usual:

    $user = new User();
    $user->setCreditCardNumber('4111111111111111'); // Automatically encrypted on flush
    $entityManager->persist($user);
    $entityManager->flush();
    
  2. Querying Encrypted Fields Use ExpressionBuilder for comparisons:

    $qb = $entityManager->createQueryBuilder();
    $expr = $qb->expr();
    $qb->andWhere($expr->eq('u.creditCardNumber', ':card'))
       ->setParameter('card', '4111111111111111');
    
  3. File Encryption For encrypted file storage (e.g., encrypt_binary), use the File type with a custom FileLoader:

    /**
     * @ORM\Column(type="encrypt_binary")
     */
    private $sensitiveFile;
    
  4. Multi-Tenancy (Organization-Level Encryption) Extend the bundle to support organization-specific keys by overriding the CipherKeyProvider:

    cleverage_encryption:
        cipher_key_provider: app.custom_cipher_key_provider
    

Integration Tips

  • Symfony Forms: Encrypted fields work seamlessly with Symfony Forms. No extra configuration is needed.
  • API Platform: Use @ApiProperty with serializedName to expose decrypted data in responses.
  • Doctrine Lifecycle Events: Listen to prePersist/preUpdate to log encryption events or validate data before encryption.

Gotchas and Tips

Pitfalls

  1. Session Dependency The cipher key is decrypted and stored in the session at login. If sessions are disabled or invalidated, decryption fails.

    • Fix: Use a session handler that persists across restarts (e.g., Redis).
  2. Key Rotation Changing the encryption key breaks existing encrypted data. Plan for key rotation during migrations.

    • Workaround: Use a versioned key system or maintain backward compatibility.
  3. Performance Overhead Encryption/decryption adds ~10-20ms per field. Avoid encrypting frequently queried fields.

    • Tip: Use encrypt_string for small fields (e.g., credit cards) and encrypt_text for large data.
  4. Doctrine DQL Limitations Encrypted fields cannot be used in ORDER BY, GROUP BY, or complex aggregations.

    • Tip: Decrypt in PHP after fetching or use a database view.

Debugging

  • Check Session: Verify the cipher key is set in the session:
    $this->get('session')->get('cleverage_encryption.cipher_key');
    
  • Enable Logging: Configure Monolog to log encryption errors:
    monolog:
        handlers:
            encryption:
                type: stream
                path: "%kernel.logs_dir%/encryption.log"
                level: debug
    

Extension Points

  1. Custom Cipher Providers Implement Clevage\EncryptionBundle\Provider\CipherKeyProviderInterface for dynamic keys:

    class OrganizationCipherKeyProvider implements CipherKeyProviderInterface {
        public function getCipherKey(): string {
            return $this->getOrganizationKey($_SESSION['org_id']);
        }
    }
    
  2. Custom Encryption Types Extend the bundle to support new types (e.g., encrypt_json):

    class JsonEncryptionType extends EncryptionType {
        public function convertToDatabaseValue($value, AbstractPlatform $platform) {
            return parent::convertToDatabaseValue(json_encode($value), $platform);
        }
    }
    
  3. Key Management Replace the default key storage with a secrets manager (e.g., AWS KMS):

    cleverage_encryption:
        cipher_key_provider: app.aws_kms_key_provider
    

Configuration Quirks

  • Environment Variables: Ensure ENCRYPTION_KEY and ENCRYPTION_IV are 32/16-byte hex strings, respectively.
  • Doctrine Cache: Clear the metadata cache after adding new encrypted fields:
    php bin/console doctrine:cache:clear-metadata
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware