【问题标题】:Apache Santuario signature element locationApache Santuario 签名元素位置
【发布时间】:2013-03-03 22:41:02
【问题描述】:

如何使用 apache santuario 对文档进行签名,以便签名位于标签内而不是 MyXML 标签的末尾?

<MyXML>
    <SignaturePlace></SignaturePlace>
    <DataToSign>BlaBlaBla</DataToSign>
</MyXML>

在标准 JSE dsig 库中有 javax.xml.crypto.dsig.dom.DOMSignContext 类,其构造函数采用 2 个参数 - RSA 私钥和生成的 XMLSignature 父元素的位置。 apache santuario 的实现中是否有类似的东西?

【问题讨论】:

    标签: java xml apache signature


    【解决方案1】:

    是的,您可以使用 Apache Santuario 做到这一点。

    这里是使用上面的示例 XML 执行此操作的示例代码:

    // Assume "document" is the Document you want to sign, and that you have already have the cert and the key
    
    // Construct the signature and add the necessary transforms, etc.
    XMLSignature signature = new XMLSignature(document, null, XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1);
    final Transforms transforms = new Transforms(document);
    transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
    transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
    signature.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);
    
    // Now insert the signature as the last child of the outermost node
    document.getDocumentElement().appendChild(signature.getElement());
    
    // Finally, actually sign the document.
    signature.addKeyInfo(x509Certificate);
    signature.addKeyInfo(x509Certificate.getPublicKey());
    signature.sign(privateKey);
    

    这种情况很简单,因为您希望签名成为最外层节点的最后一个子节点。如果要在第 3 个子节点之前插入签名,首先要获取一个指向要在之前插入签名的节点的 Node,然后使用“insertBefore()”方法。

    final Node thirdChildNode = document.getFirstChild().getNextSibling().getNextSibling();
    document.getDocumentElement().insertBefore(signature.getElement(), thirdChildNode);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-16
      • 2014-05-02
      • 2013-04-04
      • 1970-01-01
      • 2011-05-13
      • 1970-01-01
      相关资源
      最近更新 更多