PHP Classes

Symfony PHP Encrypt Decrypt Bundle: Encrypt and decrypt values using OpenSSL

Recommend this page to a friend!
  Info   Documentation   View files Files   Install with Composer Install with Composer   Download Download   Reputation   Support forum   Blog    
Last Updated Ratings Unique User Downloads Download Rankings
2024-03-06 (7 months ago) RSS 2.0 feedNot enough user ratingsTotal: 31 This week: 1All time: 11,098 This week: 36Up
Version License PHP version Categories
encryptbundle 1.0.0MIT/X Consortium ...8.2Cryptography, Libraries, Templates, S..., P...
Description 

Author

This package can encrypt and decrypt values using OpenSSL.

It provides several classes to use in applications based on the Symfony framework that can encrypt and decrypt values stored and retrieved by the applications using the OpenSSL library.

Currently, the package can:

- Uses event listeners to encrypt transparently and decrypt data

- Provide an extension to the twig template engine to decrypt encoded values

- Etc..

Innovation Award
PHP Programming Innovation award nominee
March 2024
Number 3
Encryption protects sensitive data from being stolen by people with bad intentions.

Encryption is usually used during the transmission of data sent between two computers, such as the content of Web pages served by a secure site using SSL encryption.

Encryption can also be used to store and encrypt data in databases.

This package implements a transparent encryption and decryption solution for PHP applications based on the Symfony framework, making it easy for Symfony developers to use.

Manuel Lemos
Picture of Francisco
Name: Francisco <contact>
Classes: 1 package by
Country: Cuba Cuba
Age: ???
All time rank: 451615 in Cuba Cuba
Week rank: 44 Up1 in Cuba Cuba Up
Innovation award
Innovation award
Nominee: 1x

Instructions

Install with composer: composer require psolutions/encrypt-bundle

Documentation

PSolutions Encrypt Bundle

A bundle to handle encoding and decoding of parameters using OpenSSL and Doctrine lifecycle events. It's a fork of https://github.com/mogilvie/EncryptBundle

Features include: - v1 is Symfony 6.4 and 7.0 compatible. - Uses OpenSSL - Uses Event listeners

Features road map:

  • [x] Create a factory method to expand for different encryptors
  • [x] Create a twig function to decrypt encoded values
  • [x] Expand parameters to allow selection of encoding method
  • [x] Create CLI commands to encrypt and decrypt the entire database
  • [ ] Handle DateTime data types via the bundle.

License

This bundle is under the MIT license. See the complete license in the bundle:

Resources/meta/LICENSE

About

EncryptBundle has been written for the Parolla Plugins and Parolla websites to encode users private data. The bundle is expanded in a larger gdpr-bundle.

Reporting an issue or a feature request

Issues and feature requests are tracked in the Github issue tracker.

When reporting a bug, it may be a good idea to reproduce it in a basic project built using the Symfony Standard Edition to allow developers of the bundle to reproduce the issue by simply cloning it and following some steps.

Installation

Step 1: Install from package

Open a command console, enter your project directory and execute the following command to download the latest development version of this bundle:

$ composer require psolutions/encrypt-bundle

Step 2: Enable the bundle

The receipe will create a package config file under config/packages/psolutions_encrypt.yaml.

If required, enable the bundle by adding it to the list of registered bundles in the config/bundles.php file of your project:

<?php

return [
    ...
    PSolutions\EncryptBundle\PSolutionsEncryptBundle::class => ['all' => true],
];

Step 2: Configure the bundle

Generate a 256-bit key using the command provided in the bundle.

$ bin/console encrypt:genkey

Copy the key into your .env file.

###> encrypt-bundle ###
PSOLUTIONS_ENCRYPT_KEY= change_me!
###< encrypt-bundle ###

Maker will have created a packages yaml file. The key is resolved in there.

