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:be.fedict.eid.tsl.TrustServiceList.java

private Node getSignatureNode() {
    Element nsElement = this.tslDocument.createElement("ns");
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", XMLSignature.XMLNS);
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tsl", "http://uri.etsi.org/02231/v2#");

    Node signatureNode;/*ww  w  . j a v  a2s .  c  om*/
    try {
        signatureNode = XPathAPI.selectSingleNode(this.tslDocument, "tsl:TrustServiceStatusList/ds:Signature",
                nsElement);
    } catch (TransformerException e) {
        throw new RuntimeException("XPath error: " + e.getMessage(), e);
    }
    return signatureNode;
}

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

private void xmlSign(PrivateKey privateKey, X509Certificate certificate, String tslId)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException,
        XMLSignatureException {// w w w.  ja va 2s.com
    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.validation.xades.XAdESSignature.java

@Override
public byte[] getArchiveTimestampData(int index, Document originalData) throws IOException {

    try {/*from ww w.j  a v  a  2 s  . co  m*/
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();

        XMLStructure s = new DOMStructure(signatureElement);
        XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());
        DOMXMLSignature signature = (DOMXMLSignature) factory.unmarshalXMLSignature(s);

        DOMSignContext signContext = new DOMSignContext(new SpecialPrivateKey(), signatureElement);
        signContext.putNamespacePrefix(XMLSignature.XMLNS, "ds");
        signContext.setProperty("javax.xml.crypto.dsig.cacheReference", true);
        signContext.setURIDereferencer(new OneExternalFileURIDereferencer("detached-file", originalData));

        // TODO naramsda: check ! Don't let met publish that without further test !!
        // DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        // dbf.setNamespaceAware(true);
        // org.w3c.dom.Document xmlDoc = dbf.newDocumentBuilder().newDocument();
        // signature.marshal(xmlDoc.createElement("test"), "ds", signContext);

        for (Object o : signature.getSignedInfo().getReferences()) {
            DOMReference r = (DOMReference) o;
            InputStream data = r.getDigestInputStream();
            if (data != null) {
                IOUtils.copy(data, buffer);
            }
        }

        List<Node> timeStampNodesXadesA = new LinkedList<Node>();

        Element signedInfo = XMLUtils.getElement(signatureElement, "./ds:SignedInfo");
        timeStampNodesXadesA.add(signedInfo);

        Element signatureValue = XMLUtils.getElement(signatureElement, "./ds:SignatureValue");
        timeStampNodesXadesA.add(signatureValue);

        Element keyInfo = XMLUtils.getElement(signatureElement, "./ds:KeyInfo");
        timeStampNodesXadesA.add(keyInfo);

        Element unsignedSignaturePropertiesNode = getUnsignedSignatureProperties(signatureElement);

        NodeList unsignedProperties = unsignedSignaturePropertiesNode.getChildNodes();
        int count = 0;
        for (int i = 0; i < unsignedProperties.getLength(); i++) {
            if (unsignedProperties.item(i).getNodeType() == Node.ELEMENT_NODE) {
                Element unsignedProperty = (Element) unsignedProperties.item(i);
                if ("ArchiveTimeStamp".equals(unsignedProperty.getLocalName())) {
                    if (count == index) {
                        LOG.info("We only need data up to ArchiveTimeStamp index " + index);
                        break;
                    }
                    count++;
                }
                timeStampNodesXadesA.add(unsignedProperty);
            }
        }

        buffer.write(getC14nValue(timeStampNodesXadesA));

        return buffer.toByteArray();
        //        } catch (ParserConfigurationException e) {
        //            throw new IOException("Error when computing the archive data", e);
    } catch (MarshalException e) {
        throw new IOException("Error when computing the archive data", e);
    } catch (XPathExpressionException e) {
        throw new EncodingException(MSG.ARCHIVE_TIMESTAMP_DATA_ENCODING);
    }
}

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

