luisgoncalves / xades4j

A Java library for XAdES signature services
GNU Lesser General Public License v3.0
111 stars 66 forks source link

signature invalid #264

Closed pragdev closed 2 years ago

pragdev commented 2 years ago

Hello, I'm trying to learn more about this framework and the standard. I have tried to sign a document but I cannot get it right. The validation on always fails on the digest values and I'm not sure why. I have to use this website to validate it https://tools.chilkat.io/xmlDsigVerify.cshtml

this is the code.

` System.setProperty("org.apache.xml.security.ignoreLineBreaks", "true") def doc = DocumentBuilderFactory .newInstance() .newDocumentBuilder() .parse(new ByteArrayInputStream(invoice.bytes)) def elem = doc.getDocumentElement() DOMHelper.useIdAsXmlId(elem)

    def keyStoreFile = new File(resourceLoader.getResource('keystore_server.p12').get().toURI())

    def keyProvider = FileSystemKeyStoreKeyingDataProvider
            .builder("pkcs12", keyStoreFile.absolutePath, single())
            .storePassword(new PassStoreProvider())
            .entryPassword(new PassProvider())
            .build()

    BasicSignatureOptions config = new BasicSignatureOptions()
    config.includePublicKey(true)
    config.includeSigningCertificate(SigningCertificateMode.SIGNING_CERTIFICATE)
    config.signKeyInfo(true)

    XadesSigner signer = new XadesBesSigningProfile(keyProvider)
            .withBasicSignatureOptions(config)
            .newSigner()

    // Define the signed object
    DataObjectDesc obj = new DataObjectReference("")
            .withTransform(XPath2FilterTransform.XPath2Filter.subtract('/descendant::ds:Signature'))
            .withTransform(new EnvelopedSignatureTransform())
            .withTransform(new ExclusiveCanonicalXMLWithoutComments())
            .withDataObjectFormat(new DataObjectFormatProperty("application/octet-stream"))

    signer.sign new SignedDataObjects(obj), doc.getDocumentElement()

    Transformer transformer = TransformerFactory.newInstance().newTransformer()
    DOMSource source = new DOMSource(doc)

    def writer = new StringWriter()
    StreamResult result = new StreamResult(writer)
    transformer.transform(source, result)

    return writer.toString()`
luisgoncalves commented 2 years ago

Hi. I haven't read the code in detail, but at first glance: I think you need to set the DocumentBuilderFactory to be namespace aware.

pragdev commented 2 years ago

That worked, thanks!