如何加密存储在数据库中的Joomla配置参数?

时间:2018-02-28 21:51:48

标签: joomla joomla3.0

我发现了这个问题,这与我需要做的事情相同: How do you Encrypt and Decrypt a PHP String? 在保存数据之前,我已经完成了所有工作以加密数据。在事件函数onExtensionBeforeSave中,我可以访问该表。我可以从jinput获取需要加密的值并加密它们。我无法弄清楚的是如何将加密数据放入表对象中,以便在存储/保存之前替换未加密的数据。

1 个答案:

答案 0 :(得分:0)

我能够弄清楚这一点。在扩展事件onExtensionBeforeSave中,我获取post数据,加载config.xml文件以检查我的自定义字段的表单字段(type ='encryptedtext'),加密那些并使用表对象绑定并检查它,所以它将被正确存储。

     function onExtensionBeforeSave($context, $table, $isNew)
 {
     $jinput = JFactory::getApplication()->input;
     $component = $jinput->get('component');

     if($component !== 'com_store') // Only encrypting fields in the store component for now
     {
         return true;
     }

     $form_path = JPATH_ADMINISTRATOR . '\\components\\' . $component . '\\config.xml';
     $xml = simplexml_load_file($form_path);
     $has_encrypted = false;
     foreach($xml->fieldset as $fieldset)
     {
         foreach($fieldset as $field)
         {
            if($field['type'] == 'encryptedtext') // is our custom form field type to be encrypted
            {
                $has_encrypted = true;
                if(!$fields) // get fields if it hasn't already been done
                {
                    $fields = $jinput->get('jform', '', 'array');   
                }
                $field = (string)$field['name'];
                $value = (string)$fields[$field];
                $cipher = "aes-256-ctr";
                $ivlen = openssl_cipher_iv_length($cipher);
                $iv = openssl_random_pseudo_bytes($ivlen, $isStrongCrypto);
                if (!$isStrongCrypto) 
                {
                    throw new \Exception("Not a strong key");
                }
                $keyhash = openssl_digest($component, 'sha256', true);
                $opts =  OPENSSL_RAW_DATA;
                $encrypted = openssl_encrypt($value, $cipher, $keyhash, $opts, $iv);
                if ($encrypted === false)
                {
                    throw new \Exception('Encryption failed: ' . openssl_error_string());
                }
                $result = $iv . $encrypted;
                $result = base64_encode($result);
                $fields[$field] = $result;
            }
         }
     }         
     if(!has_encrypted)
     {
         return false;
     }
     $data = array(
         'params'=>$fields,
         'option'=>$component
     );
     if (!$table->bind($data))
     {
         throw new RuntimeException($table->getError());
     }
     if (!$table->check())
     {
         throw new RuntimeException($table->getError());
     }
     return true;
}

剩下的就是在自定义字段的getInput函数中解密它。如果有人需要,我会回答这个问题,如果人们看到改进,或者它是完全垃圾,我会喜欢一些批评......