Vytek / xades4j

Automatically exported from code.google.com/p/xades4j
GNU Lesser General Public License v3.0
0 stars 0 forks source link

Error on signing xml document #35

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
Sucessfully compiled but on execution it produced error.

I expected signed XML , but error produced.

Operating system :Windows 7 pro 32 bit,  
Development IDE: NetBeans 7.0.1, 
JDK : 1.6
Xades4j version : xades4j-1.1.0

Source code
-----------
package xadesevaluator;

import org.w3c.dom.Element;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactoryConfigurationError;
import org.w3c.dom.Node;
import java.io.FileOutputStream;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.Source;
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import java.io.File;
import java.security.KeyStoreException;
import java.security.cert.X509Certificate;
import java.util.List;
import org.apache.xml.security.transforms.Transforms;
import org.apache.xml.security.utils.resolver.ResourceResolver;
import org.xml.sax.SAXException;
import xades4j.XAdES4jException;
import xades4j.properties.AllDataObjsCommitmentTypeProperty;
import xades4j.production.SignedDataObjects;
import xades4j.properties.DataObjectDesc;
import xades4j.production.DataObjectReference;

import xades4j.production.XadesBesSigningProfile;
import xades4j.production.XadesSigner;
import xades4j.production.XadesSignatureResult;
import xades4j.production.XadesSigningProfile;
import xades4j.properties.DataObjectTransform;

import xades4j.providers.KeyingDataProvider;
import xades4j.providers.SigningCertChainException;
import xades4j.providers.impl.FileSystemKeyStoreKeyingDataProvider;
import xades4j.providers.impl.KeyStoreKeyingDataProvider.SigningCertSelector;
import xades4j.verification.UnexpectedJCAException;

public class xadesenvelopedsignaturetest {

    private static final String KEYSTOREPATH = ".";//"target/test-files/xades/";
    private static final String SOURCE_SIGNING_PATH = ".\\Testkullanici1.pfx";//"src/test/resources/xades/exported.pfx";
    private static final String SOURCE_CERT_PATH = ".";//"src/test/resources/xades/";

    public xadesenvelopedsignaturetest() {
        ResourceResolver.register("com.uk.nmi.sw.datavaulttesting.vaulttestingutils.xades.XPointerResourceResolver");
    }

    public static void main(String[] args) throws Exception {
            XadesSigner signer = getSigner("123456", SOURCE_SIGNING_PATH);
            signWithoutIDEnveloped(KEYSTOREPATH + "\\080_Signed.xml", signer);
    }

    public static XadesSigner getSigner(String password, String pfxPath) throws Exception {//SigningException {
        try {
            KeyingDataProvider keyingProvider = getKeyingDataProvider(pfxPath, password);
            XadesSigningProfile p = new XadesBesSigningProfile(keyingProvider);
            return p.newSigner();
        } catch (Exception ex) {
            throw new Exception("Error " + ex);
        }
        /*} catch (KeyStoreException ex) {
        throw new SigningException("Keystore Problem : " + ex);
        } catch (SigningCertChainException ex) {
        throw new SigningException("Signer Cert Chain Problem", ex);
        } catch (UnexpectedJCAException ex) {
        throw new SigningException("JCA Problem getting Signer", ex);
        } catch (XadesProfileResolutionException ex) {
        throw new SigningException("XadesProfileResolutionException problem geting Signer", ex);
        }*/
    }

    private static KeyingDataProvider getKeyingDataProvider(String pfxPath, String password) throws KeyStoreException, SigningCertChainException, UnexpectedJCAException {
        KeyingDataProvider keyingProvider = new FileSystemKeyStoreKeyingDataProvider("pkcs12", pfxPath, new SigningCertSelector() {

            @Override
            public X509Certificate selectCertificate(List<X509Certificate> list) {
                return list.get(0);
            }
        }, new DirectPasswordProvider(password), new DirectPasswordProvider(password), true);
        if (keyingProvider.getSigningCertificateChain().isEmpty()) {
            throw new IllegalArgumentException("Cannot initialize keystore with path " + pfxPath);
        }
        return keyingProvider;
    }

    /**
     * Generate the signature and output a single signed file using the enveloped structure
     * This means that the signature is within the signed XML
     * This method signs the root node, not an ID
     * @param outputPath
     * @param signer
     * @param valid
     * @throws TransformerFactoryConfigurationError
     * @throws XAdES4jException
     * @throws TransformerConfigurationException
     * @throws TransformerException
     * @throws IOException
     * @throws FileNotFoundException
     */
    private static void signWithoutIDEnveloped(String outputPath, XadesSigner signer) throws TransformerFactoryConfigurationError, XAdES4jException, TransformerConfigurationException, TransformerException, IOException, FileNotFoundException {

        // Copy source doc into target document
        Document sourceDoc = getDocument(".\\080.xml");
        sourceDoc.setDocumentURI(null);

        writeXMLToFile(sourceDoc, outputPath);

        sourceDoc = getDocument(outputPath);

        Element signatureParent = (Element) sourceDoc.getDocumentElement();
        Element elementToSign = sourceDoc.getDocumentElement();
        String refUri;
        if (elementToSign.hasAttribute("Id")) {
            refUri = '#' + elementToSign.getAttribute("Id");
        } else {
            if (elementToSign.getParentNode().getNodeType() != Node.DOCUMENT_NODE) {
                throw new IllegalArgumentException("Element without Id must be the document root");
            }
            refUri = "";
        }

        DataObjectDesc dataObjRef = new DataObjectReference(refUri).withTransform(new DataObjectTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE));
        XadesSignatureResult result = signer.sign(new SignedDataObjects(dataObjRef).withCommitmentType(AllDataObjsCommitmentTypeProperty.proofOfOrigin()), signatureParent);

