Example usage for javax.xml.crypto.dsig XMLSignature XMLNS

List of usage examples for javax.xml.crypto.dsig XMLSignature XMLNS

Introduction

In this page you can find the example usage for javax.xml.crypto.dsig XMLSignature XMLNS.

Prototype

String XMLNS

To view the source code for javax.xml.crypto.dsig XMLSignature XMLNS.

Click Source Link

Document

The XML Namespace URI of the W3C Recommendation for XML-Signature Syntax and Processing.

Usage

From source file:eu.europa.esig.dss.xades.signature.EnvelopedSignatureBuilder.java

/**
 * Bob --> This method is not used anymore, but it can replace {@code NOT_ANCESTOR_OR_SELF_DS_SIGNATURE} transformation. Performance test should be performed!
 * In case of the enveloped signature the existing signatures are removed.
 *
 * @param domDoc {@code Document} containing the signatures to analyse
 *//*from   w  w w  .  j a va 2 s . c o  m*/
protected void removeExistingSignatures(final Document domDoc) {

    final NodeList signatureNodeList = domDoc.getElementsByTagNameNS(XMLSignature.XMLNS,
            XPathQueryHolder.XMLE_SIGNATURE);
    for (int ii = signatureNodeList.getLength() - 1; ii >= 0; ii--) {
        final Element signatureDOM = (Element) signatureNodeList.item(ii);
        signatureDOM.getParentNode().removeChild(signatureDOM);
    }
}

From source file:com.bcmcgroup.flare.xmldsig.Xmldsig.java

/**
 * Used to verify an enveloped digital signature
 *
 * @param doc a Document object containing the xml with the signature
 * @param keyStorePath a String containing the path to the KeyStore
 * @param keyStorePW a String containing the KeyStore password
 * @param verifyAlias a String containing the alias of the public key used for verification
 * @return True if signature passes verification, False otherwise
 *///from  ww  w . j a  v  a2  s . c o  m
public static boolean verifySignature(Document doc, String keyStorePath, String keyStorePW,
        String verifyAlias) {
    boolean coreValidation = false;
    PublicKey publicKey = ClientUtil.getPublicKeyByAlias(keyStorePath, keyStorePW, verifyAlias);
    if (publicKey == null) {
        logger.error(
                "Public key was null when verifying signature. Ensure keystore configuration values are set properly.");
        return false;
    }
    try {
        NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        if (nl.getLength() == 0) {
            logger.error("No XML Digital Signature was found. The document was discarded.");
            return false;
        }
        Node signatureNode = nl.item(nl.getLength() - 1);
        DOMValidateContext valContext = new DOMValidateContext(publicKey, signatureNode);
        valContext.setURIDereferencer(new MyURIDereferencer(signatureNode.getParentNode()));
        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
        XMLSignature signature = fac.unmarshalXMLSignature(valContext);
        coreValidation = signature.validate(valContext);
        if (!coreValidation) {
            // for testing/debugging when validation fails...
            logger.error("Digital Signature Core Validation failed.");
            boolean signatureValidation = signature.getSignatureValue().validate(valContext);
            logger.debug("Digital Signature Validation: " + signatureValidation);
            @SuppressWarnings("rawtypes")
            Iterator i = signature.getSignedInfo().getReferences().iterator();
            for (int j = 0; i.hasNext(); j++) {
                Reference ref = (Reference) i.next();
                boolean referenceValidation = ref.validate(valContext);
                logger.debug("Digital Signature Reference Validation: " + referenceValidation);
                byte[] calculatedDigestValue = ref.getCalculatedDigestValue();
                byte[] digestValue = ref.getDigestValue();
                String cdvString = new String(Base64.encodeBase64(calculatedDigestValue));
                logger.debug("Digital Signature Calculated Digest Value: " + cdvString);
                String dvString = new String(Base64.encodeBase64(digestValue));
                logger.debug("Digital Signature Digest Value: " + dvString);
            }
        }
    } catch (MarshalException e) {
        logger.error("MarshalException when attempting to verify a digital signature.");
    } catch (XMLSignatureException e) {
        logger.error("XMLSignature Exception when attempting to verify a digital signature.");
    }
    return coreValidation;
}

From source file:eu.europa.ec.markt.dss.validation102853.tsl.TrustedListsCertificateSource.java

