Example usage for javax.xml.crypto.dsig XMLSignatureFactory newXMLObject

List of usage examples for javax.xml.crypto.dsig XMLSignatureFactory newXMLObject

Introduction

In this page you can find the example usage for javax.xml.crypto.dsig XMLSignatureFactory newXMLObject.

Prototype

public abstract XMLObject newXMLObject(List<? extends XMLStructure> content, String id, String mimeType,
        String encoding);

Source Link

Document

Creates an XMLObject from the specified parameters.

Usage

From source file:be.fedict.eid.applet.service.signer.ooxml.OOXMLSignatureFacet.java

private void addManifestObject(XMLSignatureFactory signatureFactory, Document document, String signatureId,
        List<Reference> references, List<XMLObject> objects)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    Manifest manifest = constructManifest(signatureFactory, document);
    String objectId = "idPackageObject"; // really has to be this value.
    List<XMLStructure> objectContent = new LinkedList<XMLStructure>();
    objectContent.add(manifest);/*from  w w w .  java  2s .c  om*/

    addSignatureTime(signatureFactory, document, signatureId, objectContent);

    objects.add(signatureFactory.newXMLObject(objectContent, objectId, null, null));

    DigestMethod digestMethod = signatureFactory.newDigestMethod(this.digestAlgo.getXmlAlgoId(), null);
    Reference reference = signatureFactory.newReference("#" + objectId, digestMethod, null,
            "http://www.w3.org/2000/09/xmldsig#Object", null);
    references.add(reference);
}

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

public Signature createSignature(final Noekkelpar noekkelpar, final List<AsicEAttachable> attachedFiles)
        throws XmlValideringException {
    XMLSignatureFactory xmlSignatureFactory = getSignatureFactory();
    SignatureMethod signatureMethod = getSignatureMethod(xmlSignatureFactory);

    // Lag signatur-referanse for alle filer
    List<Reference> references = references(xmlSignatureFactory, attachedFiles);

    // Lag signatur-referanse for XaDES properties
    references.add(xmlSignatureFactory.newReference("#SignedProperties", sha256DigestMethod,
            singletonList(canonicalXmlTransform), signedPropertiesType, null));

    // Generer XAdES-dokument som skal signeres, informasjon om nkkel brukt til signering og informasjon om hva som er signert
    Document document = createXAdESProperties.createPropertiesToSign(attachedFiles, noekkelpar.getSertifikat());

    KeyInfo keyInfo = keyInfo(xmlSignatureFactory, noekkelpar.getCertificateChain());
    SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod,
            references);//  w  ww.  j a  v  a 2  s.c  om

    // Definer signatur over XAdES-dokument
    XMLObject xmlObject = xmlSignatureFactory
            .newXMLObject(singletonList(new DOMStructure(document.getDocumentElement())), null, null, null);
    XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo,
            singletonList(xmlObject), "Signature", null);

    try {
        xmlSignature.sign(new DOMSignContext(noekkelpar.getPrivateKey(), document));
    } catch (MarshalException e) {
        throw new XmlKonfigurasjonException("Klarte ikke  lese ASiC-E XML for signering", e);
    } catch (XMLSignatureException e) {
        throw new XmlKonfigurasjonException("Klarte ikke  signere ASiC-E element.", e);
    }

    // Pakk Signatur inn i XAdES-konvolutt
    wrapSignatureInXADeSEnvelope(document);

    ByteArrayOutputStream outputStream;
    try {
        outputStream = new ByteArrayOutputStream();
        Transformer transformer = transformerFactory.newTransformer();
        schema.newValidator().validate(new DOMSource(document));
        transformer.transform(new DOMSource(document), new StreamResult(outputStream));
    } catch (TransformerException e) {
        throw new KonfigurasjonException("Klarte ikke  serialisere XML", e);
    } catch (SAXException e) {
        throw new XmlValideringException(
                "Kunne ikke validere generert signatures.xml. Sjekk at input er gyldig og at det ikke er ugyldige tegn i filnavn o.l.",
                KLIENT, e);
    } catch (IOException e) {
        throw new RuntimeIOException(e);
    }
    return new Signature(outputStream.toByteArray());
}

From source file:no.digipost.signature.client.asice.signature.CreateSignature.java