protected InputStream getToBeSignedStream(Document document, SignatureParameters parameters) {

    try {//from  w  ww . j  a  v  a  2s  .c om

        /* Read the document */
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        org.w3c.dom.Document doc = null;
        if (parameters.getSignaturePackaging() == SignaturePackaging.ENVELOPED) {
            doc = db.parse(document.openStream());
        } else {
            doc = db.newDocument();
            doc.appendChild(doc.createElement("empty"));
        }

        /* Interceptor */
        SpecialPrivateKey dummyPrivateKey = new SpecialPrivateKey();

        /* Context */
        DOMSignContext signContext = new DOMSignContext(dummyPrivateKey, doc.getDocumentElement());
        signContext.putNamespacePrefix(XMLSignature.XMLNS, "ds");

        String signatureValueId = "value-" + computeDeterministicId(parameters);
        DOMXMLSignature signature = createSignature(parameters, doc, document, signContext, signatureValueId);

        /* Output document */
        if (LOG.isLoggable(Level.FINE)) {
            ByteArrayOutputStream logOutput = new ByteArrayOutputStream();
            Result result = new StreamResult(logOutput);
            Transformer xformer = TransformerFactory.newInstance().newTransformer();
            Source source = new DOMSource(doc);
            xformer.transform(source, result);
            LOG.fine("Document after digest " + new String(logOutput.toByteArray()));
        }

        DOMSignedInfo domSignedInfo = (DOMSignedInfo) signature.getSignedInfo();
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        domSignedInfo.canonicalize(signContext, output);
        output.close();

        return new ByteArrayInputStream(output.toByteArray());

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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

Document signDocument(Document document, SignatureParameters parameters, byte[] signatureValue) {

    try {/*from   w w w .  j  ava  2s  .c om*/

        /* Read the document */
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        org.w3c.dom.Document doc = null;
        if (parameters.getSignaturePackaging() == SignaturePackaging.ENVELOPED) {
            doc = db.parse(document.openStream());
        } else {
            doc = db.newDocument();
            doc.appendChild(doc.createElement("empty"));
        }

        /* Interceptor */
        SpecialPrivateKey dummyPrivateKey = new SpecialPrivateKey();

        /* Context */
        DOMSignContext signContext = new DOMSignContext(dummyPrivateKey, doc.getDocumentElement());
        signContext.putNamespacePrefix(XMLSignature.XMLNS, "ds");

        String signatureValueId = "value-" + computeDeterministicId(parameters);

        DOMXMLSignature domSig = createSignature(parameters, doc, document, signContext, signatureValueId);

        String xpathString = "//ds:SignatureValue[@Id='" + signatureValueId + "']";
        Element signatureValueEl = XMLUtils.getElement(doc, xpathString);

        if (parameters.getSignatureAlgorithm() == SignatureAlgorithm.ECDSA) {
            signatureValueEl.setTextContent(
                    new String(Base64.encode(SignatureECDSA.convertASN1toXMLDSIG(signatureValue))));
        } else if (parameters.getSignatureAlgorithm() == SignatureAlgorithm.DSA) {
            signatureValueEl.setTextContent(new String(Base64.encode(convertASN1toXMLDSIG(signatureValue))));
        } else {
            signatureValueEl.setTextContent(new String(Base64.encode(signatureValue)));
        }

        UnsignedPropertiesType unsigned = createUnsignedXAdESProperties(parameters, domSig, null,
                signatureValueEl);
        if (unsigned != null) {
            JAXBContext xadesJaxbContext = JAXBContext.newInstance(getXades13ObjectFactory().getClass());
            Marshaller m = xadesJaxbContext.createMarshaller();
            JAXBElement<UnsignedPropertiesType> el = getXades13ObjectFactory()
                    .createUnsignedProperties(unsigned);
            m.marshal(el, getXAdESQualifyingProperties(parameters, doc));
        }

        /* Output document */
        ByteArrayOutputStream outputDoc = new ByteArrayOutputStream();
        Result output = new StreamResult(outputDoc);
        Transformer xformer = TransformerFactory.newInstance().newTransformer();
        Source source = new DOMSource(doc);
        xformer.transform(source, output);
        outputDoc.close();

        return new InMemoryDocument(outputDoc.toByteArray());

    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (JAXBException e) {
        throw new RuntimeException(e);
    } catch (XPathExpressionException e) {
        throw new RuntimeException(e);
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    } catch (SAXException e) {
        throw new RuntimeException(e);
    } catch (XMLSignatureException e) {
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new RuntimeException(e);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
}

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

/**
 * Creates signature part of assertion. Uses digest method algorithm
 * corresponding to the signature algorithm used.
 *
 * @param assertion/*from   w  w w  . java  2 s  .co m*/
 * @param signatureAlgorithm
 * @return
 */
private Element createSignatureAndSignAssertion(Assertion assertion, SignatureAlgorithm signatureAlgorithm,
        SignInfo signInfo) {
    assert assertion != null;
    assert signatureAlgorithm != null;

    XMLSignatureFactory factory = XMLSignatureFactory.getInstance();
    Element assertionElement = marshallAssertion(assertion);
    List<Transform> transforms = createTransforms();
    Reference ref = createReference(transforms, assertionElement.getAttribute(Assertion.ID_ATTRIB_NAME),
            // here we use the digest method which is corresponding to the
            // signature algorithm used
            signatureAlgorithm.getDigestMethod().toString());
    SignedInfo signedInfo = createSignedInfo(Collections.singletonList(ref), signatureAlgorithm);

    DOMSignContext signingContext = new DOMSignContext(signInfo.getPrivateKey(), assertionElement);
    signingContext.putNamespacePrefix(SignatureConstants.TRANSFORM_C14N_EXCL_OMIT_COMMENTS, "ec");
    signingContext.putNamespacePrefix(XMLSignature.XMLNS, "ds");

    // signature should be the second section in the assertion - after issuer
    // here we are sure that the structure of assertion is as follows:
    // 1) issuer 2) subject
    // we get subject node and enter signature before it and the result is:
    // 1) issuer 2) signature 3) subject
    Node subjectNode = assertionElement.getChildNodes().item(1);
    signingContext.setNextSibling(subjectNode);
    log.debug("Set SigningContext into assertion (after Issuer or as a first child in the assertion DOM).");

    final KeyInfo keyInfo = createKeyInfo(signInfo);
    XMLSignature xmlSignature = factory.newXMLSignature(signedInfo, keyInfo);

    try {
        final long start = System.nanoTime();
        xmlSignature.sign(signingContext);
        perfLog.trace("'signature.sign' took {} ms.", TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start));
    } catch (MarshalException e) {
        throw new IllegalStateException(e);
    } catch (XMLSignatureException e) {
        throw new IllegalStateException(e);
    }
    log.debug("Created Signature and sign it.");

    return assertionElement;
}

From source file:nl.clockwork.mule.ebms.cxf.XMLDSignatureInInterceptor.java

private boolean verify(Document document, List<EbMSDataSource> dataSources)
        throws MarshalException, XMLSignatureException {
    NodeList nodeList = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    if (nodeList.getLength() > 0) {
        XMLSignatureFactory signFactory = XMLSignatureFactory.getInstance();
        DOMValidateContext validateContext = new DOMValidateContext(new XMLDSigKeySelector(), nodeList.item(0));
        URIDereferencer dereferencer = new EbMSDataSourceURIDereferencer(dataSources);
        validateContext.setURIDereferencer(dereferencer);
        XMLSignature signature = signFactory.unmarshalXMLSignature(validateContext);
        return signature.validate(validateContext);
    }//from  w w w. java  2  s.c o  m
    return true;
}

From source file:org.apache.camel.component.xmlsecurity.api.XAdESSignatureProperties.java

protected void replacePrefix(Element el, Input input) {
    replacePrefixForNode(el, input);/*from ww w . ja v  a2  s.  c  om*/
    NamedNodeMap nnm = el.getAttributes();
    List<Attr> xmlnsToBeRemoved = new ArrayList<Attr>(2);
    int length = nnm.getLength();
    for (int i = 0; i < length; i++) {
        Node attr = nnm.item(i);
        replacePrefixForNode(attr, input);
        if (attr.getNodeType() == Node.ATTRIBUTE_NODE) {
            if ("xmlns".equals(attr.getLocalName()) || "xmlns".equals(attr.getPrefix())) {
                if (XMLSignature.XMLNS.equals(attr.getTextContent())
                        || findNamespace(input.getMessage()).equals(attr.getTextContent())) {
                    xmlnsToBeRemoved.add((Attr) attr);
                }
            }
        }
    }
    // remove xml namespace declaration for XML signature and XAdES namespace
    for (Attr toBeRemoved : xmlnsToBeRemoved) {
        el.removeAttributeNode(toBeRemoved);
    }

}

From source file:org.apache.camel.component.xmlsecurity.api.XAdESSignatureProperties.java

protected void replacePrefixForNode(Node node, Input input) {
    if (XMLSignature.XMLNS.equals(node.getNamespaceURI())) {
        node.setPrefix(input.getPrefixForXmlSignatureNamespace());
    } else if (findNamespace(input.getMessage()).equals(node.getNamespaceURI())) {
        node.setPrefix(findPrefix(input.getMessage()));
    }/*from   w  w w. j  ava 2  s.  c o m*/
}

From source file:org.apache.jcp.xml.dsig.internal.dom.DOMHMACSignatureMethod.java

void marshalParams(Element parent, String prefix) throws MarshalException {
    Document ownerDoc = DOMUtils.getOwnerDocument(parent);
    Element hmacElem = DOMUtils.createElement(ownerDoc, "HMACOutputLength", XMLSignature.XMLNS, prefix);
    hmacElem.appendChild(ownerDoc.createTextNode(String.valueOf(outputLength)));

    parent.appendChild(hmacElem);/* w  w w .  jav a 2s  . c om*/
}