/**
 * Load a trusted list for the specified URL
 *
 * @param url//from  w w  w .jav  a  2s  .c o m
 * @param signerCert
 * @return
 * @throws IOException
 */
private TrustStatusList getTrustStatusList(String url, X509Certificate signerCert) {

    InputStream input = null;
    try {

        input = dataLoader.get(url);
        if (input == null) {

            throw new DSSNullReturnedException("The loader returned a null InputStream for: " + url);
        }
        if (url.toLowerCase().endsWith(".zip")) {

            input = getZippedData(input);
        }

        Document doc = DSSXMLUtils.buildDOM(input);

        boolean coreValidity = true;
        if (checkSignature) {

            coreValidity = false;
            if (signerCert != null) {

                final NodeList signatureNodeList = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
                if (signatureNodeList.getLength() == 0) {

                    throw new DSSException("Not ETSI compliant signature. The Xml is not signed.");
                }
                if (signatureNodeList.getLength() > 1) {

                    throw new DSSException("Not ETSI compliant signature. There is more than one signature.");
                }
                final Element signatureEl = (Element) signatureNodeList.item(0);

                final KeySelector keySelector = KeySelector.singletonKeySelector(signerCert.getPublicKey());
                final DOMValidateContext valContext = new DOMValidateContext(keySelector, signatureEl);
                final TSLURIDereferencer tsluriDereferencer = new TSLURIDereferencer(signatureEl);
                valContext.setURIDereferencer(tsluriDereferencer);
                final XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM");
                final XMLSignature signature = factory.unmarshalXMLSignature(valContext);
                coreValidity = signature.validate(valContext);
                LOG.info("The TSL signature validity: " + coreValidity);
            }
        }
        final TrustStatusList tsl = TrustServiceListFactory.newInstance(doc);
        tsl.setWellSigned(coreValidity);
        return tsl;
    } catch (DSSException e) {

        throw e;
    } catch (Exception e) {

        throw new DSSException(e);
    } finally {

        DSSUtils.closeQuietly(input);
    }
}

From source file:no.difi.sdp.client.asice.signature.CreateSignatureTest.java

private boolean verify_signature(final Signature signature2) {
    try {//from w ww .j  ava  2 s . c  o  m
        signature2.getBytes();
        DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
        fac.setNamespaceAware(true);
        DocumentBuilder builder = fac.newDocumentBuilder();
        final Document doc = builder.parse(new ByteArrayInputStream(signature2.getBytes()));
        //System.err.println(new String(signature2.getBytes()));
        NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        DOMValidateContext valContext = new DOMValidateContext(
                noekkelpar.getSertifikat().getX509Certificate().getPublicKey(), nl.item(0));
        valContext.setURIDereferencer(new URIDereferencer() {
            @Override
            public Data dereference(final URIReference uriReference, final XMLCryptoContext context)
                    throws URIReferenceException {
                //System.out.println("$$$$ " + uriReference.getURI());
                for (AsicEAttachable file : files) {
                    if (file.getFileName().equals(uriReference.getURI().toString())) {
                        return new OctetStreamData(new ByteArrayInputStream(file.getBytes()));
                    }
                }
                uriReference.getURI().toString().replace("#", "");
                Node element = doc.getElementsByTagName("SignedProperties").item(0);
                return new DOMSubTreeData(element, false);

            }
        });
        XMLSignatureFactory fact = XMLSignatureFactory.getInstance("DOM");
        XMLSignature signature = fact.unmarshalXMLSignature(valContext);
        boolean coreValidity = signature.validate(valContext);
        if (coreValidity == false) {
            System.err.println("Signature failed core validation");
            boolean sv = signature.getSignatureValue().validate(valContext);
            System.out.println("signature validation status: " + sv);
            if (sv == false) {
                // Check the validation status of each Reference.
                Iterator i = signature.getSignedInfo().getReferences().iterator();
                for (int j = 0; i.hasNext(); j++) {
                    boolean refValid = ((javax.xml.crypto.dsig.Reference) i.next()).validate(valContext);
                    System.out.println("ref[" + j + "] validity status: " + refValid);
                }
            }
        }
        return coreValidity;
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
        return false;
    }
}

From source file:com.alvexcore.repo.SimpleKeySelectorResult.java

