Where to encrypt/decrypt my data?

后端 未结 3 1383
情深已故
情深已故 2021-01-31 23:41

I\'m using Symfony 2 with Doctrine 2.

I need to encrypt a field in my entity using an encryption service, and I\'m wondering where should I put this logic.

I\'m

3条回答
  •  灰色年华
    2021-02-01 00:11

    I don't know if it's the right way at all, but I implemented this recently by creating a custom mapping type, as per the Doctrine docs. Something like the following:

    class EncryptedStringType extends TextType
    {
        const MYTYPE = 'encryptedstring'; // modify to match your type name
    
        public function convertToPHPValue($value, AbstractPlatform $platform)
        {
            return base64_decode($value);
        }
    
        public function convertToDatabaseValue($value, AbstractPlatform $platform)
        {
            return base64_encode($value);
        }
    
        public function getName()
        {
            return self::MYTYPE;
        }
    }
    

    I registered this type in my bundle class:

    class MyOwnBundle extends Bundle
    {
        public function boot()
        {
            $em = $this->container->get("doctrine.orm.entity_manager");
            try
            {
                Type::addType("encryptedstring", "My\OwnBundle\Type\EncryptedStringType");
    
                $em->
                    getConnection()->
                    getDatabasePlatform()->
                    registerDoctrineTypeMapping("encryptedstring", "encryptedstring");
            } catch (\Doctrine\DBAL\DBALException $e)
            {
                // For some reason this exception gets thrown during
                // the clearing of the cache. I didn't have time to
                // find out why :-)
            }
        }
    }
    

    and then I was able to reference it when creating my entities, eg:

    /**
     * @ORM\Column(type="encryptedstring")
     * @Assert\NotBlank()
     */
    protected $name;
    

    This was a quick implementation, so I'd be interested to know the correct way of doing it. I presume also that your encryption service is something available from the container; I don't know how feasible/possible it would be to pass services into custom types this way either... :-)

提交回复
热议问题