Search code examples
javaxmlelectronic-signature

Add Reference to Resolver for a detached XAdES signature


I've got to create my own XAdES signature for a project, and everything works fine except the detached signatures. As far as I understand, I have to add a reference to the XML object which will point to a container where the original document is stored. I have tried both with a ResolverAnonymous and a ResolverLocalFileSystem.

XMLSignature sig = new XMLSignature(docToBeSigned, "", sigAlgorithm);
Element element = sig.getElement();

//adding signedinfo, keyinfo and xades properties in between

ResolverLocalFilesystem resolver = new ResolverLocalFilesystem();
//ResolverAnonymous resolver = new ResolverAnonymous(documentToSign);
sig.addResourceResolver(resolver);

sig.addDocument("DetachedObjectReference-1", null,
ESIGUtils.algorithmIDtoURN(hashAlgorithmID), /* it sends the corresponding SHA-1 URL */
SignedDataObject-Reference", null);

Element objeto = docToBeSigned.createElement("ds:Object");
objeto.setAttribute("Id", "Object-1");

element.appendChild(objeto);

sig.sign(privateKey);

return docToBeSigned;

The error I'm getting is as follows:

Original Exception was org.apache.xml.security.signature.ReferenceNotInitializedException: Could not find a resolver for URI DetachedObjectReference-1 and Base 
Original Exception was org.apache.xml.security.signature.ReferenceNotInitializedException: Could not find a resolver for URI DetachedObjectReference-1 and Base 
Original Exception was org.apache.xml.security.utils.resolver.ResourceResolverException: Could not find a resolver for URI DetachedObjectReference-1 and Base

Could anybody say where's my mistake?

Thanks in advance!


Solution

  • Alright, fixed it.

    There is an ID resolver from Apache XML Security which adds the reference I was missing. The next code snippet needs to be added for the signature to work:

    Element objeto = docToBeSigned.createElementNS(
                Constants.SignatureSpecNS, "ds:Object");
        objeto.setAttributeNS(null, Constants._ATT_ID, "DetachedSignatureReference");
        IdResolver.registerElementById(objeto, "DetachedSignatureReference");
    

    instead of the resolvers I was using.