Skip to main content

Encrypting Data with Doctrine

· 2 min read
Stephan Hochdörfer
Head of IT Business Operations

In one of our current projects, we have to store sensitive user data in the database. Naturally, I was looking how to best encrypt the data in a Symfony & Doctrine application.

I could have used Hashicorp Vault and its in-transit encryption secrets engine but that would have added another level of operations complexity to the project.

While looking for alternatives, I came across the specshaper/encrypt-bundle Composer package on GitHub. It looked promising since it hooks into the Doctrine events to encrypt and decrypt the data when needed.

Installing the bundle works as follows:

  1. Install the bundle via Composer: composer require specshaper/encrypt-bundle
  2. Add the bundle to your config/bundles.php file
  3. Generate a 256-bit key by running bin/console encrypt:genkey
  4. Add the generated key to your env.local file: SPEC_SHAPER_ENCRYPT_KEY=my_key_here

To let Doctrine know which properties of your entity should be encryptd, add the #[Encrypted] attribute:

<?php

declare(strict_types=1);

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use SpecShaper\EncryptBundle\Annotations\Encrypted;

#[ORM\Entity]
#[ORM\Table(name: 'my_entity')]
class MyEntity
{
#[ORM\Column(type: 'string')]
#[Encrypted]
private string $password;

public function getPassword(): string
{
return $this->password;
}

public function setPassword(string $password): void
{
$this->password = $password;
}
}

With the bundle set up, Doctrine will encrypt the data on write and decrypt the data automatically for you when reading the entities.