private LicenseInfo getLicenseInfo(InputStream lic) {
    Document licenseXML = null;/*from w w w .j a  va2  s  .co m*/
    try {
        DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
        fact.setNamespaceAware(true);
        licenseXML = fact.newDocumentBuilder().parse(lic);
        NodeList nl = licenseXML.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        DOMValidateContext valContext = new DOMValidateContext(new AlvexKeySelector(), nl.item(0));
        XMLSignatureFactory sfac = XMLSignatureFactory.getInstance("DOM");
        XMLSignature sgn = sfac.unmarshalXMLSignature(valContext);
        if (!sgn.validate(valContext))
            return LicenseInfo.INVALID_LICENSE;
    } catch (Exception ex) {
        return LicenseInfo.INVALID_LICENSE;
    }
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    String id = licenseXML.getDocumentElement().getElementsByTagName("id").item(0).getTextContent();
    String product = licenseXML.getDocumentElement().getElementsByTagName("product").item(0).getTextContent();
    String owner = licenseXML.getDocumentElement().getElementsByTagName("owner").item(0).getTextContent();
    String edition = licenseXML.getDocumentElement().getElementsByTagName("edition").item(0).getTextContent();

    // We intentially have separate try/catch blocks. These tags may fail independently
    // and we'd like to prevent failed version tag from stopping dates parsing.
    String version = ANY_VERSION;
    try {
        version = licenseXML.getDocumentElement().getElementsByTagName("version").item(0).getTextContent();
    } catch (Exception e) {
    }

    Date issued = null;
    Date validThru = null;
    try {
        String expiresStr = licenseXML.getDocumentElement().getElementsByTagName("expires").item(0)
                .getTextContent();
        validThru = sdf.parse(expiresStr);
        String issuedStr = licenseXML.getDocumentElement().getElementsByTagName("issued").item(0)
                .getTextContent();
        issued = sdf.parse(issuedStr);
    } catch (Exception e) {
        String expiresStr = licenseXML.getDocumentElement().getElementsByTagName("expires").item(0)
                .getTextContent();
        String issuedStr = licenseXML.getDocumentElement().getElementsByTagName("issued").item(0)
                .getTextContent();
        logger.warn(
                "Can not parse license dates. " + "Issued: " + issuedStr + ". Expires: " + expiresStr + ".");
    }

    int cores = new Integer(
            licenseXML.getDocumentElement().getElementsByTagName("cores").item(0).getTextContent());
    int users = new Integer(
            licenseXML.getDocumentElement().getElementsByTagName("users").item(0).getTextContent());

    return new LicenseInfo(id, owner, product, edition, version, cores, users, issued, validThru, false);
}

From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileT.java

@Override
public Document extendSignatures(Document document, Document originalData, SignatureParameters parameters)
        throws IOException {
    InputStream input = document.openStream();

    if (this.tspSource == null) {
        throw new ConfigurationException(MSG.CONFIGURE_TSP_SERVER);
    }/*from w  w w .j  a va 2  s.  c om*/

    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        org.w3c.dom.Document doc = db.parse(input);

        NodeList signatureNodeList = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        if (signatureNodeList.getLength() == 0) {
            throw new RuntimeException(
                    "Impossible to perform the extension of the signature, the document is not signed.");
        }
        for (int i = 0; i < signatureNodeList.getLength(); i++) {
            Element signatureEl = (Element) signatureNodeList.item(i);
            extendSignatureTag(signatureEl, originalData, parameters.getSignatureFormat());
        }

        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        LSOutput output = impl.createLSOutput();
        output.setByteStream(buffer);
        writer.write(doc, output);

        return new InMemoryDocument(buffer.toByteArray());

    } catch (ParserConfigurationException ex) {
        throw new RuntimeException(ex);
    } catch (SAXException e) {
        throw new IOException("Cannot parse document", e);
    } catch (ClassCastException e) {
        throw new IOException("Cannot save document", e);
    } catch (ClassNotFoundException e) {
        throw new IOException("Cannot save document", e);
    } catch (InstantiationException e) {
        throw new IOException("Cannot save document", e);
    } catch (IllegalAccessException e) {
        throw new IOException("Cannot save document", e);
    } finally {
        if (input != null) {
            input.close();
        }
    }

}

From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileBES.java

