2

库:apache Santuario + xades4j。

使用 xpath 选择元素并对其进行签名。

如果我尝试对没有命名空间的简单 XML 进行签名并验证签名,则效果很好,但如果 XML 定义了命名空间,例如以下 XML:

<ClinicalDocument xmlns="urn:hl7-org:v3">
    <element1tobesigned.../>
    <element2tobesigned.../>
</ClinicalDocument>

并且在验证签名时发现异常

    858 WARN [main] org.apache.xml.security.signature.Reference - URI“#xmldsig-5fb20abe-b14c-4d84-a908-e22e776cd6f1-signedprops”的验证失败
    858 WARN [main] org.apache.xml.security.signature.Reference - 预期摘要:q0WnWFf9j0kcT46t5cXmcPnVvu5o51oAcmej/SjCazQ=
    858 WARN [main] org.apache.xml.security.signature.Reference - 实际摘要:41zXKVkRCsxUYpNZXW5b9KkZlTC9LM9WA8O7WHQz1Rg=

    xades4j.verification.ReferenceValueException:无法验证参考“#xmldsig-5fb20abe-b14c-4d84-a908-e22e776cd6f1-signedprops”

原因是 XML 命名空间 (urn:hl7-org:v3) 被添加到 xades:SignedProperties 然后摘要变得不同。

858  DEBUG [main] org.apache.xml.security.utils.DigesterOutputStream     - Pre-digested input
858  DEBUG [main] org.apache.xml.security.utils.DigesterOutputStream   - <xades:SignedProperties xmlns="urn:hl7-org:v3" ........./>

