duanpu5048 2018-06-07 18:01
浏览 72

如何在Symfony中处理AES密钥

I'm developing a web app using Symfony 3.4 with PHP 7.2 and a SQLite db.

I want to encrypt some fields of my entity using AES-256 using standard libraries - openssl or sodium - but I'm really not sure on how to properly do it so I'm asking for your guidance before I make many big awful mistakes:

  1. what are the best practices for storing key and IV?
  2. is it relevant where I put it as long as it is not accessible by the web browser? I'm thinking to put them in the config.yml but it feels wrong, very wrong
  3. which library is more secure between openssl and sodium?
  • 写回答

1条回答 默认 最新

  • dongyi2425 2018-06-08 12:10
    关注

    I'm using the following code where my secret is stored in the parameters.yml so it will no be visible if you push it to Git.

    /**
     * SecurityHelper.
     *
     * @author Kengy Van Hijfte <development@kengy.be>
     */
    class SecurityHelper
    {
        /** @var  string $secret */
        private $secret;
    
        public function __construct($secret)
        {
            $this->secret = $secret;
        }
    
        /**
         * @param $text
         * @return string
         */
        public function encrypt($text)
        {
            if (null == $text)
                return null;
    
            // Generate an initialization vector
            $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
            // Encrypt the data using AES 256 encryption in CBC mode using our encryption key and initialization vector.
            $encrypted = openssl_encrypt($text, 'aes-256-cbc', $this->secret, 0, $iv);
            // The $iv is just as important as the key for decrypting, so save it with our encrypted data using a unique separator (::)
            return base64_encode($encrypted . '::' . $iv);
        }
    
        /**
         * @param $text
         * @return string
         */
        public function decrypt($text)
        {
            if (null == $text)
                return null;
    
            // To decrypt, split the encrypted data from our IV - our unique separator used was "::"
            list($encrypted_data, $iv) = explode('::', base64_decode($text), 2);
            return openssl_decrypt($encrypted_data, 'aes-256-cbc', $this->secret, 0, $iv);
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 任务A:大数据平台搭建(容器环境)怎么做呢?
  • ¥15 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计