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

Doctrine Encrypted Types Laravel Package

aeliot/doctrine-encrypted-types

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require aeliot/doctrine-encrypted-types
    

    Ensure doctrine/doctrine-bundle is also installed (required dependency).

  2. First Use Case: Encrypting a Field

    • Register the type in your Entity:
      use Aeliot\DoctrineEncryptedTypes\Types\EncryptedStringType;
      
      /**
       * @ORM\Column(type="encrypted_string")
       */
      private $sensitiveData;
      
    • Configure encryption keys in config/packages/doctrine_encrypted.yaml:
      aeliot_doctrine_encrypted:
          encryption_keys:
              - '%env(ENCRYPTION_KEY)%'
      
  3. Key Setup Generate a secure key (e.g., 32-byte AES-256) and store it in .env:

    ENCRYPTION_KEY=your_32_byte_base64_encoded_key_here
    

Implementation Patterns

Common Workflows

  1. Entity Integration

    • Use built-in types (encrypted_string, encrypted_text, encrypted_int, etc.) for sensitive fields.
    • Example for a User entity:
      /**
       * @ORM\Column(type="encrypted_string")
       */
      private $creditCardNumber;
      
      public function getCreditCardNumber(): ?string
      {
          return $this->creditCardNumber;
      }
      
  2. Custom Encryption Logic

    • Extend EncryptedType for custom behavior:
      use Aeliot\DoctrineEncryptedTypes\Types\EncryptedType;
      
      class CustomEncryptedType extends EncryptedType
      {
          public function getName(): string
          {
              return 'custom_encrypted_string';
          }
      }
      
    • Register the custom type in services.yaml:
      services:
          App\Doctrine\CustomEncryptedType:
              tags: [doctrine.type]
      
  3. Querying Encrypted Data

    • Use EncryptedExpressionBuilder for comparisons:
      $qb = $entityManager->createQueryBuilder();
      $qb->andWhere(
          $qb->expr()->eq(
              'entity.sensitiveField',
              $qb->expr()->literal('plaintext_value')
          )
      );
      // Automatically decrypts during query execution.
      
  4. Bulk Operations

    • Leverage DoctrineEncryptedBundle for batch encryption/decryption (if installed):
      $em->getRepository(User::class)->encryptField('creditCardNumber', $users);
      

Gotchas and Tips

Pitfalls

  1. Key Management

    • Never hardcode keys in source. Use environment variables or a secure secrets manager.
    • Key rotation: If keys change, existing encrypted data becomes unreadable. Plan for backward compatibility or migration scripts.
  2. Performance Overhead

    • Encryption/decryption adds latency. Benchmark with your workload:
      // Disable encryption for non-sensitive fields to avoid unnecessary overhead.
      /**
       * @ORM\Column(type="string")
       */
      private $nonSensitiveField;
      
  3. Query Limitations

    • Encrypted fields cannot be used in ORDER BY, GROUP BY, or complex aggregations (e.g., SUM). Decrypt first in application logic if needed.
  4. Doctrine Cache Invalidation

    • Clear metadata cache after adding new encrypted types:
      php bin/console doctrine:cache:clear-metadata
      

Debugging Tips

  1. Enable Logging Add to config/packages/monolog.yaml:

    handlers:
        doctrine_encrypted:
            type: stream
            path: "%kernel.logs_dir%/doctrine_encrypted.log"
            level: debug
            channels: ["doctrine"]
    
  2. Verify Encryption Check raw database values vs. decrypted values:

    $user = $em->find(User::class, 1);
    var_dump($user->getCreditCardNumber()); // Decrypted
    var_dump($em->getConnection()->fetchOne('SELECT credit_card_number FROM user WHERE id = 1')); // Encrypted
    
  3. Common Errors

    • "Encryption key not found": Ensure encryption_keys is configured in doctrine_encrypted.yaml.
    • "Type not found": Register the type in services.yaml with the doctrine.type tag.

Extension Points

  1. Custom Cipher Override getCipher() in a custom type for non-AES encryption (e.g., ChaCha20):

    protected function getCipher(): string
    {
        return 'chacha20';
    }
    
  2. Key Derivation Use getKey() to implement key derivation (e.g., PBKDF2) from a master key:

    protected function getKey(): string
    {
        return hash_hmac('sha256', $this->masterKey, 'salt');
    }
    
  3. Field-Level Configuration Use attributes for dynamic encryption (Laravel-style):

    use Aeliot\DoctrineEncryptedTypes\Attributes\Encrypted;
    
    #[Encrypted(key: 'special_key')]
    private $apiToken;
    

    (Note: Requires custom attribute listener.)

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