# app/config/packages/psolutions_encrypt.yaml
psolutions_encrypt:
  encrypt_key: '%env(PSOLUTIONS_ENCRYPT_KEY)%'
  is_disabled: false # Turn this to true to disable the encryption.
  connections:   # Optional, define the connection name(s) for the subscriber to listen to.
    - 'default'
    - 'tenant'
  encryptor_class: App\Encryptors\MyCustomEncryptor # Optional to override the bundle OpenSslEncryptor.
  annotation_classes: # Optional to override the default annotation/Attribute object.
    - App\Annotation\MyAttribute

You can disable encryption by setting the 'is_disabled' option to true. Decryption still continues if any values contain the \<ENC> suffix.

If you want to define your own annotation/attribute, then this can be used to trigger encryption by adding the annotation class name to the 'annotation_classes' option array.

You can pass the class name of your own encyptor service using the optional encryptorClass option.

Alternative EncryptKeyEvent

The EncryptKey can be set via a dispatched event listener, which overrides any .env or param.yml defined key. Create a listener for the EncryptKeyEvents::LOAD_KEY event and set your encryption key at that point.

Step 3: Create the entities

Add the Encrypted attribute class within the entity.

<?php
...
use PSolutions\EncryptBundle\Annotations\Encrypted;

Add the attribute #[Encrypted] to the properties you want encrypted.

<?php

    #[Encrypted]
    #[Column]
    protected string $taxNumber;
    
    #[Column(type: string, nullable: true)]
    #[Encrypted]
    protected ?bool $isSelfEmployed;
    
    /
     * Date of birth
     */
    #[Encrypted]
    #[Column]
    protected ?String $dob;
   

Where encrypting a field you will need to set the column type as string.

Your getters and setters may also need to be type declared.

For example, boolean should either be return declared bool, or return a bool using a ternary method.

<?php
    /
     * Get isSelfEmployed
     *
     * @return boolean
     */
    public function isSelfEmployed(): bool
    {
        return $this->isSelfEmployed;
    }

    /
     * Get isSelfEmployed
     *
     * @return boolean
     */
    public function isSelfEmployed(): bool
    {
        return ($this->isSelfEmployed == 1 ? true: false);
    }

For DateTime parameters store the date as a string, and use the getters and setters to convert that string.

You may also need to create a DataTransformer if you are using the parameter in a form with the DateType form type.

Step 4: General Use

The bundle comes with an DoctrineEncryptListener. This listener catches the doctrine events onLoad, onFlush and postFlush.

The onLoad event listener will decrypt your entity parameter at loading. This means that your forms and form fields will already be decrypted.

The onFlush and postFlush event listeners will check if encryption is enabled, and encrypt the data before entry to the database.

So, in normal CRUD operation you do not need to do anything in the controller for encrypting or decrypting the data.

Step 5: Decrypt in services and controllers

You can of course inject the EncryptorInterface service any time into classes either by using autowiring or defining the injection in your service definitions.

<?php
    use PSolutions\EncryptBundle\Encryptors\EncryptorInterface;
        
    // Inject the Encryptor from the service container at class construction
    public function __construct(private readonly EncryptorInterface $encryptor)
    {
        
    }
    
    // Inject the Encryptor in controller actions.
    public function editAction(EncryptorInterface $encryptor)
    {
        ...
        // An example encrypted value, you would get this from your database query.
        $encryptedValue = "3DDOXwqZAEEDPJDK8/LI4wDsftqaNCN2kkyt8+QWr8E=<ENC>";
        
        $decrypted = $encryptor->decrypt($encryptedValue);
        ...
    }


Or you can dispatch the EncryptEvent.

<?php
    ...
    use PSolutions\EncryptBundle\Event\EncryptEvent;
    use PSolutions\EncryptBundle\Event\EncryptEvents;
    use Symfony\Component\EventDispatcher\EventDispatcherInterface;
    ...
    
    public function indexAction(EventDispatcherInterface $dispatcher)
    {
        ...
        // An example encrypted value, you would get this from your database query.
        $event = new EncryptEvent("3DDOXwqZAEEDPJDK8/LI4wDsftqaNCN2kkyt8+QWr8E=<ENC>");

        $dispatcher->dispatch(EncryptEvents::DECRYPT, $event);
        
        $decrypted = $event->getValue();
    }

