ResourceResolverException:无法解析具有ID主体的元素

时间:2019-12-05 23:14:05

标签: java digital-signature x509certificate

我正在尝试签署xml文档的一部分,但出现错误“ javax.xml.crypto.URIReferenceException:com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException: ID主体”。我不明白该错误,因为肥皂主体具有名为“ Body”的id属性。为什么找不到它?

以下是创建初始xml文档的代码:

//create Document, create envelope and append it to document, create header
//and append it to envelope, create body and append it to envelope
private Document startDocument() {       
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    Document doc = null;
    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        doc = builder.newDocument();
        System.out.println("" + doc.getXmlVersion());
        //Envelope
        Element envelope = doc.createElementNS("http://schemas.xmlsoap.org/soap/envelope/", "B:Envelope");
        envelope.setAttribute("xmlns:B", "http://schemas.xmlsoap.org/soap/envelope/");
        envelope.setAttribute("xmlns:SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12");
        envelope.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        doc.appendChild(envelope);

        //Header
        Element header = doc.createElementNS("http://schemas.xmlsoap.org/soap/envelope/", "SOAP:Header");
        header.setAttribute("xmlns:SOAP", "http://schemas.xmlsoap.org/soap/envelope/");
        header.setAttribute("xmlns:SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12");
        envelope.appendChild(header);   

        //Body
        Element body = doc.createElementNS("http://schemas.xmlsoap.org/soap/envelope/", "SOAP:Body");
        body.setAttribute("xmlns:SOAP", "http://schemas.xmlsoap.org/soap/envelope/");
        body.setAttribute("ID", "Body");
        envelope.appendChild(body);

        //Save document nodes
        envelopeNode = envelope;
        headerNode   = header;
        bodyNode     = body;

    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return doc;
}

此代码向标头节点添加一个“ SOAP-SEC:Signature”节点:

    private void makeHeader() {
    //$document = $this->document;
    Element header = headerNode;

    // SOAP-SEC:Security
    Element security = document.createElementNS("http://schemas.xmlsoap.org/soap/security/2000-12", "SOAP-SEC:Signature");
    security.setAttribute("SOAP:mustUnderstand", "1");

    header.appendChild(security);

    // Add Signature Later in sign()
    this.securityNode = security;
}

然后,此代码尝试对文档的正文部分进行签名,并将签名添加到SOAP-SEC:Signature节点。

    private void buildSignatureBlock5(String privateKeyPath, String publicKeyPath) {
    // Create a DOM XMLSignatureFactory that will be used to generate the enveloped signature.
    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");

    //Create a Reference to the enveloped document (in this case, you are signing the Body 
    //section of the document), and also specify the SHA1 digest algorithm and the ENVELOPED Transform.
    Reference ref = null;
    try {
        ref = fac.newReference
         ("#Body", fac.newDigestMethod(DigestMethod.SHA1, null),
          Collections.singletonList
           (fac.newTransform
            (Transform.ENVELOPED, (TransformParameterSpec) null)),
             null, null);
    } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // Create the SignedInfo.
    SignedInfo si = null;
    try {
        si = fac.newSignedInfo
         (fac.newCanonicalizationMethod
          (CanonicalizationMethod.INCLUSIVE,
           (C14NMethodParameterSpec) null),
            fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null),
             Collections.singletonList(ref));
    } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }       

    // Load the KeyStore and get the signing key and certificate.
    KeyStore ks = null;
    try {
        ks = KeyStore.getInstance("JKS");
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        ks.load(new FileInputStream(storage_path +"/keys/myproject.jks"), "changeit".toCharArray());
    } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    KeyStore.PrivateKeyEntry keyEntry = null;
    try {
        keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry
            ("1", new KeyStore.PasswordProtection("changeit".toCharArray()));
    } catch (NoSuchAlgorithmException | UnrecoverableEntryException | KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    X509Certificate cert = (X509Certificate) keyEntry.getCertificate();

    // Create the KeyInfo containing the X509Data.
    KeyInfoFactory kif = fac.getKeyInfoFactory();
    List x509Content = new ArrayList();
    String issuerName = cert.getIssuerX500Principal().getName();
    BigInteger serialNumber = cert.getSerialNumber();
    X509IssuerSerial issuer = kif.newX509IssuerSerial(issuerName, serialNumber);
    x509Content.add(issuer);
    x509Content.add(cert);
    X509Data xd = kif.newX509Data(x509Content);
    KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));    

    // Create a DOMSignContext and specify the RSA PrivateKey and
    // location of the resulting XMLSignature's parent element.
    Element envHeaderSig = (Element) document.getElementsByTagName("SOAP-SEC:Signature").item(0);   
    DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), envHeaderSig);

    // Create the XMLSignature, but don't sign it yet.
    XMLSignature signature = fac.newXMLSignature(si, ki);

    // Marshal, generate, and sign the enveloped signature.
    try {
        signature.sign(dsc);  //error occurs here
    } catch (MarshalException | XMLSignatureException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

它失败,并在signature.sign行出现主题错误。我机智!有什么建议吗?

1 个答案:

答案 0 :(得分:0)

我在这里找到了解决方法

  

XML dig sig error after upgrade to java7u25

现在我的身体创建部分如下:

        //Body
        Element body = doc.createElementNS("http://schemas.xmlsoap.org/soap/envelope/", "SOAP:Body");
        body.setAttribute("xmlns:SOAP", "http://schemas.xmlsoap.org/soap/envelope/");
        body.setAttribute("Id", "Body");
        //due to bug in java, need to do the following 2 lines to prevent "Cannot resolve element with ID Body" during signature.sign
        Attr idAttr = body.getAttributeNode("Id");
        body.setIdAttributeNode(idAttr,true);
        envelope.appendChild(body);

我剩下的一个问题是,signature.sign方法在每个证书和签名行的末尾插入空格。这是显示不需要的空白的签名示例:

<SignatureValue>QcjPfiZcmqE8aMNH5AKVk+oFBYQ4LynV3a5YlJIxuf0y22QQ0NA2BTkRriI85dd/6Qcezf5xFguJ&#13;
V+Mlk44c0uZD7TE+NlsFz3q1vtHHPi/9ygc2kJgQeSzxiCR2AHCONN3UN89RjidIqnN1qtKrBhc+&#13;
GNeEGhjqgV7DHvzK7tHVkC6c1EevsOV5bH2Gu0X5JsGwOtSHWe6eyOXue0TW7XWrqOLmOusWYhRR&#13;
ONJFoa49LQ4WV/RP498rp2TJ0bNE36PMWD6sMh52ERTj6NhngIl2cGjbbwzYteDN/ujo5bHmosmC&#13;
dVKBmgaw2YAICJy4BROyK7AmZI5BxKoZ6CY1Tw==</SignatureValue>

我已经研究了此问题的解决方案,但到目前为止,我尝试过的任何方法都没有奏效。如果您知道其中一个,请发表评论。