Java Android XML sign (santuario)

48 Views Asked by At

I have simple XML file(String)

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Header><wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" soapenv:mustUnderstand="1">
  </wsse:Security>
</soapenv:Header>
<soapenv:Body xmlns:soapsec="http://schemas.xmlsoap.org/soap/security/2000-12" soapsec:id="Body">
  <z:FooBar xmlns:z="http://example.com"></z:FooBar>
</soapenv:Body>
</soapenv:Envelope>

Java procedure for xml-sign is:

   public static void sign(Document doc,Key signKey, X509Certificate signCert, Element signElement){
        Element e1 =(Element)doc.getElementsByTagName("soapenv:Body").item(0);
        e1.setIdAttribute("soapsec:id", true);
        String elementId = e1.getAttribute("soapsec:id");
        if (elementId == null) {
        }
        String elementRefId = "#" + elementId;
        org.apache.xml.security.Init.init();
        try {
            XMLSignature signature = new XMLSignature(signElement.getOwnerDocument(),
                    elementRefId,   //baseURI
                    XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256,  // signatureMethodURI
                    Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); //  canonicalizationMethodURI
            signature.setId("wsu:Id");
            signElement.appendChild(signature.getElement());         
            Transforms transforms = new Transforms(signElement.getOwnerDocument());
            transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);  //  Canonical CN14
            signature.addDocument(elementRefId, transforms, MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA256);              signature.addKeyInfo(signCert);
            signature.addKeyInfo(signCert.getPublicKey());
            signature.sign(signKey);
        } catch (XMLSecurityException xmse) {
            throw new RuntimeException(xmse);
        } catch (Exception e) {
            throw e;
        }
    }

I call this procedure with signElement parameter <Body...>

signed XML is generated, everything looks fine.....but when I try verify this signature, "Reference 1 wrong digest" error occured. But signature is verified. Digest no.

So bad reference hash?

I tried manualy generate SHA 256 from body element. With next Bas64 encoding.

I tried it from string "<z:FooBar xmlns:z="http://example.com"></z:FooBar>" also from "<soapenv:Body xmlns:soapsec="http://schemas.xmlsoap.org/soap/security/2000-12" soapsec:id="Body"> <z:FooBar xmlns:z="http://example.com"></z:FooBar> </soapenv:Body>" also from canonized (EXC-CN14) canonized strings. But without succed.

What is correct way to make SHA256 digest of XML? Why my santuario code calculate wrong digest?

I tried sign it by santuario xmlsec library, also manualy calculate digest and signature.

0

There are 0 best solutions below