private DOMXMLSignature createEnveloped(SignatureParameters params, DOMSignContext signContext,
        org.w3c.dom.Document doc, String signatureId, String signatureValueId) throws NoSuchAlgorithmException,
        InvalidAlgorithmParameterException, JAXBException, MarshalException, XMLSignatureException {

    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());

    signContext.setURIDereferencer(new URIDereferencer() {

        @Override/*from  ww  w . jav  a  2  s.c  o m*/
        public Data dereference(URIReference uriReference, XMLCryptoContext context)
                throws URIReferenceException {
            final XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());
            Data data = fac.getURIDereferencer().dereference(uriReference, context);
            return data;
        }
    });

    Map<String, String> xpathNamespaceMap = new HashMap<String, String>();
    xpathNamespaceMap.put("ds", XMLSignature.XMLNS);

    List<Reference> references = new ArrayList<Reference>();

    /* The first reference concern the whole document */
    List<Transform> transforms = new ArrayList<Transform>();
    transforms.add(fac.newTransform(CanonicalizationMethod.ENVELOPED, (TransformParameterSpec) null));

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    org.w3c.dom.Document empty;
    try {
        empty = dbf.newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException e1) {
        throw new RuntimeException(e1);
    }
    Element xpathEl = empty.createElementNS(XMLSignature.XMLNS, "XPath");
    xpathEl.setTextContent("");
    empty.adoptNode(xpathEl);
    XPathFilterParameterSpec specs = new XPathFilterParameterSpec("not(ancestor-or-self::ds:Signature)");
    DOMTransform t = (DOMTransform) fac.newTransform("http://www.w3.org/TR/1999/REC-xpath-19991116", specs);

    transforms.add(t);
    DigestMethod digestMethod = fac.newDigestMethod(params.getDigestAlgorithm().getXmlId(), null);
    Reference reference = fac.newReference("", digestMethod, transforms, null, "xml_ref_id");
    references.add(reference);

    List<XMLObject> objects = new ArrayList<XMLObject>();

    String xadesSignedPropertiesId = "xades-" + computeDeterministicId(params);
    QualifyingPropertiesType qualifyingProperties = createXAdESQualifyingProperties(params,
            xadesSignedPropertiesId, reference, MimeType.XML);
    qualifyingProperties.setTarget("#" + signatureId);

    Node marshallNode = doc.createElement("marshall-node");
    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.marshal(xades13ObjectFactory.createQualifyingProperties(qualifyingProperties), marshallNode);
    Element qualifier = (Element) marshallNode.getFirstChild();

    // add XAdES ds:Object
    List<XMLStructure> xadesObjectContent = new LinkedList<XMLStructure>();
    xadesObjectContent.add(new DOMStructure(marshallNode.getFirstChild()));
    XMLObject xadesObject = fac.newXMLObject(xadesObjectContent, null, null, null);
    objects.add(xadesObject);

    Reference xadesreference = fac.newReference("#" + xadesSignedPropertiesId, digestMethod,
            Collections.singletonList(
                    fac.newTransform(CanonicalizationMethod.INCLUSIVE, (TransformParameterSpec) null)),
            XADES_TYPE, null);
    references.add(xadesreference);

    /* Signed Info */
    SignatureMethod sm = fac.newSignatureMethod(
            params.getSignatureAlgorithm().getXMLSignatureAlgorithm(params.getDigestAlgorithm()), null);

    CanonicalizationMethod canonicalizationMethod = fac
            .newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null);
    SignedInfo signedInfo = fac.newSignedInfo(canonicalizationMethod, sm, references);

    /* Creation of signature */
    KeyInfoFactory keyFactory = KeyInfoFactory.getInstance("DOM", new XMLDSigRI());

    List<Object> infos = new ArrayList<Object>();
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(params.getSigningCertificate());
    if (params.getCertificateChain() != null) {
        for (X509Certificate c : params.getCertificateChain()) {
            if (!c.getSubjectX500Principal().equals(params.getSigningCertificate().getSubjectX500Principal())) {
                certs.add(c);
            }
        }
    }
    infos.add(keyFactory.newX509Data(certs));
    KeyInfo keyInfo = keyFactory.newKeyInfo(infos);

    DOMXMLSignature signature = (DOMXMLSignature) fac.newXMLSignature(signedInfo, keyInfo, objects, signatureId,
            signatureValueId);

    /* Marshall the signature to permit the digest. Need to be done before digesting the references. */
    signature.marshal(doc.getDocumentElement(), "ds", signContext);

    signContext.setIdAttributeNS((Element) qualifier.getFirstChild(), null, "Id");

    digestReferences(signContext, references);

    return signature;

}

