定制 specshaper/encrypt-bundle 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

specshaper/encrypt-bundle

Composer 安装命令:

composer require specshaper/encrypt-bundle

包简介

Bundle provides a service for encrypting values via attribute.

关键字:

README 文档

README

A bundle to handle encoding and decoding of parameters using OpenSSL and Doctrine lifecycle events.

Features include:

  • V5 is Symfony 6.4|7.4|8.0 PHP >=8.2
  • V4 is Symfony 6.4|7.0 PHP 8.2 and beta.
  • V3 is Symfony 5.4|6.0 PHP 8.0. I'm moving my projects to symfony 7 so will not maintain after this v3.2.
  • V2 is Symfony 5 not maintained.
  • v1 is Symfony 3.4 not maintained.
  • Uses OpenSSL
  • Uses Lifecycle events

Features road map:

  • Create a factory method to expand for different encryptors
  • Create a twig function to decrypt encoded values
  • Expand parameters to allow selection of encoding method
  • 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 specshaper/encrypt-bundle dev-master

This command requires you to have Composer installed globally, as explained in the installation chapter of the Composer documentation.

Step 2: Enable the bundle

The receipe will create a package config file under config/packages/spec_shaper_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 [
    ...
    SpecShaper\EncryptBundle\SpecShaperEncryptBundle::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 ###
SPEC_SHAPER_ENCRYPT_KEY= change_me!
###< encrypt-bundle ###

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

# app/config/packages/spec_shaper_encrypt.yaml
spec_shaper_encrypt:
  encrypt_key: '%env(SPEC_SHAPER_ENCRYPT_KEY)%'
  is_disabled: false # Turn this to true to disable the encryption.
  connections:   # Optional, define the connection name(s) for the listener
    - 'default'
    - 'tenant'
  listener_class: App\EventListener\MyCustomListener # Optional to override the bundle Doctrine event listener.
  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.

You can extend the EncryptBundle default Listener and override its methods. Use the 'listener_class' option to point the bundle at your custom listener.

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 SpecShaper\EncryptBundle\Annotations\Encrypted;

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

Note that the legacy annotation '@Encrypted' in the parameters is deprecated and will be discontinued in the next major update.

<?php

    /**
     * A PPS number is always 7 numbers followed by either one or two letters.
     * 
     * @ORM\Column(type="string")
     */
    #[Encrypted]
    protected string $taxNumber;
    
    /**
     * True if the user is self employed.
     * 
     * @ORM\Column(type="string", nullable=true)
     */
    #[Encrypted]
    protected ?bool $isSelfEmployed;
    
    /**
     * Date of birth
     * 
     * @Encrypted
     * Note that the above Encrypted property is a legacy annotation, and while
     * it still is supported, it will be deprecated in favour of Attributes.
     * 
     * @ORM\Column(type="string", nullable=true)
     */
    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 SpecShaper\EncryptBundle\Encryptors\EncryptorInterface;
    ...
    /**
     * @var SpecShaper\EncryptBundle\Encryptors\EncryptorInterface;
     */
    private $encryptor;
    ...
    
    // Inject the Encryptor from the service container at class construction
    public function __construct(EncryptorInterface $encryptor)
    {
        $this->encryptor = $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 SpecShaper\EncryptBundle\Event\EncryptEvent;
    use SpecShaper\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 listener 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 decrypt or encrypt.

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

specshaper/encrypt-bundle 适用场景与选型建议

specshaper/encrypt-bundle 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 684.58k 次下载、GitHub Stars 达 104, 最近一次更新时间为 2017 年 10 月 21 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「encrypt bundle」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 specshaper/encrypt-bundle 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 specshaper/encrypt-bundle 我们能提供哪些服务?
定制开发 / 二次开发

基于 specshaper/encrypt-bundle 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 684.58k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 105
  • 点击次数: 27
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 104
  • Watchers: 8
  • Forks: 42
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2017-10-21