robrichards/xmlseclibs

How to display two tags when the node content is empty.

Closed this issue · 3 comments

How to display two tags when the node content is empty.

For example, in this case:

<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" /> <SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />

That's what I want

<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"></CanonicalizationMethod> <SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"></SignatureMethod>

If I'm not mistaken, in XML these are considered to be exactly the same thing and any parser should recognise both forms. But still, I think you should be able to change this behaviour by passing the LIBXML_NOEMPTYTAG constant to your DOMdocument's saveXML() call: http://nl1.php.net/manual/en/domdocument.savexml.php

@thijskh Thank you very much for your help, the following is my method, left to the people.

protected function generateXMLSignFields($xml, $prefix = 'ds')
        {
            // 加载要签名的XML
            $doc = new \DOMDocument();
            $doc->loadXML($xml);

            // 创建一个新的安全对象
            $objDSig = new XMLSecurityDSig($prefix);
            // 使用c14n专属规范化
            $objDSig->setCanonicalMethod(XMLSecurityDSig::C14N);
            // 签名使用 SHA-256
            $objDSig->addReference(
                $doc,
                XMLSecurityDSig::SHA1,
                ['http://www.w3.org/2000/09/xmldsig#enveloped-signature'],
                ['force_uri' => true]
            );

            // 创建一个新的(私有)安全密钥
            $objKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA256, ['type' => 'private']);

            // 如果密钥有密码,则使用它进行设置
            // $objKey->passphrase = '<passphrase>';

            // 加载私钥
            $objKey->loadKey("-----BEGIN RSA PRIVATE KEY-----\n" . wordwrap($this->privateKey, 64, "\n", true) . "\n-----END RSA PRIVATE KEY-----\n");

            // 对XML文件签名
            $objDSig->sign($objKey);

            // 将关联的公钥添加到签名
            // $objDSig->add509Cert("-----BEGIN PUBLIC KEY-----\n" . wordwrap($this->publicKey, 64, "\n", true) . "\n-----END PUBLIC KEY-----\n");

            // 将签名附加到XML
            $objDSig->appendSignature($doc->documentElement);
            // saveXML 里面 LIBXML_NOEMPTYTAG 是为了不简写空值的标签。例:(<test />  => <test></test>)
            return $doc->saveXML($doc->documentElement, LIBXML_NOEMPTYTAG);
        }

Closing as appears everything is all set