From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileT.java

@Override
public Document extendSignature(Object signatureId, Document document, Document originalData,
        SignatureParameters parameters) throws IOException {
    InputStream input = document.openStream();

    if (this.tspSource == null) {
        throw new ConfigurationException(MSG.CONFIGURE_TSP_SERVER);
    }/* w w  w .ja  v  a  2  s .  c  om*/

    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        org.w3c.dom.Document doc = db.parse(input);

        NodeList signatureNodeList = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        if (signatureNodeList.getLength() == 0) {
            throw new RuntimeException(
                    "Impossible to perform the extension of the signature, the document is not signed.");
        }
        for (int i = 0; i < signatureNodeList.getLength(); i++) {
            Element signatureEl = (Element) signatureNodeList.item(i);
            String sid = signatureEl.getAttribute("Id");
            if (signatureId.equals(sid)) {
                extendSignatureTag(signatureEl, originalData, parameters.getSignatureFormat());
            }
        }

        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        LSOutput output = impl.createLSOutput();
        output.setByteStream(buffer);
        writer.write(doc, output);

        return new InMemoryDocument(buffer.toByteArray());

    } catch (ParserConfigurationException ex) {
        throw new RuntimeException(ex);
    } catch (SAXException e) {
        throw new IOException("Cannot parse document", e);
    } catch (ClassCastException e) {
        throw new IOException("Cannot save document", e);
    } catch (ClassNotFoundException e) {
        throw new IOException("Cannot save document", e);
    } catch (InstantiationException e) {
        throw new IOException("Cannot save document", e);
    } catch (IllegalAccessException e) {
        throw new IOException("Cannot save document", e);
    } finally {
        if (input != null) {
            input.close();
        }
    }

}

From source file:eu.europa.esig.dss.asic.signature.ASiCService.java

private void buildAsicManifest(final ASiCSignatureParameters underlyingParameters,
        final DSSDocument detachedDocument, final OutputStream outputStream) {

    ASiCParameters asicParameters = underlyingParameters.aSiC();

    final Document documentDom = DSSXMLUtils.buildDOM();
    final Element asicManifestDom = documentDom.createElementNS(ASiCNamespaces.ASiC, "asic:ASiCManifest");
    documentDom.appendChild(asicManifestDom);

    final Element sigReferenceDom = DSSXMLUtils.addElement(documentDom, asicManifestDom, ASiCNamespaces.ASiC,
            "asic:SigReference");
    final String signatureName = getSignatureFileName(asicParameters);
    sigReferenceDom.setAttribute("URI", signatureName);
    sigReferenceDom.setAttribute("MimeType", MimeType.PKCS7.getMimeTypeString()); // only CAdES form

    DSSDocument currentDetachedDocument = detachedDocument;
    do {//from www.j  a  v a 2 s.c  o m

        final String detachedDocumentName = currentDetachedDocument.getName();
        final Element dataObjectReferenceDom = DSSXMLUtils.addElement(documentDom, sigReferenceDom,
                ASiCNamespaces.ASiC, "asic:DataObjectReference");
        dataObjectReferenceDom.setAttribute("URI", detachedDocumentName);

        final Element digestMethodDom = DSSXMLUtils.addElement(documentDom, dataObjectReferenceDom,
                XMLSignature.XMLNS, "DigestMethod");
        final DigestAlgorithm digestAlgorithm = underlyingParameters.getDigestAlgorithm();
        digestMethodDom.setAttribute("Algorithm", digestAlgorithm.getXmlId());

        final Element digestValueDom = DSSXMLUtils.addElement(documentDom, dataObjectReferenceDom,
                XMLSignature.XMLNS, "DigestValue");
        final byte[] digest = DSSUtils.digest(digestAlgorithm, currentDetachedDocument.getBytes());
        final String base64Encoded = Base64.encodeBase64String(digest);
        final Text textNode = documentDom.createTextNode(base64Encoded);
        digestValueDom.appendChild(textNode);

        currentDetachedDocument = currentDetachedDocument.getNextDocument();
    } while (currentDetachedDocument != null);

    storeXmlDom(outputStream, documentDom);
}

From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileBES.java