public Signature createSignature(final List<ASiCEAttachable> attachedFiles,
        final KeyStoreConfig keyStoreConfig) {
    XMLSignatureFactory xmlSignatureFactory = getSignatureFactory();
    SignatureMethod signatureMethod = getSignatureMethod(xmlSignatureFactory);

    // Create signature references for all files
    List<Reference> references = references(xmlSignatureFactory, attachedFiles);

    // Create signature reference for XAdES properties
    references.add(xmlSignatureFactory.newReference("#SignedProperties", sha256DigestMethod,
            singletonList(canonicalXmlTransform), signedPropertiesType, null));

    // Generate XAdES document to sign, information about the key used for signing and information about what's signed
    Document document = createXAdESProperties.createPropertiesToSign(attachedFiles,
            keyStoreConfig.getCertificate());

    KeyInfo keyInfo = keyInfo(xmlSignatureFactory, keyStoreConfig.getCertificateChain());
    SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod,
            references);/*ww w . j a v  a2  s .c o  m*/

    // Define signature over XAdES document
    XMLObject xmlObject = xmlSignatureFactory
            .newXMLObject(singletonList(new DOMStructure(document.getDocumentElement())), null, null, null);
    XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo,
            singletonList(xmlObject), "Signature", null);

    try {
        xmlSignature.sign(new DOMSignContext(keyStoreConfig.getPrivateKey(), document));
    } catch (MarshalException e) {
        throw new XmlConfigurationException("failed to read ASiC-E XML for signing", e);
    } catch (XMLSignatureException e) {
        throw new XmlConfigurationException("Failed to sign ASiC-E element.", e);
    }

    wrapSignatureInXADeSEnvelope(document);

    ByteArrayOutputStream outputStream;
    try {
        outputStream = new ByteArrayOutputStream();
        Transformer transformer = transformerFactory.newTransformer();
        schema.newValidator().validate(new DOMSource(document));
        transformer.transform(new DOMSource(document), new StreamResult(outputStream));
    } catch (TransformerException e) {
        throw new ConfigurationException("Unable to serialize XML.", e);
    } catch (SAXException e) {
        throw new XmlValidationException(
                "Failed to validate generated signature.xml. Verify that the input is valid and that there are no illegal symbols in file names etc.",
                e);
    } catch (IOException e) {
        throw new RuntimeIOException(e);
    }
    return new Signature(outputStream.toByteArray());
}

From source file:be.fedict.eid.applet.service.signer.odf.OpenOfficeSignatureFacet.java

