2

我一直试图让它工作,但是当我尝试为我的 XML 文档中的特定元素创建数字名称时,我总是遇到异常。源文档是一个 SOAP 信封,程序从文件中解析数据并创建 Document 对象。基本上我要做的是创建一个具有多个部分/引用的数字签名......主要是 SOAP 头的安全节点下的 SOAP 主体和时间戳节点。所以现在我正在尝试签署 SOAP 消息的正文部分。SOAP Body 有一个 wsu:Id 值,我在创建 Reference 对象时使用它。我正在使用 securityNode 参考来插入 Signature 节点,因为无论如何它都应该在该位置。我不认为这是一个问题,但我想我会说出来以防万一。我认为我这样做是正确的,但它' 不工作。我看到其他人发布了同样的问题,但没有给出答案。

我尝试了很多不同的东西,只要我指定用于创建引用对象的 URI,我就会得到异常。奇怪的是,在签署上下文时抛出了异常。我这样做对吗?我该如何纠正?任何帮助是极大的赞赏。

// * ** * ** * ** 例外 ** * ** * ** *

线程“main”中的异常 javax.xml.crypto.dsig.XMLSignatureException: javax.xml.crypto.URIReferenceException: java.lang.NullPointerException at org.jcp.xml.dsig.internal.dom.DOMReference.dereference(Unknown Source) at org.jcp.xml.dsig.internal.dom.DOMReference.digest(Unknown Source) at org.jcp.xml.dsig.internal.dom.DOMXMLSignature.digestReference(Unknown Source) at org.jcp.xml.dsig.internal。 dom.DOMXMLSignature.sign(Unknown Source) at XMLDsigTester.main(XMLDsigTester.java:163) 原因:javax.xml.crypto.URIReferenceException: java.lang.NullPointerException at org.jcp.xml.dsig.internal.dom.DOMURIDereferencer .dereference(Unknown Source) ... 5 更多原因:com.sun.org.apache.xml.internal.security.utils.resolver 中的 java.lang.NullPointerException。implementations.ResolverDirectHTTP.engineCanResolve(Unknown Source) at com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver.canResolve(Unknown Source) at com.sun.org.apache.xml.internal.security。 utils.resolver.ResourceResolver.getInstance(Unknown Source) ... 还有 6 个 javax.xml.crypto.URIReferenceException: java.lang.NullPointerException at org.jcp.xml.dsig.internal.dom.DOMURIDereferencer.dereference(Unknown Source) at org.jcp.xml.dsig.internal.dom.DOMReference.dereference(Unknown Source) at org.jcp.xml.dsig.internal.dom.DOMReference.digest(Unknown Source) at org.jcp.xml.dsig.internal。 dom.DOMXMLSignature.digestReference(Unknown Source) at org.jcp.xml.dsig.internal.dom.DOMXMLSignature.sign(Unknown Source) at XMLDsigTester。main(XMLDsigTester.java:163) 原因:com.sun.org.apache.xml.internal.security.utils.resolver.implementations.ResolverDirectHTTP.engineCanResolve 的 java.lang.NullPointerException com.sun.org .apache.xml.internal.security.utils.resolver.ResourceResolver.canResolve(Unknown Source) at com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver.getInstance(Unknown Source) ... 6更多的getInstance(Unknown Source) ... 6 更多getInstance(Unknown Source) ... 6 更多

  //********************   JAVA CLass  ********************



    import javax.xml.crypto.*;
    import javax.xml.crypto.dsig.*;
    import javax.xml.crypto.dom.*;
    import javax.xml.crypto.dsig.dom.DOMSignContext;
    import javax.xml.crypto.dsig.keyinfo.*;
    import javax.xml.crypto.dsig.spec.TransformParameterSpec;
    import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.OutputStream;
    import java.security.*;
    import java.util.Collections;
    import java.util.Iterator;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import org.w3c.dom.Document;
    import org.w3c.dom.*;

    public class XMLDsigTester
    {

    public static void main(String[] args) throws Exception
    {

    //////////////          DECLARATIONS      //////////////////

    final String ENVELOPE_TAG = "Envelope";
    final String HEADER_TAG = "Header";
    final String SECURITY_TAG = "Security";
    final String BODY_TAG = "Body";
    final String SEPARATOR = ":";

    Node envelopeNode = null;
    Node headerNode = null;
    Node bodyNode = null;

    NodeList envelopeChildren = null;
    NodeList headerChildren = null;
    Node childNode = null;
    Node securityNode = null;

    String providerName = null;
    String sEnvelopeNamespace = null;
    String sFullHeaderTagName = null;
    String sFullBodyTagName = null;
    String sNodeName = null;

    int iEnvelopeChildren;
    int iHeaderChildren;

    //////////////          START OF LOGIC      //////////////////

    providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI");

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Document doc = dbf.newDocumentBuilder().parse(new FileInputStream("myfile.xml"));

    Provider providerObj = (Provider) Class.forName(providerName).newInstance();

    ///  Create references to the Envelope, Header, Body and Security nodes  ///

    envelopeNode = doc.getDocumentElement();
    envelopeChildren = envelopeNode.getChildNodes();
    iEnvelopeChildren = envelopeChildren.getLength();

    sEnvelopeNamespace = envelopeNode.getPrefix();
    if (sEnvelopeNamespace != null && !sEnvelopeNamespace.trim().equals(""))
    {
    sFullHeaderTagName = sEnvelopeNamespace.trim().concat(SEPARATOR).concat(HEADER_TAG);
    sFullBodyTagName = sEnvelopeNamespace.trim().concat(SEPARATOR).concat(BODY_TAG);
    }
    else
    {
    sFullHeaderTagName = HEADER_TAG;
    sFullBodyTagName = BODY_TAG;
    }

    for (int i=0; i < iEnvelopeChildren; i++)
    {
    sNodeName = null;
    childNode = null;

    childNode = envelopeChildren.item(i);
    sNodeName = childNode.getNodeName().trim();

    if (sNodeName.equalsIgnoreCase(sFullHeaderTagName))
    headerNode = childNode;
    else if (sNodeName.equalsIgnoreCase(sFullBodyTagName))
    bodyNode = childNode;
    }

    headerChildren = headerNode.getChildNodes();
    iHeaderChildren = headerChildren.getLength();

    String sLocalNodeName = null;
    for (int i=0; i < iHeaderChildren; i++)
    {
    sLocalNodeName = null;
    sNodeName = null;
    childNode = null;

    childNode = headerChildren.item(i);
    sNodeName = childNode.getNodeName().trim();

    sLocalNodeName = childNode.getLocalName();

    if (sLocalNodeName != null)
    if (sLocalNodeName.trim().equalsIgnoreCase(SECURITY_TAG))
    {
    securityNode = childNode;
    break;
    }
    }

    ///  Main logic for generating XML signature  ///

    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", providerObj);

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(512);
    KeyPair kp = kpg.generateKeyPair();

    KeyInfoFactory kif = fac.getKeyInfoFactory();
    KeyValue kv = kif.newKeyValue(kp.getPublic());

    KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));


    DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), securityNode);
    dsc.putNamespacePrefix("http://www.w3.org/2000/09/xmldsig#", "ds");


    DigestMethod digestMethod = fac.newDigestMethod(DigestMethod.SHA1, null);
    Transform transformObj = fac.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null);

    Reference ref = fac.newReference("part-Body-4F4332715C4C1670E10080000A441E26", digestMethod, Collections.singletonList(transformObj), null, null);

    CanonicalizationMethod canonMethodObj = fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null);
    SignatureMethod signatureMethodObj = fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
    SignedInfo si = fac.newSignedInfo(canonMethodObj, signatureMethodObj, Collections.singletonList(ref));

    XMLSignature signature = fac.newXMLSignature(si, ki);
    signature.sign(dsc);

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer trans = tf.newTransformer();
    trans.transform(new DOMSource(doc), new StreamResult(new FileOutputStream("mySignedFile.xml")));
    }
    } <br>

    //********************   INPUT DATA  ********************

    <soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
       <soap-env:Header>
          <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
             <wsu:Timestamp wsu:Id="ts-4F43326F5C4C1670E10080000A441E26">
                <wsu:Created>2012-09-30T22:09:55Z</wsu:Created>
                <wsu:Expires>2012-09-30T22:14:55Z</wsu:Expires>
             </wsu:Timestamp>
          </wsse:Security>
          <wsa:Action soap-env:mustUnderstand="1" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing"/>
          <wsa:MessageID xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing">uuid:4f43f2ff-38aa-1a90-e100-80000a441e26</wsa:MessageID>
       </soap-env:Header>
       <soap-env:Body wsu:Id="part-Body-4F4332715C4C1670E10080000A441E26" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
           <PurchaseOrder>
             <Customer>
               <Name>Robert Smith</Name>
               <CustomerId>788335</CustomerId>
             </Customer>
             <Item partNum="C763">
               <ProductId>6883-JF3</ProductId>
               <Quantity>3</Quantity>
               <ShipDate>2002-09-03</ShipDate>
               <Name>ThinkPad X20</Name>
             </Item>
           </PurchaseOrder>
       </soap-env:Body>
    </soap-env:Envelope>
