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



我找到了这个问题,这与我需要做的相同:你如何加密和解密PHP字符串?我已经让一切工作到在保存数据之前加密数据的程度。在事件函数onExtensionBeforeSave中,我可以访问该表。我可以从jinput获取需要加密的值并加密它们。我无法弄清楚的是如何将加密数据放入表对象中,以便在存储/保存之前替换未加密的数据。

我能够弄清楚这一点。在扩展事件onExtensionBeforeSave中,我获取发布数据,加载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 函数中解密它。我回答这个问题以防有人需要它,如果人们看到改进,或者如果它完全是垃圾,我希望得到一些批评......

最新更新