private DOMXMLSignature createEnveloping(SignatureParameters params, DOMSignContext signContext,
        org.w3c.dom.Document doc, String signatureId, String signatureValueId, Document inside)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, JAXBException, MarshalException,
        XMLSignatureException, ParserConfigurationException, IOException {

    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());

    DigestMethod digestMethod = fac.newDigestMethod(params.getDigestAlgorithm().getXmlId(), null);

    List<XMLObject> objects = new ArrayList<XMLObject>();
    List<Reference> references = new ArrayList<Reference>();

    byte[] b64data = Base64.encode(IOUtils.toByteArray(inside.openStream()));

    List<Transform> transforms = new ArrayList<Transform>();
    Map<String, String> xpathNamespaceMap = new HashMap<String, String>();
    xpathNamespaceMap.put("ds", "http://www.w3.org/2000/09/xmldsig#");
    Transform exclusiveTransform = fac.newTransform(CanonicalizationMethod.BASE64,
            (TransformParameterSpec) null);
    transforms.add(exclusiveTransform);/*from   ww  w .j a  va  2s . c o m*/

    /* The first reference concern the whole document */
    Reference reference = fac.newReference("#signed-data-" + computeDeterministicId(params), digestMethod,
            transforms, null, "signed-data-ref");
    references.add(reference);

    String xadesSignedPropertiesId = "xades-" + computeDeterministicId(params);
    QualifyingPropertiesType qualifyingProperties = createXAdESQualifyingProperties(params,
            xadesSignedPropertiesId, reference, MimeType.PLAIN);
    qualifyingProperties.setTarget("#" + signatureId);

    Node marshallNode = doc.createElement("marshall-node");

    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.marshal(xades13ObjectFactory.createQualifyingProperties(qualifyingProperties), marshallNode);

    Element qualifier = (Element) marshallNode.getFirstChild();

    // add XAdES ds:Object
    List<XMLStructure> xadesObjectContent = new LinkedList<XMLStructure>();
    xadesObjectContent.add(new DOMStructure(marshallNode.getFirstChild()));
    XMLObject xadesObject = fac.newXMLObject(xadesObjectContent, null, null, null);
    objects.add(xadesObject);

    List<Transform> xadesTranforms = new ArrayList<Transform>();
    Transform exclusiveTransform2 = fac.newTransform(CanonicalizationMethod.INCLUSIVE,
            (TransformParameterSpec) null);
    xadesTranforms.add(exclusiveTransform2);
    Reference xadesreference = fac.newReference("#" + xadesSignedPropertiesId, digestMethod, xadesTranforms,
            XADES_TYPE, null);
    references.add(xadesreference);

    /* Signed Info */
    SignatureMethod sm = fac.newSignatureMethod(
            params.getSignatureAlgorithm().getXMLSignatureAlgorithm(params.getDigestAlgorithm()), null);

    CanonicalizationMethod canonicalizationMethod = fac
            .newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null);
    SignedInfo signedInfo = fac.newSignedInfo(canonicalizationMethod, sm, references);

    /* Creation of signature */
    KeyInfoFactory keyFactory = KeyInfoFactory.getInstance("DOM", new XMLDSigRI());

    List<Object> infos = new ArrayList<Object>();
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(params.getSigningCertificate());
    if (params.getCertificateChain() != null) {
        for (X509Certificate c : params.getCertificateChain()) {
            if (!c.getSubjectX500Principal().equals(params.getSigningCertificate().getSubjectX500Principal())) {
                certs.add(c);
            }
        }
    }
    infos.add(keyFactory.newX509Data(certs));
    KeyInfo keyInfo = keyFactory.newKeyInfo(infos);

    DOMXMLSignature signature = (DOMXMLSignature) fac.newXMLSignature(signedInfo, keyInfo, objects, signatureId,
            signatureValueId);

    /* Marshall the signature to permit the digest. Need to be done before digesting the references. */
    doc.removeChild(doc.getDocumentElement());
    signature.marshal(doc, "ds", signContext);

    Element dsObject = doc.createElementNS(XMLSignature.XMLNS, "Object");
    dsObject.setAttribute("Id", "signed-data-" + computeDeterministicId(params));
    dsObject.setTextContent(new String(b64data));
    doc.getDocumentElement().appendChild(dsObject);

    signContext.setIdAttributeNS((Element) qualifier.getFirstChild(), null, "Id");
    signContext.setIdAttributeNS(dsObject, null, "Id");

    digestReferences(signContext, references);

    return signature;

}