这是签名生成代码

    XadesTSigningProfile 配置文件 = 新 XadesTSigningProfile(keyProvider);
    profile.withTimeStampTokenProvider(TestTimeStampTokenProvider.class)
    .withAlgorithmsProviderEx(ExclusiveC14nForTimeStampsAlgorithmsProvider.class);  

    XadesSigner 签名者 = profile.newSigner();   

    DataObjectDesc obj1 = new DataObjectReference("")
    .withTransform(new ExclusiveCanonicalXMLWithoutComments())
    .withTransform(新的 XPathTransform(xPath);

    SignedDataObjects dataObjs = new SignedDataObjects().withSignedDataObject(obj1);

更改 2012-11-20 开始

// signer.sign(dataObjs, docToSign.getDocumentElement() );
       新信封(签名者).sign(docToSign.getDocumentElement());

更改 2012-11-20 结束

这是验证码

NodeList signatureNodeList = getSigElement(getDocument("my/my-document.signed.bes.countersign.xml"));

for (int i = 0; i < signatureNodeList.getLength(); i++) {
    Element signatureNode = (Element) signatureNodeList.item(i);
    verifySignature(signatureNode, new XadesVerificationProfile(VerifierTestBase.validationProviderMySigs));
    log.info("successful validation");          
}

public static XAdESForm verifySignature(Element sigElem,
            XadesVerificationProfile p) throws Exception {
        XAdESVerificationResult res = p.newVerifier().verify(sigElem, null);

        return res.getSignatureForm();
    }

Apache Santuario FAQ 中似乎有关于此问题的文档,

2.6. I sign a document and when I try to verify using the same key, it fails
After you have created the XMLSignature object, before you sign the document, you must embed the signature element in the owning document (using a call to XMLSignature.getElement() to retrieve the newly created Element node from the signature) before calling the XMLSignature.sign() method,

During canonicalisation of the SignedInfo element, the library looks at the parent and ancestor nodes of the Signature element to find any namespaces that the SignedInfo node has inherited. Any that are found are embedded in the canonical form of the SignedInfo. (This is not true when Exclusive Canonicalisation is used, but it is still good practice to insert the element node prior to the sign() method being called).

If you have not embedded the signature node in the document, it will not have any parent or ancestor nodes, so it will not inherit their namespaces. If you then embed it in the document and call verify(), the namespaces will be found and the canonical form of SignedInfo will be different to that generated during sign().

还有一个关于这个问题的文件如下

https://stackoverflow.com/a/12759909/1809884

看起来不是xades4j的bug,而是xml签名的问题。

--添加 2012-11-15

here is how to get the docToSign . in fact , i just reused the code in class  SignatureServicesTestBase . so i am sure that it is namespaceaware. 
static
    {
           DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
           db = dbf.newDocumentBuilder();
    }
 public static Document getDocument(String fileName) throws Exception
    {
        String path = toPlatformSpecificXMLDirFilePath(fileName);
        Document doc = db.parse(new FileInputStream(path));
        // Apache Santuario now uses Document.getElementById; use this convention for tests.
        Element elem = doc.getDocumentElement();
        DOMHelper.useIdAsXmlId(elem);
        return doc;
    }

and docToSign  is return by calling SignatureServicesTestBase.getDocument()

Document docToSign = SignatureServicesTestBase.getDocument("my/cdamessage.xml"); 

和 SignedProperties 元素如下

<xades:SignedSignatureProperties>
<xades:SigningTime>2012-11-15T13:58:26.167+09:00</xades:SigningTime>
<xades:SigningCertificate>
<xades:Cert>
<xades:CertDigest>
<ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
<ds:DigestValue>4btVb5gQ5cdcNhGpvDSWQZabPQrR9jf1x8e3YF9Ajss=</ds:DigestValue>
</xades:CertDigest>
<xades:IssuerSerial>
<ds:X509IssuerName>CN=Itermediate,OU=CC,O=ISEL,C=PT</ds:X509IssuerName>
<ds:X509SerialNumber>-119284162484605703133798696662099777223</ds:X509SerialNumber>
</xades:IssuerSerial>
</xades:Cert>
<xades:Cert>
<xades:CertDigest>
<ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
<ds:DigestValue>vm5QpbblsWV7fCYXotPhNTeCt4nk8cLFuF36L5RJ4Ok=</ds:DigestValue>
</xades:CertDigest>
<xades:IssuerSerial>
<ds:X509IssuerName>CN=TestCA,OU=CC,O=ISEL,C=PT</ds:X509IssuerName>
<ds:X509SerialNumber>-46248926895392336918291885380930606289</ds:X509SerialNumber>
</xades:IssuerSerial>
</xades:Cert>
<xades:Cert>
<xades:CertDigest>
<ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
<ds:DigestValue>AUaN+IdhKQqxIVmEOrFwq+Dn22ebTkXJqD3BoOP/x8E=</ds:DigestValue>
</xades:CertDigest>
<xades:IssuerSerial>
<ds:X509IssuerName>CN=TestCA,OU=CC,O=ISEL,C=PT</ds:X509IssuerName>
<ds:X509SerialNumber>-99704378678639105802976522062798066869</ds:X509SerialNumber>
</xades:IssuerSerial>
</xades:Cert>
</xades:SigningCertificate>
</xades:SignedSignatureProperties>
</xades:SignedProperties>

另外,我使用 xpath 来获取要签名的元素,并将命名空间(xmlns="urn:hl7-org:v3")也添加到结果中。

543  DEBUG [main] org.apache.xml.security.utils.ElementProxy     - setElement("ds:Transform", "null")
544  DEBUG [main] org.apache.xml.security.utils.ElementProxy     - setElement("dsig-xpath:XPath", "null")
658  DEBUG [main] org.apache.xml.security.utils.DigesterOutputStream     - Pre-digested input:
658  DEBUG [main] org.apache.xml.security.utils.DigesterOutputStream     - <component xmlns="urn:hl7-org:v3" Id="ES" contextConductionInd="true" typeCode="COMP">
        <section classCode="DOCSECT" moodCode="EVN">
          <code code="ES" codeSystem="2.16.840.1.113883.6.1" codeSystemName="SectionCode" codeSystemVersion="1.0" displayName="english"></code>
          <text>english</text>
        </section>
      </component>

xpath 有什么问题吗?xpath 快把我逼疯了。我想我必须从现在开始学习 xpath。

克里斯

4

1 回答 1

1

您正在创建一个封装签名,但缺少封装签名转换!由于正在对整个文档进行签名,因此必须排除签名节点本身,因为签名计算后它的某些内容会发生变化。

真不敢相信在你提到 Enveloped 类之前我没有看到它。顺便说一句,这个类只是一个用于简单、直接的封装签名的实用程序类。它甚至不应该在那里。您可以自己添加转换:

DataObjectDesc obj1 = new DataObjectReference("")
.withTransform(new EnvelopedSignatureTransform())
.withTransform(new ExclusiveCanonicalXMLWithoutComments())
...
于 2012-11-21T19:35:25.110 回答