        writeXMLToFile(sourceDoc, outputPath);
    }

    /**
     * Write an XML document to file
     * @param doc The document
     * @param outputPath The path to write the XML file to
     * @throws IOException
     * @throws TransformerConfigurationException
     * @throws TransformerFactoryConfigurationError
     * @throws TransformerException
     * @throws FileNotFoundException 
     */
    private static void writeXMLToFile(Document doc, String outputPath) throws IOException, TransformerConfigurationException, TransformerFactoryConfigurationError, TransformerException, FileNotFoundException {
        // Write the output to a file
        Source source = new DOMSource(doc);

        // Prepare the output file
        File outFile = new File(outputPath);
        outFile.getParentFile().mkdirs();
        outFile.createNewFile();
        FileOutputStream fos = new FileOutputStream(outFile);

        StreamResult result = new StreamResult(fos);

        // Write the DOM document to the file
        Transformer xformer = TransformerFactory.newInstance().newTransformer();
        xformer.transform(source, result);

        fos.close();
    }

    /**
     * Load a Document from an XML file
     * @param path The path to the file
     * @return The document extracted from the file
     */
    private static Document getDocument(String path) {
        try {
            // Load the XML to append the signature to.
            File fXmlFile = new File(path);
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);
            doc.getDocumentElement().normalize();
            return doc;
        } catch (SAXException ex) {
            return null;
        } catch (IOException ex) {
            return null;
        } catch (ParserConfigurationException ex) {
            return null;
        }
    }
}

Error
------
Exception in thread "main" java.lang.NoClassDefFoundError: 
[Lorg/aopalliance/intercept/MethodInterceptor;
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2427)
    at java.lang.Class.getDeclaredMethods(Class.java:1791)
    at com.google.inject.internal.ProviderMethodsModule.getProviderMethods(ProviderMethodsModule.java:78)
    at com.google.inject.internal.ProviderMethodsModule.configure(ProviderMethodsModule.java:70)
    at com.google.inject.spi.Elements$RecordingBinder.install(Elements.java:223)
    at com.google.inject.spi.Elements$RecordingBinder.install(Elements.java:232)
    at com.google.inject.spi.Elements.getElements(Elements.java:101)
    at com.google.inject.spi.Elements.getElements(Elements.java:92)
    at com.google.inject.util.Modules$RealOverriddenModuleBuilder$1.configure(Modules.java:142)
    at com.google.inject.AbstractModule.configure(AbstractModule.java:59)
    at com.google.inject.spi.Elements$RecordingBinder.install(Elements.java:223)
    at com.google.inject.spi.Elements.getElements(Elements.java:101)
    at com.google.inject.InjectorShell$Builder.build(InjectorShell.java:135)
    at com.google.inject.InjectorBuilder.build(InjectorBuilder.java:102)
    at com.google.inject.Guice.createInjector(Guice.java:92)
    at com.google.inject.Guice.createInjector(Guice.java:69)
    at com.google.inject.Guice.createInjector(Guice.java:59)
    at xades4j.utils.XadesProfileCore.getInstance(XadesProfileCore.java:149)
    at xades4j.production.XadesSigningProfile.newSigner(XadesSigningProfile.java:94)
    at xadesevaluator.xadesenvelopedsignaturetest.getSigner(xadesenvelopedsignaturetest.java:68)
    at xadesevaluator.xadesenvelopedsignaturetest.main(xadesenvelopedsignaturetest.java:60)
Caused by: java.lang.ClassNotFoundException: 
org.aopalliance.intercept.MethodInterceptor
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    ... 22 more
Java Result: 1

Original issue reported on code.google.com by cbozla...@gmail.com on 6 Mar 2012 at 11:47

GoogleCodeExporter commented 9 years ago
Do you have the guice and aopalliance jars on the classpath?

Original comment by luis.fgoncalv on 14 Mar 2012 at 6:38

GoogleCodeExporter commented 9 years ago
Any developments on this?
You may also want to set DocumentBuilder to be namespace aware.

Original comment by luis.fgoncalv on 4 Apr 2012 at 5:11

GoogleCodeExporter commented 9 years ago
The code is ok and I was able to run the code until profile creation without 
any problem. Ensure that you have the needed jars available on the project.

Youalso need to set namespace awareness:
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware(true);

Original comment by luis.fgoncalv on 8 Apr 2012 at 11:44

GoogleCodeExporter commented 9 years ago
Thanks for your help.
I will check.

Regards.

Original comment by cbozla...@gmail.com on 9 Apr 2012 at 11:22