public void preSign(XMLSignatureFactory signatureFactory, Document document, String signatureId,
        List<X509Certificate> signingCertificateChain, List<Reference> references, List<XMLObject> objects)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    LOG.debug("pre sign");

    Element dateElement = document.createElementNS("", "dc:date");
    dateElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:dc", "http://purl.org/dc/elements/1.1/");
    DateTime dateTime = new DateTime(DateTimeZone.UTC);
    DateTimeFormatter fmt = ISODateTimeFormat.dateTimeNoMillis();
    String now = fmt.print(dateTime);
    now = now.substring(0, now.indexOf("Z"));
    LOG.debug("now: " + now);
    dateElement.setTextContent(now);/*from w w w.  j a va 2 s  .  c  o m*/

    String signaturePropertyId = "sign-prop-" + UUID.randomUUID().toString();
    List<XMLStructure> signaturePropertyContent = new LinkedList<XMLStructure>();
    signaturePropertyContent.add(new DOMStructure(dateElement));
    SignatureProperty signatureProperty = signatureFactory.newSignatureProperty(signaturePropertyContent,
            "#" + signatureId, signaturePropertyId);

    List<XMLStructure> objectContent = new LinkedList<XMLStructure>();
    List<SignatureProperty> signaturePropertiesContent = new LinkedList<SignatureProperty>();
    signaturePropertiesContent.add(signatureProperty);
    SignatureProperties signatureProperties = signatureFactory
            .newSignatureProperties(signaturePropertiesContent, null);
    objectContent.add(signatureProperties);

    objects.add(signatureFactory.newXMLObject(objectContent, null, null, null));

    DigestMethod digestMethod = signatureFactory.newDigestMethod(this.digestAlgo.getXmlAlgoId(), null);
    Reference reference = signatureFactory.newReference("#" + signaturePropertyId, digestMethod);
    references.add(reference);
}

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

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

    final XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());
    DigestMethod digestMethod = fac.newDigestMethod(params.getDigestAlgorithm().getXmlId(), null);

    // Create references
    List<Reference> references = new ArrayList<Reference>();
    addReferences(documentIterator(inside), references, digestMethod, fac);
    // Create repository
    signContext.setURIDereferencer(new NameBasedDocumentRepository(inside, fac));

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

    Map<String, String> xpathNamespaceMap = new HashMap<String, String>();
    xpathNamespaceMap.put("ds", "http://www.w3.org/2000/09/xmldsig#");

    String xadesSignedPropertiesId = "xades-" + computeDeterministicId(params);
    QualifyingPropertiesType qualifyingProperties = createXAdESQualifyingProperties(params,
            xadesSignedPropertiesId, references, inside);
    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);/* ww w .  j a  v  a2s.  c o m*/

    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);

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

    digestReferences(signContext, references);

    return signature;

}

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 w  w w  .j  a  va2  s  .  c om*/

    /* 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;

}

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//  w  w  w.j av a2s .com
        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:be.fedict.eid.tsl.TrustServiceList.java

public void addXadesBes(XMLSignatureFactory signatureFactory, Document document, String signatureId,
        X509Certificate signingCertificate, List<Reference> references, List<XMLObject> objects)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    LOG.debug("preSign");

    // QualifyingProperties
    QualifyingPropertiesType qualifyingProperties = this.xadesObjectFactory.createQualifyingPropertiesType();
    qualifyingProperties.setTarget("#" + signatureId);

    // SignedProperties
    SignedPropertiesType signedProperties = this.xadesObjectFactory.createSignedPropertiesType();
    String signedPropertiesId = signatureId + "-xades";
    signedProperties.setId(signedPropertiesId);
    qualifyingProperties.setSignedProperties(signedProperties);

    // SignedSignatureProperties
    SignedSignaturePropertiesType signedSignatureProperties = this.xadesObjectFactory
            .createSignedSignaturePropertiesType();
    signedProperties.setSignedSignatureProperties(signedSignatureProperties);

    // SigningTime
    GregorianCalendar signingTime = new GregorianCalendar();
    signingTime.setTimeZone(TimeZone.getTimeZone("Z"));
    XMLGregorianCalendar xmlSigningTime = this.datatypeFactory.newXMLGregorianCalendar(signingTime);
    xmlSigningTime.setMillisecond(DatatypeConstants.FIELD_UNDEFINED);
    signedSignatureProperties.setSigningTime(xmlSigningTime);

    // SigningCertificate
    CertIDListType signingCertificates = this.xadesObjectFactory.createCertIDListType();
    CertIDType signingCertificateId = this.xadesObjectFactory.createCertIDType();

    X509IssuerSerialType issuerSerial = this.xmldsigObjectFactory.createX509IssuerSerialType();
    issuerSerial.setX509IssuerName(signingCertificate.getIssuerX500Principal().toString());
    issuerSerial.setX509SerialNumber(signingCertificate.getSerialNumber());
    signingCertificateId.setIssuerSerial(issuerSerial);

    DigestAlgAndValueType certDigest = this.xadesObjectFactory.createDigestAlgAndValueType();
    DigestMethodType jaxbDigestMethod = this.xmldsigObjectFactory.createDigestMethodType();
    jaxbDigestMethod.setAlgorithm(DigestMethod.SHA256);
    certDigest.setDigestMethod(jaxbDigestMethod);
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    byte[] digestValue;
    try {//from  w  ww  . j  a  va2s .  co  m
        digestValue = messageDigest.digest(signingCertificate.getEncoded());
    } catch (CertificateEncodingException e) {
        throw new RuntimeException("certificate encoding error: " + e.getMessage(), e);
    }
    certDigest.setDigestValue(digestValue);
    signingCertificateId.setCertDigest(certDigest);

    signingCertificates.getCert().add(signingCertificateId);
    signedSignatureProperties.setSigningCertificate(signingCertificates);

    // marshall XAdES QualifyingProperties
    Node qualifyingPropertiesNode = marshallQualifyingProperties(document, qualifyingProperties);

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

    // add XAdES ds:Reference
    DigestMethod digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA256, null);
    List<Transform> transforms = new LinkedList<Transform>();
    Transform exclusiveTransform = signatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE,
            (TransformParameterSpec) null);
    transforms.add(exclusiveTransform);
    Reference reference = signatureFactory.newReference("#" + signedPropertiesId, digestMethod, transforms,
            XADES_TYPE, null);
    references.add(reference);
}

From source file:be.fedict.eid.applet.service.signer.ooxml.OOXMLSignatureFacet.java

private void addSignatureInfo(XMLSignatureFactory signatureFactory, Document document, String signatureId,
        List<Reference> references, List<XMLObject> objects)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    List<XMLStructure> objectContent = new LinkedList<XMLStructure>();

    Element signatureInfoElement = document.createElementNS(OFFICE_DIGSIG_NS, "SignatureInfoV1");
    signatureInfoElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", OFFICE_DIGSIG_NS);

    Element setupIDElement = document.createElementNS(OFFICE_DIGSIG_NS, "SetupID");

    signatureInfoElement.appendChild(setupIDElement);

    Element signatureTextElement = document.createElementNS(OFFICE_DIGSIG_NS, "SignatureText");

    signatureInfoElement.appendChild(signatureTextElement);

    Element signatureImageElement = document.createElementNS(OFFICE_DIGSIG_NS, "SignatureImage");

    signatureInfoElement.appendChild(signatureImageElement);

    Element signatureCommentsElement = document.createElementNS(OFFICE_DIGSIG_NS, "SignatureComments");

    signatureInfoElement.appendChild(signatureCommentsElement);

    Element windowsVersionElement = document.createElementNS(OFFICE_DIGSIG_NS, "WindowsVersion");
    windowsVersionElement.setTextContent("6.1");
    signatureInfoElement.appendChild(windowsVersionElement);

    Element officeVersionElement = document.createElementNS(OFFICE_DIGSIG_NS, "OfficeVersion");
    officeVersionElement.setTextContent("15.0");
    signatureInfoElement.appendChild(officeVersionElement);

    Element applicationVersionElement = document.createElementNS(OFFICE_DIGSIG_NS, "ApplicationVersion");
    applicationVersionElement.setTextContent("15.0");
    signatureInfoElement.appendChild(applicationVersionElement);

    Element monitorsElement = document.createElementNS(OFFICE_DIGSIG_NS, "Monitors");
    monitorsElement.setTextContent("1");
    signatureInfoElement.appendChild(monitorsElement);

    Element horizontalResolutionElement = document.createElementNS(OFFICE_DIGSIG_NS, "HorizontalResolution");
    horizontalResolutionElement.setTextContent("1366");
    signatureInfoElement.appendChild(horizontalResolutionElement);

    Element verticalResolutionElement = document.createElementNS(OFFICE_DIGSIG_NS, "VerticalResolution");
    verticalResolutionElement.setTextContent("768");
    signatureInfoElement.appendChild(verticalResolutionElement);

    Element colorDepthElement = document.createElementNS(OFFICE_DIGSIG_NS, "ColorDepth");
    colorDepthElement.setTextContent("32");
    signatureInfoElement.appendChild(colorDepthElement);

    Element signatureProviderIdElement = document.createElementNS(OFFICE_DIGSIG_NS, "SignatureProviderId");
    signatureProviderIdElement.setTextContent("{00000000-0000-0000-0000-000000000000}");
    signatureInfoElement.appendChild(signatureProviderIdElement);

    Element signatureProviderUrlElement = document.createElementNS(OFFICE_DIGSIG_NS, "SignatureProviderUrl");
    signatureInfoElement.appendChild(signatureProviderUrlElement);

    Element signatureProviderDetailsElement = document.createElementNS(OFFICE_DIGSIG_NS,
            "SignatureProviderDetails");
    signatureProviderDetailsElement.setTextContent("9");
    signatureInfoElement.appendChild(signatureProviderDetailsElement);

    Element manifestHashAlgorithmElement = document.createElementNS(OFFICE_DIGSIG_NS, "ManifestHashAlgorithm");
    manifestHashAlgorithmElement.setTextContent("http://www.w3.org/2000/09/xmldsig#sha1");
    signatureInfoElement.appendChild(manifestHashAlgorithmElement);

    Element signatureTypeElement = document.createElementNS(OFFICE_DIGSIG_NS, "SignatureType");
    signatureTypeElement.setTextContent("1");
    signatureInfoElement.appendChild(signatureTypeElement);

    List<XMLStructure> signatureInfoContent = new LinkedList<XMLStructure>();
    signatureInfoContent.add(new DOMStructure(signatureInfoElement));
    SignatureProperty signatureInfoSignatureProperty = signatureFactory
            .newSignatureProperty(signatureInfoContent, "#" + signatureId, "idOfficeV1Details");

    List<SignatureProperty> signaturePropertyContent = new LinkedList<SignatureProperty>();
    signaturePropertyContent.add(signatureInfoSignatureProperty);
    SignatureProperties signatureProperties = signatureFactory.newSignatureProperties(signaturePropertyContent,
            null);/* w ww.j a v a 2 s.c om*/
    objectContent.add(signatureProperties);

    String objectId = "idOfficeObject";
    objects.add(signatureFactory.newXMLObject(objectContent, objectId, null, null));

    DigestMethod digestMethod = signatureFactory.newDigestMethod(this.digestAlgo.getXmlAlgoId(), null);
    Reference reference = signatureFactory.newReference("#" + objectId, digestMethod, null,
            "http://www.w3.org/2000/09/xmldsig#Object", null);
    references.add(reference);
}

