javaxmlxsddigital-signaturexml-signature

How to set a Java digital signature to an XML DSIG DTO


I have a requirement to send a signed XML message via REST. The XSD contains the schema https://www.w3.org/TR/2002/REC-xmldsig-core-20020212/xmldsig-core-schema.xsd. I was able to successfully generate the XML document with a signature and write it to a file.

My problem is that the XML signing library (javax.xml.crypto.dsig) generates the signature as interface "XMLSignature". But the DTOs generated from my XSD use the Java classes from xmldsig-core-schema.xsd.

Is there a way for the XML signing library to use the generated Java files from XSD or simply convert the XMLSignature?

This is the generated classes from XSD:

enter image description here


Solution

  • I was able to achieve this requirement by creating a custom unmarshaller.

    Here's the signing code where I create a new XMLSignature object from package javax.xml.crypto.dsig. Use it to sign the document.

    Finally, use the custom unmarshaller to read the document as DTO and eventually get the signature object to be assign to the JAXB generated DTO.

    XMLSignature signature = signatureFactory.newXMLSignature(signedInfo, ki);
    
    // Marshal, generate, and sign the enveloped signature
    signature.sign(dsc);
    
    JAXBElement<?> root = XmlUtils.UNMARSHALLER.unmarshal(getStreamSource(doc), xml.getClass());
    
    xml.setSignature(((Xml) root.getValue()).getSignature());
    

    A more detailed explanation is available in my blog at https://www.czetsuyatech.com/2023/02/java-implementation-of-digital-signature-and-x509certificate.html