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

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

Introduction

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

Prototype

public abstract Reference newReference(String uri, DigestMethod dm, List<? extends Transform> transforms,
        String type, String id);

Source Link

Document

Creates a Reference with the specified parameters.

Usage

From source file:com.vmware.identity.saml.impl.TokenAuthorityImpl.java

/**
 * Creates a Reference part of Signature section
 *
 * @param transforms//from w ww .j ava 2 s.c om
 * @param id
 * @param digestMethod
 * @return
 * @throws NoSuchAlgorithmException
 * @throws InvalidAlgorithmParameterException
 */
private Reference createReference(List<Transform> transforms, String id, String digestMethod) {
    assert transforms != null;
    assert id != null;
    assert digestMethod != null;

    XMLSignatureFactory factory = XMLSignatureFactory.getInstance();

    javax.xml.crypto.dsig.DigestMethod digestAlgorithm;
    try {
        digestAlgorithm = factory.newDigestMethod(digestMethod, null);
    } catch (Exception e) {
        throw new IllegalStateException("Cannot create digest method object.", e);
    }

    log.debug("Created reference with id: {} and digestMethod: {}", id, digestMethod);
    return factory.newReference("#" + id, digestAlgorithm, transforms, null, null);
}

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. ja v  a  2 s . co  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;

}

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

public void preSign(XMLSignatureFactory signatureFactory, Document document, String signatureId,
        List<X509Certificate> signingCertificateChain, List<Reference> references, List<XMLObject> objects)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    try {//from   ww  w. j a  v a2 s. c o m
        URL odfUrl = this.signatureService.getOpenDocumentURL();
        InputStream odfInputStream = odfUrl.openStream();
        ZipInputStream odfZipInputStream = new ZipInputStream(odfInputStream);
        ZipEntry zipEntry;

        DigestMethod digestMethod = signatureFactory.newDigestMethod(this.digestAlgo.getXmlAlgoId(), null);

        while (null != (zipEntry = odfZipInputStream.getNextEntry())) {
            if (ODFUtil.isToBeSigned(zipEntry)) {
                String name = zipEntry.getName();
                /*
                 * Whitespaces are illegal in URIs
                 * 
                 * Note that OOo 3.0/3.1 seems to have a bug, seems like the
                 * OOo signature verification doesn't convert it back to
                 * whitespace, to be investigated
                 */
                String uri = name.replaceAll(" ", "%20");

                Reference reference;
                if (name.endsWith(".xml") && !isEmpty(odfZipInputStream)) {
                    /* apply transformation on non-empty XML files only */
                    List<Transform> transforms = new LinkedList<Transform>();
                    Transform transform = signatureFactory.newTransform(CanonicalizationMethod.INCLUSIVE,
                            (TransformParameterSpec) null);
                    transforms.add(transform);
                    reference = signatureFactory.newReference(uri, digestMethod, transforms, null, null);
                } else {
                    reference = signatureFactory.newReference(uri, digestMethod);
                }
                references.add(reference);
                LOG.debug("entry: " + name);
            }
        }
    } catch (IOException e) {
        LOG.error("IO error: " + e.getMessage(), e);
    } catch (Exception e) {
        LOG.error("Error: " + e.getMessage(), e);
    }
}

From source file:be.fedict.eid.tsl.TrustServiceList.java

private void xmlSign(PrivateKey privateKey, X509Certificate certificate, String tslId)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException,
        XMLSignatureException {/* ww  w  .j  ava2s . co m*/
    XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM",
            new org.jcp.xml.dsig.internal.dom.XMLDSigRI());
    LOG.debug("xml signature factory: " + signatureFactory.getClass().getName());
    LOG.debug("loader: " + signatureFactory.getClass().getClassLoader());
    XMLSignContext signContext = new DOMSignContext(privateKey, this.tslDocument.getDocumentElement());
    signContext.putNamespacePrefix(XMLSignature.XMLNS, "ds");

    DigestMethod digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA256, null);
    List<Reference> references = new LinkedList<Reference>();
    List<Transform> transforms = new LinkedList<Transform>();
    transforms.add(signatureFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
    Transform exclusiveTransform = signatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE,
            (TransformParameterSpec) null);
    transforms.add(exclusiveTransform);

    Reference reference = signatureFactory.newReference("#" + tslId, digestMethod, transforms, null, null);
    references.add(reference);

    String signatureId = "xmldsig-" + UUID.randomUUID().toString();
    List<XMLObject> objects = new LinkedList<XMLObject>();
    addXadesBes(signatureFactory, this.tslDocument, signatureId, certificate, references, objects);

    SignatureMethod signatureMethod;
    if (isJava6u18OrAbove()) {
        signatureMethod = signatureFactory
                .newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", null);
    } else {
        signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
    }
    CanonicalizationMethod canonicalizationMethod = signatureFactory
            .newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null);
    SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, references);

    List<Object> keyInfoContent = new LinkedList<Object>();

    KeyInfoFactory keyInfoFactory = KeyInfoFactory.getInstance();
    List<Object> x509DataObjects = new LinkedList<Object>();
    x509DataObjects.add(certificate);
    x509DataObjects.add(keyInfoFactory.newX509IssuerSerial(certificate.getIssuerX500Principal().toString(),
            certificate.getSerialNumber()));
    X509Data x509Data = keyInfoFactory.newX509Data(x509DataObjects);
    keyInfoContent.add(x509Data);

    KeyValue keyValue;
    try {
        keyValue = keyInfoFactory.newKeyValue(certificate.getPublicKey());
    } catch (KeyException e) {
        throw new RuntimeException("key exception: " + e.getMessage(), e);
    }
    keyInfoContent.add(keyValue);

    KeyInfo keyInfo = keyInfoFactory.newKeyInfo(keyInfoContent);

    String signatureValueId = signatureId + "-signature-value";
    XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, keyInfo, objects, signatureId,
            signatureValueId);
    xmlSignature.sign(signContext);
}

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   w  w  w.j  a v  a  2s .  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.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);//from w  w  w .  j a  va  2 s. 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: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 {/*  w ww .j  a  v a2  s.  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);//from w w w . j a v a2 s.  c o m
    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;/*  w  w  w .  j  a v a2  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);
}

From source file:org.apache.cxf.ws.security.sts.provider.operation.IssueDelegate.java

private void signXML(Element target, String refId, KeyStoreInfo keyStoreInfo) {

    org.apache.xml.security.Init.init();

    XMLSignatureFactory signFactory = XMLSignatureFactory.getInstance(SIGN_FACTORY_TYPE);
    try {/*  ww w .java2  s .  c  o  m*/
        DigestMethod method = signFactory.newDigestMethod(DigestMethod.SHA1, null);
        Transform transform = signFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null);
        Reference ref = signFactory.newReference('#' + refId, method, Collections.singletonList(transform),
                null, null);

        CanonicalizationMethod canonMethod = signFactory
                .newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null);
        SignatureMethod signMethod = signFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
        SignedInfo si = signFactory.newSignedInfo(canonMethod, signMethod, Collections.singletonList(ref));

        KeyStore.PrivateKeyEntry keyEntry = getKeyEntry(keyStoreInfo);
        if (keyEntry == null) {
            throw new IllegalStateException("Key is not found in keystore. Alias: " + keyStoreInfo.getAlias());
        }

        KeyInfo ki = getKeyInfo(signFactory, keyEntry);

        DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), target);

        XMLSignature signature = signFactory.newXMLSignature(si, ki);

        signature.sign(dsc);

    } catch (Exception e) {
        throw new STSException("Cannot sign xml document: " + e.getMessage(), e);
    }
}