4

1 回答 1

4

我希望现在还为时不晚:)。我一直在用您的输入对您的代码进行一些测试。您需要知道的第一件事是您需要使用“#nodeId”指定节点名称,在您的示例中应该是“#part-Body-4F4332715C4C1670E10080000A441E26”(您缺少“#”符号)。下一个问题与“wsu”命名空间中的“Id”有关;如果它只是“Id”而不是“wsu:Id”,您的代码将定位“soap-env:Body”节点,但情况并非如此。如果您可以添加额外的“Id”属性或修改您的示例删除“wsu”命名空间前缀,那么您就完成了。如果您不这样做,那么您需要进行一些修改,添加一个转换,以便您可以选择要签名的节点。你应该替换你的行:

Transform transformObj = fac.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null);

Reference ref = fac.newReference("part-Body-4F4332715C4C1670E10080000A441E26", digestMethod, Collections.singletonList(transformObj), null, null);

和:

List<Transform> transforms = new ArrayList<Transform>(2);
Map<String, String> namespaces = new HashMap<String, String>(1);
namespaces.put("soap-env", "http://schemas.xmlsoap.org/soap/envelope/");
XPathFilterParameterSpec paramsXpath = new XPathFilterParameterSpec("/soap-env:Envelope/soap-env:Body", namespaces);
transforms.add(fac.newTransform(Transform.XPATH, (TransformParameterSpec) paramsXpath));

Transform transformObj = fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null);
transforms.add(transformObj);

Reference ref = fac.newReference("", digestMethod, transforms, null, null);

在这个新代码中,您使用 XPath 将转换添加到从您提供的 xml 输入中选择“soap-env:Body”节点的引用。该节点将被签名并添加到“安全”节点。

于 2012-11-16T14:10:05.763 回答