Step 5: Decrypt in templates

If you query a repository using a select with an array result then the doctrine onLoad event subscriber will not decrypt any encrypted values.

In this case, use the twig filter to decrypt your value when rendering.

{{ employee.bankAccountNumber | decrypt }}

Commands

You have already seen the command to generate a encryption key:

$ bin/console encrypt:genkey

You can decrypt/encrypt the entire database using the following

$ bin/console encrypt:database decrypt connection

The requried argument should be be decrypt or encrypt.

There is an option to define the database connection if you employ multiple connections in your application.


  Files folder image Files (25)  
File Role Description
Files folder image.github (1 file)
Files folder imageconfig (1 file)
Files folder imagesrc (1 file, 7 directories)
Files folder imagetests (1 directory)
Files folder imagetranslations (1 file)
Accessible without login Plain text file CHANGELOG.md Data Auxiliary data
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file README.md Doc. Read me

  Files folder image Files (25)  /  .github  
File Role Description
  Accessible without login Plain text file FUNDING.yml Data Auxiliary data

  Files folder image Files (25)  /  config  
File Role Description
  Accessible without login Plain text file services.yaml Data Auxiliary data

  Files folder image Files (25)  /  src  
File Role Description
Files folder imageAnnotations (1 file)
Files folder imageCommand (2 files)
Files folder imageEncryptors (3 files)
Files folder imageEvent (5 files)
Files folder imageEventListener (3 files)
Files folder imageException (1 file)
Files folder imageTwig (1 file)
  Plain text file PSolutionsEncryptBundle.php Class Class source

  Files folder image Files (25)  /  src  /  Annotations  
File Role Description
  Plain text file Encrypted.php Class Class source

  Files folder image Files (25)  /  src  /  Command  
File Role Description
  Plain text file EncryptDatabaseCommand.php Class Class source
  Plain text file GenKeyCommand.php Class Class source

  Files folder image Files (25)  /  src  /  Encryptors  
File Role Description
  Plain text file EncryptorFactory.php Class Class source
  Plain text file EncryptorInterface.php Class Class source
  Plain text file OpenSslEncryptor.php Class Class source

  Files folder image Files (25)  /  src  /  Event  
File Role Description
  Plain text file EncryptEvent.php Class Class source
  Plain text file EncryptEventInterface.php Class Class source
  Plain text file EncryptEvents.php Class Class source
  Plain text file EncryptKeyEvent.php Class Class source
  Plain text file EncryptKeyEvents.php Class Class source

  Files folder image Files (25)  /  src  /  EventListener  
File Role Description
  Plain text file DoctrineEncryptListener.php Class Class source
  Plain text file DoctrineEncryptListenerInterface.php Class Class source
  Plain text file EncryptEventListener.php Class Class source

  Files folder image Files (25)  /  src  /  Exception  
File Role Description
  Plain text file EncryptException.php Class Class source

  Files folder image Files (25)  /  src  /  Twig  
File Role Description
  Plain text file EncryptExtension.php Class Class source

  Files folder image Files (25)  /  tests  
File Role Description
Files folder imageUnit (2 directories)

  Files folder image Files (25)  /  tests  /  Unit  
File Role Description
Files folder imageCommand (1 file)
Files folder imageEncryptors (1 file)

  Files folder image Files (25)  /  tests  /  Unit  /  Command  
File Role Description
  Plain text file GenKeyCommandTest.php Class Class source

  Files folder image Files (25)  /  tests  /  Unit  /  Encryptors  
File Role Description
  Plain text file OpenSslEncryptorTest.php Class Class source

  Files folder image Files (25)  /  translations  
File Role Description
  Accessible without login Plain text file messages.en.xlf Data Auxiliary data

The PHP Classes site has supported package installation using the Composer tool since 2013, as you may verify by reading this instructions page.
Install with Composer Install with Composer
 Version Control Unique User Downloads Download Rankings  
 100%
Total:31
This week:1
All time:11,098
This week:36Up