DoctrineEncryptBundle icon indicating copy to clipboard operation
DoctrineEncryptBundle copied to clipboard

FindBy encrypted field

Open scolandrea opened this issue 9 years ago • 1 comments

Hi,

Im trying finyby using encrypted field but seem doesnt work this way.

How can i do it?,

Regards!

scolandrea avatar Aug 05 '15 19:08 scolandrea

Hi,

You can't get back the encryptor from the subscriber (private without getter) so you have to declare a whole class yourself. Basically create a new class :

<?php

namespace Vendor\Projet\CoreBundle\Encryptor;

use VMelnik\DoctrineEncryptBundle\Encryptors\EncryptorInterface;

class CustomDataEncryptor implements EncryptorInterface
{

    /**
     * @var string
     */
    private $secretKey;

    /**
     * @var string
     */
    private $initializationVector;

    /**
     * {@inheritdoc}
     */
    public function __construct($key) {
        $this->secretKey = md5($key);
        $this->initializationVector = mcrypt_create_iv(
            mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB),
            MCRYPT_RAND
        );
    }

    /**
     * {@inheritdoc}
     */
    public function encrypt($data) {
        return trim(base64_encode(mcrypt_encrypt(
            MCRYPT_RIJNDAEL_256,
            $this->secretKey,
            $data,
            MCRYPT_MODE_ECB,
            $this->initializationVector
        )));
    }

    /**
     * {@inheritdoc}
     */
    public function decrypt($data) {
        return trim(mcrypt_decrypt(
            MCRYPT_RIJNDAEL_256,
            $this->secretKey,
            base64_decode($data),
            MCRYPT_MODE_ECB,
            $this->initializationVector
        ));
    }

}

and then reference that service in the service.yml :

custom_data_encryptor:
        class: Vendor\Projet\CoreBundle\Encryptor\CustomDataEncryptor
        arguments: [%vmelnik_doctrine_encrypt.secret_key%]

let the bundle know about your new encryptor class :

vmelnik_doctrine_encrypt:
    secret_key: xxx
    encryptor: aes256
    encryptor_class: Vendor\Project\CoreBundle\Encryptor\CustomDataEncryptor
    db_driver: orm

then you can find like that for exemple (I suppose you are in a controller just for the demo) :

// Find a user by his secret surname

$query = 'Alan';
$encryptor = $this->get('custom_data_encryptor');
$this->getDoctrine()->getManager()->getRepository('VendorProjectCoreBundle:User')->findBySurname(
     'secret_surname' => $encryptor->encrypt($query)
);

jr-k avatar Feb 17 '16 21:02 jr-k