Skip to the content
Precision Soft
All projects

Symfony Doctrine Encrypt

PHP

A Symfony bundle with encrypted Doctrine field types, including a deterministic one you can still search with WHERE. Console commands encrypt or decrypt the data you already have.

View on GitHubcomposer require precision-soft/symfony-doctrine-encrypt

Symfony Doctrine Encrypt is a Symfony bundle for transparent AES-256 encryption of Doctrine ORM entity fields. The work is done by custom Doctrine types. The entity always holds the plaintext, and values are encrypted and decrypted at the persistence layer.

It is for Symfony applications that must keep personal or sensitive columns encrypted at rest, even columns that still need a WHERE clause. Console commands encrypt, decrypt and rotate an existing database. It requires PHP 8.2 or newer with ext-openssl, Doctrine ORM 3, Doctrine DBAL 4 and Symfony 7 or 8. Symfony 8 needs PHP 8.4.

Installation

composer require precision-soft/symfony-doctrine-encrypt

Register the bundle in config/bundles.php:

use PrecisionSoft\Doctrine\Encrypt\PrecisionSoftDoctrineEncryptBundle;
 
return [
    PrecisionSoftDoctrineEncryptBundle::class => ['all' => true],
];

Quick start

Create config/packages/precision_soft_doctrine_encrypt.yaml:

precision_soft_doctrine_encrypt:
    salt: '%env(APP_ENCRYPTION_SALT)%'
    encryptors:
        - PrecisionSoft\Doctrine\Encrypt\Encryptor\Aes256Encryptor
        - PrecisionSoft\Doctrine\Encrypt\Encryptor\Aes256FixedEncryptor
    enabled_types: [encryptedAes256, encryptedAes256fixed]

salt is required and must be at least 32 characters; it is HKDF input material, not a password. encryptors and enabled_types are optional and default to every registered encryptor and its type. Generate a salt, keep it in a secret manager and never commit it:

php -r "echo base64_encode(random_bytes(48));"

Map the fields with one of the two encrypted types:

#[ORM\Entity]
class Customer
{
    #[ORM\Column(type: 'encryptedAes256')]
    private string $name;
 
    #[ORM\Column(type: 'encryptedAes256fixed')]
    private string $email;
}

Encryption types

  • encryptedAes256 (Aes256Type): non-deterministic, a random nonce per encryption, so the same plaintext produces a different ciphertext each time. This is the secure default.
  • encryptedAes256fixed (Aes256FixedType): deterministic, the nonce is derived from the plaintext, which enables WHERE queries at the cost of revealing that two rows hold the same value.

To search a deterministic column, encrypt the parameter with EntityService::setEncryptedParameter(). It throws NonDeterministicEncryptorException for a field whose encryptor is not deterministic.

public function findByEmail(string $email): ?Customer
{
    $queryBuilder = $this->createQueryBuilder('c')
        ->where('c.email = :email');
 
    $this->entityService->setEncryptedParameter($queryBuilder, 'email', Customer::class, 'email', $email);
 
    return $queryBuilder->getQuery()->getOneOrNullResult();
}

EntityService also exposes encrypt(), decrypt(), hasEncryptor(), hasEncryptedValue() and getEntitiesWithEncryption().

Commands

php bin/console precision-soft:doctrine:database:encrypt
php bin/console precision-soft:doctrine:database:decrypt
php bin/console precision-soft:doctrine:database:rotate

encrypt encrypts an existing plaintext database after enabling the bundle, decrypt reverses it before disabling the bundle, and rotate re-encrypts rows under the current salt without an intermediate plaintext database. All three ask for confirmation (skip it with --no-interaction), accept --manager for a specific entity manager, and share options for long runs: --batch-size (default 50), --entity, --checkpoint for a resumable JSON cursor, --from-id and --dry-run. A checkpoint belongs to the command, entity manager and salt version that wrote it, and a run refuses a file written under another scope.

Key rotation

Configure versioned salts and point current_salt_version at the one used for new writes. Every ciphertext carries its salt version, so rows written under an older version stay readable.

precision_soft_doctrine_encrypt:
    salts:
        v1: '%env(APP_ENCRYPTION_SALT_V1)%'
        v2: '%env(APP_ENCRYPTION_SALT_V2)%'
    current_salt_version: v2

salt and salts are mutually exclusive. The online rotation is:

  • Deploy the new salt next to the old one, with current_salt_version on the new version.
  • Run database:rotate to re-encrypt every row under the current salt.
  • Confirm with database:rotate --dry-run --verify, which writes nothing and fails while any value is still on another salt version, then drop the old salt.

Dropping a salt before its rows are rotated makes those rows unreadable. Deterministic columns encrypted under the old salt stop matching WHERE queries until they are rotated. An offline path with decrypt and encrypt in a maintenance window is also supported.

Security notes

  • AES-256-CTR with HMAC-SHA256; encryption, MAC and nonce subkeys are derived separately from the salt through HKDF-SHA256, and the raw salt is never used as a key.
  • Tampered or corrupted values fail MAC verification on decryption.
  • encrypt() returns already-encrypted data unchanged, which prevents double encryption.
  • Encryptors cannot be serialised, are reduced to their algorithm and salt version in dumps, and the salt is marked #[\SensitiveParameter]. var_export() remains an exposure and must not be used on an encryptor.
  • Ciphertext is roughly 1.34 times the plaintext plus about eighty bytes of envelope; size columns for the ciphertext. A column without a declared length is created at 1000.

Custom encryptors, for example backed by an external KMS, implement EncryptorInterface, or DeterministicEncryptorInterface for WHERE support, and are registered as tagged services. Only one encryptor per Doctrine type can be active.

Documentation

  • README: full configuration, the EntityService API, command options, format versioning and upgrade notes.
  • CHANGELOG: release history.
  • Example application: a runnable customer directory with deterministic lookups, salt rotation and resumable checkpoints.