Search code examples
javaxmljakarta-eesignjava-security

Add Signature to XML element without "id"


I need sign a XML Document. But, the XML element to sign does not have an id. Is there any way to add the signature by tag name?

something like this:

   `<father>
       <child>element to sign, without "id" </child>
      <I need the signature here></I need the signature here>
    </father>`

I understand that my problem is in this sentence:

Reference ref = fac.newReference("", fac.newDigestMethod(
      DigestMethod.SHA1, null), Collections.singletonList(fac
            .newTransform(Transform.ENVELOPED,
                    (TransformParameterSpec) null)), null, null);

I tried this way:

Reference ref = fac.newReference("#child", fac.newDigestMethod(
      DigestMethod.SHA1, null), Collections.singletonList(fac
            .newTransform(Transform.ENVELOPED,
                    (TransformParameterSpec) null)), null, null);

But this throws an exception because it does not find the element, the first option works but the signature is added to end of xml file:

   `<father>
       <child>element to sign, without "id" </child>
    </father>
    <Signature></Signature>`

Any recommendation?

Thanks in advance!!!


Solution

  • Have you tried anything like child only? The code below will not solve your problem because it will return a empty id, but it can serve as inspiration. Try, for instance, pass el as reference in newReference function.

    elements = doc.getElementsByTagName(tag);  
    Element el = (Element) elements.item(0);  
    String id = el.getAttribute("Id");  
    
    //Reference ref = fac.newReference("".concat(id), fac.newDigestMethod(DigestMethod.SHA1, null), transformList, null, null);  
    Reference ref = fac.newReference("#" + id, fac.newDigestMethod(DigestMethod.SHA1, null), transformList, null, null);