From source file:be.fedict.eid.applet.service.signer.facets.XAdESSignatureFacet.java

public void preSign(XMLSignatureFactory signatureFactory, Document document, String signatureId,
        List<X509Certificate> signingCertificateChain, List<Reference> references, List<XMLObject> objects)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    LOG.debug("preSign");

    // QualifyingProperties
    QualifyingPropertiesType qualifyingProperties = this.xadesObjectFactory.createQualifyingPropertiesType();
    qualifyingProperties.setTarget("#" + signatureId);

    // SignedProperties
    SignedPropertiesType signedProperties = this.xadesObjectFactory.createSignedPropertiesType();
    String signedPropertiesId;//from  w  w w  . ja va2 s. c o  m
    if (null != this.idSignedProperties) {
        signedPropertiesId = this.idSignedProperties;
    } else {
        signedPropertiesId = signatureId + "-xades";
    }
    signedProperties.setId(signedPropertiesId);
    qualifyingProperties.setSignedProperties(signedProperties);

    // SignedSignatureProperties
    SignedSignaturePropertiesType signedSignatureProperties = this.xadesObjectFactory
            .createSignedSignaturePropertiesType();
    signedProperties.setSignedSignatureProperties(signedSignatureProperties);

    // SigningTime
    GregorianCalendar signingTime = new GregorianCalendar(TimeZone.getTimeZone("Z"));
    Date currentClockValue = this.clock.getTime();
    signingTime.setTime(currentClockValue);
    XMLGregorianCalendar xmlGregorianCalendar = this.datatypeFactory.newXMLGregorianCalendar(signingTime);
    xmlGregorianCalendar.setMillisecond(DatatypeConstants.FIELD_UNDEFINED);
    signedSignatureProperties.setSigningTime(xmlGregorianCalendar);

    // SigningCertificate
    if (null == signingCertificateChain || signingCertificateChain.isEmpty()) {
        throw new RuntimeException("no signing certificate chain available");
    }
    X509Certificate signingCertificate = signingCertificateChain.get(0);
    CertIDType signingCertificateId = getCertID(signingCertificate, this.xadesObjectFactory,
            this.xmldsigObjectFactory, this.digestAlgorithm, this.issuerNameNoReverseOrder);
    CertIDListType signingCertificates = this.xadesObjectFactory.createCertIDListType();
    signingCertificates.getCert().add(signingCertificateId);
    signedSignatureProperties.setSigningCertificate(signingCertificates);

    // ClaimedRole
    if (null != this.role && false == this.role.isEmpty()) {
        SignerRoleType signerRole = this.xadesObjectFactory.createSignerRoleType();
        signedSignatureProperties.setSignerRole(signerRole);
        ClaimedRolesListType claimedRolesList = this.xadesObjectFactory.createClaimedRolesListType();
        signerRole.setClaimedRoles(claimedRolesList);
        AnyType claimedRole = this.xadesObjectFactory.createAnyType();
        claimedRole.getContent().add(this.role);
        claimedRolesList.getClaimedRole().add(claimedRole);
    }

    // XAdES-EPES
    if (null != this.signaturePolicyService) {
        SignaturePolicyIdentifierType signaturePolicyIdentifier = this.xadesObjectFactory
                .createSignaturePolicyIdentifierType();
        signedSignatureProperties.setSignaturePolicyIdentifier(signaturePolicyIdentifier);

        SignaturePolicyIdType signaturePolicyId = this.xadesObjectFactory.createSignaturePolicyIdType();
        signaturePolicyIdentifier.setSignaturePolicyId(signaturePolicyId);

        ObjectIdentifierType objectIdentifier = this.xadesObjectFactory.createObjectIdentifierType();
        signaturePolicyId.setSigPolicyId(objectIdentifier);
        IdentifierType identifier = this.xadesObjectFactory.createIdentifierType();
        objectIdentifier.setIdentifier(identifier);
        identifier.setValue(this.signaturePolicyService.getSignaturePolicyIdentifier());
        objectIdentifier.setDescription(this.signaturePolicyService.getSignaturePolicyDescription());

        byte[] signaturePolicyDocumentData = this.signaturePolicyService.getSignaturePolicyDocument();
        DigestAlgAndValueType sigPolicyHash = getDigestAlgAndValue(signaturePolicyDocumentData,
                this.xadesObjectFactory, this.xmldsigObjectFactory, this.digestAlgorithm);
        signaturePolicyId.setSigPolicyHash(sigPolicyHash);

        String signaturePolicyDownloadUrl = this.signaturePolicyService.getSignaturePolicyDownloadUrl();
        if (null != signaturePolicyDownloadUrl) {
            SigPolicyQualifiersListType sigPolicyQualifiers = this.xadesObjectFactory
                    .createSigPolicyQualifiersListType();
            signaturePolicyId.setSigPolicyQualifiers(sigPolicyQualifiers);

            AnyType sigPolicyQualifier = this.xadesObjectFactory.createAnyType();
            sigPolicyQualifiers.getSigPolicyQualifier().add(sigPolicyQualifier);

            JAXBElement<String> spUriElement = this.xadesObjectFactory.createSPURI(signaturePolicyDownloadUrl);
            sigPolicyQualifier.getContent().add(spUriElement);
        }
    } else if (this.signaturePolicyImplied) {
        SignaturePolicyIdentifierType signaturePolicyIdentifier = this.xadesObjectFactory
                .createSignaturePolicyIdentifierType();
        signedSignatureProperties.setSignaturePolicyIdentifier(signaturePolicyIdentifier);

        signaturePolicyIdentifier.setSignaturePolicyImplied("");
    }

    // DataObjectFormat
    if (false == this.dataObjectFormatMimeTypes.isEmpty()) {
        SignedDataObjectPropertiesType signedDataObjectProperties = this.xadesObjectFactory
                .createSignedDataObjectPropertiesType();
        signedProperties.setSignedDataObjectProperties(signedDataObjectProperties);

        List<DataObjectFormatType> dataObjectFormats = signedDataObjectProperties.getDataObjectFormat();
        for (Map.Entry<String, String> dataObjectFormatMimeType : this.dataObjectFormatMimeTypes.entrySet()) {
            DataObjectFormatType dataObjectFormat = this.xadesObjectFactory.createDataObjectFormatType();
            dataObjectFormat.setObjectReference("#" + dataObjectFormatMimeType.getKey());
            dataObjectFormat.setMimeType(dataObjectFormatMimeType.getValue());
            dataObjectFormats.add(dataObjectFormat);
        }
    }

    // marshall XAdES QualifyingProperties
    Node qualifyingPropertiesNode = marshallQualifyingProperties(document, this.xadesObjectFactory,
            qualifyingProperties);

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

    // add XAdES ds:Reference
    DigestMethod digestMethod = signatureFactory.newDigestMethod(digestAlgorithm.getXmlAlgoId(), null);
    List<Transform> transforms = new LinkedList<Transform>();
    Transform exclusiveTransform = signatureFactory.newTransform(CanonicalizationMethod.INCLUSIVE,
            (TransformParameterSpec) null);
    transforms.add(exclusiveTransform);
    Reference reference = signatureFactory.newReference("#" + signedPropertiesId, digestMethod, transforms,
            XADES_TYPE, null);
    references.add(reference);
}