Example usage for org.w3c.dom Document createComment

List of usage examples for org.w3c.dom Document createComment

Introduction

In this page you can find the example usage for org.w3c.dom Document createComment.

Prototype

public Comment createComment(String data);

Source Link

Document

Creates a Comment node given the specified string.

Usage

From source file:org.apache.xml.security.samples.signature.CreateMerlinsExampleTwentyThree.java

/**
 * Method main/*from w w  w .j a v  a  2  s  .  com*/
 *
 * @param unused
 * @throws Exception
 */
public static void main(String unused[]) throws Exception {
    Constants.setSignatureSpecNSprefix("ds");
    //J-
    String keystoreType = "JKS";
    String keystoreFile = "data/org/apache/xml/security/samples/input/keystore.jks";
    String keystorePass = "xmlsecurity";
    String privateKeyAlias = "test";
    String privateKeyPass = "xmlsecurity";
    String certificateAlias = "test";
    File signatureFile = new File("merlinsTwentyThreeRecreatedNoRetrievalMethod.xml");
    //J+
    KeyStore ks = KeyStore.getInstance(keystoreType);
    FileInputStream fis = new FileInputStream(keystoreFile);

    ks.load(fis, keystorePass.toCharArray());

    PrivateKey privateKey = (PrivateKey) ks.getKey(privateKeyAlias, privateKeyPass.toCharArray());

    if (privateKey == null) {
        throw new RuntimeException("Private key is null");
    }

    X509Certificate cert = (X509Certificate) ks.getCertificate(certificateAlias);
    javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();

    dbf.setNamespaceAware(true);

    javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
    org.w3c.dom.Document doc = db.newDocument();

    //////////////////////////////////////////////////
    Element envelope = doc.createElementNS("http://www.usps.gov/", "Envelope");

    envelope.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", "http://www.usps.gov/");
    envelope.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:foo", "http://www.usps.gov/foo");
    envelope.appendChild(doc.createTextNode("\n"));
    doc.appendChild(doc.createComment(" Preamble "));
    doc.appendChild(envelope);
    doc.appendChild(doc.createComment(" Postamble "));

    Element dearSir = doc.createElementNS("http://www.usps.gov/", "DearSir");

    dearSir.appendChild(doc.createTextNode("foo"));
    envelope.appendChild(dearSir);
    envelope.appendChild(doc.createTextNode("\n"));

    Element body = doc.createElementNS("http://www.usps.gov/", "Body");

    body.appendChild(doc.createTextNode("bar"));
    envelope.appendChild(body);
    envelope.appendChild(doc.createTextNode("\n"));

    Element YoursSincerely = doc.createElementNS("http://www.usps.gov/", "YoursSincerely");
    YoursSincerely.appendChild(doc.createTextNode("\n"));

    envelope.appendChild(YoursSincerely);

    Element PostScript = doc.createElementNS("http://www.usps.gov/", "PostScript");

    PostScript.appendChild(doc.createTextNode("bar"));
    envelope.appendChild(PostScript);

    Element Notaries = doc.createElementNS(null, "Notaries");

    Notaries.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", "");
    Notaries.setAttributeNS(null, "Id", "notaries");
    IdResolver.registerElementById(Notaries, "Id");

    {
        Element Notary = doc.createElementNS(null, "Notary");

        Notary.setAttributeNS(null, "name", "Great, A. T.");
        Notaries.appendChild(Notary);
    }

    {
        Element Notary = doc.createElementNS(null, "Notary");

        Notary.setAttributeNS(null, "name", "Hun, A. T.");
        Notaries.appendChild(Notary);
    }

    envelope.appendChild(Notaries);
    envelope.appendChild(doc.createComment(" Commentary "));

    //////////////////////////////////////////////////
    String BaseURI = signatureFile.toURL().toString();
    XMLSignature sig = new XMLSignature(doc, BaseURI, XMLSignature.ALGO_ID_SIGNATURE_DSA);

    YoursSincerely.appendChild(sig.getElement());
    sig.setId("signature");

    /*
     * Add the Objects
     */

    // object-1
    {
        ObjectContainer object1 = new ObjectContainer(doc);

        object1.setId("object-1");
        object1.setMimeType("text/plain");
        object1.appendChild(doc.createTextNode("I am the text."));
        sig.appendObject(object1);
    }

    // object-2
    {
        ObjectContainer object2 = new ObjectContainer(doc);

        object2.setId("object-2");
        object2.setMimeType("text/plain");
        object2.setEncoding("http://www.w3.org/2000/09/xmldsig#base64");
        object2.appendChild(doc.createTextNode("SSBhbSB0aGUgdGV4dC4="));
        sig.appendObject(object2);
    }

    // object-3
    {
        ObjectContainer object = new ObjectContainer(doc);

        object.setId("object-3");

        Element nonc = doc.createElementNS(null, "NonCommentandus");

        nonc.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", "");
        nonc.appendChild(doc.createComment(" Commentandum "));
        object.appendChild(doc.createTextNode("\n        "));
        object.appendChild(nonc);
        object.appendChild(doc.createTextNode("\n      "));
        sig.appendObject(object);
    }

    // object number 4
    {
        ObjectContainer object = new ObjectContainer(doc);

        object.appendChild(createObject4(sig));
        sig.appendObject(object);
    }

    // object number 4
    {
        ObjectContainer object = new ObjectContainer(doc);
        SignatureProperties sps = new SignatureProperties(doc);

        sps.setId("signature-properties-1");

        SignatureProperty sp = new SignatureProperty(doc, "#signature");
        Element signedAdress = doc.createElementNS("urn:demo", "SignedAddress");

        signedAdress.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", "urn:demo");

        Element IP = doc.createElementNS("urn:demo", "IP");

        IP.appendChild(doc.createTextNode("192.168.21.138"));
        signedAdress.appendChild(IP);
        sp.appendChild(signedAdress);
        sps.addSignatureProperty(sp);
        object.appendChild(sps.getElement());
        sig.appendObject(object);
    }

    {
        ObjectContainer object = new ObjectContainer(doc);

        object.setId("object-4");

        X509Data x509data = new X509Data(doc);

        x509data.add(new XMLX509SubjectName(doc, cert));
        x509data.add(new XMLX509IssuerSerial(doc, cert));
        x509data.add(new XMLX509Certificate(doc, cert));
        object.appendChild(x509data.getElement());
        sig.appendObject(object);
    }

    /*
     * Add References
     */
    sig.getSignedInfo()
            .addResourceResolver(new org.apache.xml.security.samples.utils.resolver.OfflineResolver());
    sig.addDocument("http://www.w3.org/TR/xml-stylesheet");

    {
        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_BASE64_DECODE);
        sig.addDocument("http://xmldsig.pothole.com/xml-stylesheet.txt", transforms,
                Constants.ALGO_ID_DIGEST_SHA1);
    }

    {
        Transforms transforms = new Transforms(doc);
        XPathContainer xpathC = new XPathContainer(doc);

        xpathC.setXPath("self::text()");
        transforms.addTransform(Transforms.TRANSFORM_XPATH, xpathC.getElementPlusReturns());
        sig.addDocument("#object-1", transforms, Constants.ALGO_ID_DIGEST_SHA1, null,
                "http://www.w3.org/2000/09/xmldsig#Object");
    }
    /*
    {
       Transforms transforms = new Transforms(doc);
       XPathContainer xpathC = new XPathContainer(doc);
            
       //J-
       xpathC.setXPathNamespaceContext("ds", Constants.SignatureSpecNS);
       xpathC.setXPath("\n"
        + " ancestor-or-self::ds:SignedInfo                    " + "\n"
        + "  and                                               " + "\n"
        + " count(ancestor-or-self::ds:Reference |             " + "\n"
        + "      here()/ancestor::ds:Reference[1]) >           " + "\n"
        + " count(ancestor-or-self::ds:Reference)              " + "\n"
        + "  or                                                " + "\n"
        + " count(ancestor-or-self::node() |                   " + "\n"
        + "      id('notaries')) =                             " + "\n"
        + " count(ancestor-or-self::node())                    " + "\n");
       //J+
       transforms.addTransform(Transforms.TRANSFORM_XPATH,
                         xpathC.getElementPlusReturns());
       sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1, null,
                 "http://www.w3.org/2000/09/xmldsig#Object");
    }
    */

    {
        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_BASE64_DECODE);
        sig.addDocument("#object-2", transforms, Constants.ALGO_ID_DIGEST_SHA1, null,
                "http://www.w3.org/2000/09/xmldsig#Object");
    }

    sig.addDocument("#manifest-1", null, Constants.ALGO_ID_DIGEST_SHA1, null,
            "http://www.w3.org/2000/09/xmldsig#Manifest");
    sig.addDocument("#signature-properties-1", null, Constants.ALGO_ID_DIGEST_SHA1, null,
            "http://www.w3.org/2000/09/xmldsig#SignatureProperties");

    {
        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
        sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);
    }

    {
        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
        transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
        sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);
    }

    {
        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
        sig.addDocument("#xpointer(/)", transforms, Constants.ALGO_ID_DIGEST_SHA1);
    }

    {
        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
        transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
        sig.addDocument("#xpointer(/)", transforms, Constants.ALGO_ID_DIGEST_SHA1);
    }

    {
        sig.addDocument("#object-3", null, Constants.ALGO_ID_DIGEST_SHA1, null,
                "http://www.w3.org/2000/09/xmldsig#Object");
    }

    {
        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
        sig.addDocument("#object-3", transforms, Constants.ALGO_ID_DIGEST_SHA1, null,
                "http://www.w3.org/2000/09/xmldsig#Object");
    }

    {
        sig.addDocument("#xpointer(id('object-3'))", null, Constants.ALGO_ID_DIGEST_SHA1, null,
                "http://www.w3.org/2000/09/xmldsig#Object");
    }

    {
        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
        sig.addDocument("#xpointer(id('object-3'))", transforms, Constants.ALGO_ID_DIGEST_SHA1, null,
                "http://www.w3.org/2000/09/xmldsig#Object");
    }

    {
        sig.addDocument("#manifest-reference-1", null, Constants.ALGO_ID_DIGEST_SHA1, "reference-1",
                "http://www.w3.org/2000/09/xmldsig#Reference");
    }

    {
        sig.addDocument("#reference-1", null, Constants.ALGO_ID_DIGEST_SHA1, "reference-2",
                "http://www.w3.org/2000/09/xmldsig#Reference");
    }

    {
        sig.addDocument("#reference-2", null, Constants.ALGO_ID_DIGEST_SHA1, null,
                "http://www.w3.org/2000/09/xmldsig#Reference");
    }

    /*
     * Add KeyInfo and sign()
     */
    {
        Transforms retrievalTransforms = new Transforms(doc);
        XPathContainer xpathC = new XPathContainer(doc);

        xpathC.setXPathNamespaceContext("ds", Constants.SignatureSpecNS);
        xpathC.setXPath("ancestor-or-self::ds:X509Data");
        retrievalTransforms.addTransform(Transforms.TRANSFORM_XPATH, xpathC.getElement());
        sig.getKeyInfo().add(new RetrievalMethod(doc, "#object-4", retrievalTransforms,
                "http://www.w3.org/2000/09/xmldsig#X509Data"));

        /*
        X509Data x509data = new X509Data(doc);
                
        x509data.add(new XMLX509SubjectName(doc, cert));
        x509data.add(new XMLX509IssuerSerial(doc, cert));
        x509data.add(new XMLX509Certificate(doc, cert));
        sig.getKeyInfo().add(x509data);
        */

        System.out.println("Start signing");
        sig.sign(privateKey);
        System.out.println("Finished signing");
    }

    FileOutputStream f = new FileOutputStream(signatureFile);

    XMLUtils.outputDOMc14nWithComments(doc, f);
    f.close();
    System.out.println("Wrote signature to " + BaseURI);

    SignedInfo s = sig.getSignedInfo();
    for (int i = 0; i < s.getLength(); i++) {
        Reference r = s.item(i);
        String fn = "merlin16_" + i + ".html";
        System.out.println("Wrote Reference " + i + " to file " + fn);
        JavaUtils.writeBytesToFilename(fn, r.getHTMLRepresentation().getBytes());
    }

    /*
    for (int i=0; i<s.getSignedContentLength(); i++) {
       if (s.item(i).getType().equals(Reference.MANIFEST_URI)) {
    System.out.println("################ Signed Manifest " + i + " ################");
       } else {
    System.out.println("################ Signed Resource " + i + " ################");
       }
       System.out.println(new String(s.getSignedContentItem(i)));
       System.out.println();
    }
    */
}

From source file:org.apache.xml.security.samples.signature.CreateSignature.java

/**
 * Method main/*from w  ww  . jav a 2s .c o m*/
 *
 * @param unused
 * @throws Exception
 */
public static void main(String unused[]) throws Exception {
    Constants.setSignatureSpecNSprefix("ds");

    //J-
    //All the parameters for the keystore
    String keystoreType = "JKS";
    String keystoreFile = "data/org/apache/xml/security/samples/input/keystore.jks";
    String keystorePass = "xmlsecurity";
    String privateKeyAlias = "test";
    String privateKeyPass = "xmlsecurity";
    String certificateAlias = "test";
    File signatureFile = new File("signature.xml");
    //J+
    KeyStore ks = KeyStore.getInstance(keystoreType);
    FileInputStream fis = new FileInputStream(keystoreFile);

    //load the keystore
    ks.load(fis, keystorePass.toCharArray());

    //get the private key for signing.
    PrivateKey privateKey = (PrivateKey) ks.getKey(privateKeyAlias, privateKeyPass.toCharArray());
    javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();

    //XML Signature needs to be namespace aware
    dbf.setNamespaceAware(true);

    javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
    org.w3c.dom.Document doc = db.newDocument();

    //Build a sample document. It will look something like:
    //<!-- Comment before -->
    //<apache:RootElement xmlns:apache="http://www.apache.org/ns/#app1">Some simple text
    //</apache:RootElement>
    //<!-- Comment after -->
    doc.appendChild(doc.createComment(" Comment before "));

    Element root = doc.createElementNS("http://www.apache.org/ns/#app1", "apache:RootElement");

    root.setAttributeNS(null, "attr1", "test1");
    root.setAttributeNS(null, "attr2", "test2");
    root.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:foo", "http://example.org/#foo");
    root.setAttributeNS("http://example.org/#foo", "foo:attr1", "foo's test");

    root.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:apache", "http://www.apache.org/ns/#app1");
    doc.appendChild(root);
    root.appendChild(doc.createTextNode("Some simple text\n"));

    //The BaseURI is the URI that's used to prepend to relative URIs
    String BaseURI = signatureFile.toURL().toString();
    //Create an XML Signature object from the document, BaseURI and
    //signature algorithm (in this case DSA)
    XMLSignature sig = new XMLSignature(doc, BaseURI, XMLSignature.ALGO_ID_SIGNATURE_DSA);

    //Append the signature element to the root element before signing because
    //this is going to be an enveloped signature.
    //This means the signature is going to be enveloped by the document.
    //Two other possible forms are enveloping where the document is inside the
    //signature and detached where they are seperate.
    //Note that they can be mixed in 1 signature with seperate references as
    //shown below.
    root.appendChild(sig.getElement());
    doc.appendChild(doc.createComment(" Comment after "));
    sig.getSignedInfo()
            .addResourceResolver(new org.apache.xml.security.samples.utils.resolver.OfflineResolver());

    {
        //create the transforms object for the Document/Reference
        Transforms transforms = new Transforms(doc);

        //First we have to strip away the signature element (it's not part of the
        //signature calculations). The enveloped transform can be used for this.
        transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
        //Part of the signature element needs to be canonicalized. It is a kind
        //of normalizing algorithm for XML. For more information please take a
        //look at the W3C XML Digital Signature webpage.
        transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
        //Add the above Document/Reference
        sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);
    }

    {
        //Add in 2 external URIs. This is a detached Reference.
        //
        // When sign() is called, two network connections are made. -- well,
        // not really, as we use the OfflineResolver which acts as a proxy for
        // these two resouces ;-))
        //
        sig.addDocument("http://www.w3.org/TR/xml-stylesheet");
        sig.addDocument("http://www.nue.et-inf.uni-siegen.de/index.html");
    }

    {
        //Add in the KeyInfo for the certificate that we used the private key of
        X509Certificate cert = (X509Certificate) ks.getCertificate(certificateAlias);

        sig.addKeyInfo(cert);
        sig.addKeyInfo(cert.getPublicKey());
        System.out.println("Start signing");
        sig.sign(privateKey);
        System.out.println("Finished signing");
    }

    FileOutputStream f = new FileOutputStream(signatureFile);

    XMLUtils.outputDOMc14nWithComments(doc, f);

    f.close();
    System.out.println("Wrote signature to " + BaseURI);
}

From source file:org.apache.xml.security.test.signature.CreateSignatureTest.java

String doSign() throws Exception {
    PrivateKey privateKey = kp.getPrivate();
    org.w3c.dom.Document doc = db.newDocument();
    doc.appendChild(doc.createComment(" Comment before "));
    Element root = doc.createElementNS("", "RootElement");

    doc.appendChild(root);/*from   www .ja  v a 2  s  .  c o m*/
    root.appendChild(doc.createTextNode("Some simple text\n"));

    Element canonElem = XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_CANONICALIZATIONMETHOD);
    canonElem.setAttributeNS(null, Constants._ATT_ALGORITHM, Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

    SignatureAlgorithm signatureAlgorithm = new SignatureAlgorithm(doc,
            XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1);
    XMLSignature sig = new XMLSignature(doc, null, signatureAlgorithm.getElement(), canonElem);

    root.appendChild(sig.getElement());
    doc.appendChild(doc.createComment(" Comment after "));
    Transforms transforms = new Transforms(doc);
    transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
    transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
    sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);

    sig.addKeyInfo(kp.getPublic());
    sig.sign(privateKey);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    XMLUtils.outputDOMc14nWithComments(doc, bos);
    return new String(bos.toByteArray());
}

From source file:org.apache.xml.security.test.signature.CreateSignatureTest.java

String doSignWithCert() throws Exception {
    KeyStore ks = KeyStore.getInstance("JKS");
    FileInputStream fis = null;/*w  ww  .ja va  2  s .  c  om*/
    if (BASEDIR != null && !"".equals(BASEDIR)) {
        fis = new FileInputStream(BASEDIR + SEP + "data/test.jks");
    } else {
        fis = new FileInputStream("data/test.jks");
    }
    ks.load(fis, "changeit".toCharArray());
    PrivateKey privateKey = (PrivateKey) ks.getKey("mullan", "changeit".toCharArray());
    org.w3c.dom.Document doc = db.newDocument();
    X509Certificate signingCert = (X509Certificate) ks.getCertificate("mullan");
    doc.appendChild(doc.createComment(" Comment before "));
    Element root = doc.createElementNS("", "RootElement");

    doc.appendChild(root);
    root.appendChild(doc.createTextNode("Some simple text\n"));

    Element canonElem = XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_CANONICALIZATIONMETHOD);
    canonElem.setAttributeNS(null, Constants._ATT_ALGORITHM, Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

    SignatureAlgorithm signatureAlgorithm = new SignatureAlgorithm(doc, XMLSignature.ALGO_ID_SIGNATURE_DSA);
    XMLSignature sig = new XMLSignature(doc, null, signatureAlgorithm.getElement(), canonElem);

    root.appendChild(sig.getElement());
    doc.appendChild(doc.createComment(" Comment after "));
    Transforms transforms = new Transforms(doc);
    transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
    transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
    sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);

    sig.addKeyInfo(signingCert);
    sig.sign(privateKey);
    X509Certificate cert = sig.getKeyInfo().getX509Certificate();
    sig.checkSignatureValue(cert.getPublicKey());
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    XMLUtils.outputDOMc14nWithComments(doc, bos);
    return new String(bos.toByteArray());
}

From source file:org.apache.xml.security.test.signature.ECDSASignatureTest.java

private byte[] doSign() throws Exception {
    PrivateKey privateKey = (PrivateKey) keyStore.getKey("ECDSA", ECDSA_JKS_PASSWORD.toCharArray());
    org.w3c.dom.Document doc = db.newDocument();
    doc.appendChild(doc.createComment(" Comment before "));
    Element root = doc.createElementNS("", "RootElement");

    doc.appendChild(root);// ww w.  j  ava  2s.  co m
    root.appendChild(doc.createTextNode("Some simple text\n"));

    Element canonElem = XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_CANONICALIZATIONMETHOD);
    canonElem.setAttributeNS(null, Constants._ATT_ALGORITHM, Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

    SignatureAlgorithm signatureAlgorithm = new SignatureAlgorithm(doc,
            XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1);
    XMLSignature sig = new XMLSignature(doc, null, signatureAlgorithm.getElement(), canonElem);

    root.appendChild(sig.getElement());
    doc.appendChild(doc.createComment(" Comment after "));
    Transforms transforms = new Transforms(doc);
    transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
    transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
    sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);

    X509Certificate x509 = (X509Certificate) keyStore.getCertificate("ECDSA");
    sig.addKeyInfo(x509);
    sig.sign(privateKey);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    XMLUtils.outputDOMc14nWithComments(doc, bos);
    return bos.toByteArray();
}

From source file:org.atricore.idbus.capabilities.sso.support.test.XmlDsigTest.java

/**
 * Sign a simple DOM document using the configured JSR 105 Provider
 *///from  ww  w. j a v  a  2s. c o m
@Test
public void simpleDocumentSign() throws Exception {

    //All the parameters for the keystore
    String keystoreType = "JKS";
    String keystoreFile = "src/test/resources/keystore.jks";
    String keystorePass = "xmlsecurity";
    String privateKeyAlias = "test";
    String privateKeyPass = "xmlsecurity";
    String certificateAlias = "test";
    File signatureFile = new File("target/signature.xml");

    KeyStore ks = KeyStore.getInstance(keystoreType);
    FileInputStream fis = new FileInputStream(keystoreFile);

    //load the keystore
    ks.load(fis, keystorePass.toCharArray());

    //get the private key for signing.
    PrivateKey privateKey = (PrivateKey) ks.getKey(privateKeyAlias, privateKeyPass.toCharArray());

    X509Certificate cert = (X509Certificate) ks.getCertificate(certificateAlias);
    PublicKey publicKey = cert.getPublicKey();

    // Create a DOM XMLSignatureFactory that will be used to generate the
    // enveloped signature
    String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI");

    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM",
            (Provider) Class.forName(providerName).newInstance());

    // Create a Reference to the enveloped document (in this case we are
    // signing the whole document, so a URI of "" signifies that) and
    // also specify the SHA1 digest algorithm and the ENVELOPED Transform.
    Reference ref = fac.newReference("#12345", fac.newDigestMethod(DigestMethod.SHA1, null),
            Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)),
            null, null);

    // Create the SignedInfo
    SignedInfo si = fac.newSignedInfo(
            fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                    (C14NMethodParameterSpec) null),
            fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref));

    // Instantiate the document to be signed
    javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();

    //XML Signature needs to be namespace aware
    dbf.setNamespaceAware(true);

    javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
    org.w3c.dom.Document doc = db.newDocument();

    //Build a sample document. It will look something like:
    //<!-- Comment before -->
    //<apache:RootElement xmlns:apache="http://www.apache.org/ns/#app1" ID="12345">Some simple text
    //</apache:RootElement>
    //<!-- Comment after -->
    doc.appendChild(doc.createComment(" Comment before "));

    Element root = doc.createElementNS("http://www.apache.org/ns/#app1", "apache:RootElement");

    root.setAttributeNS(null, "ID", "12345");

    root.setAttributeNS(null, "attr1", "test1");
    root.setAttributeNS(null, "attr2", "test2");
    root.setAttributeNS(org.apache.xml.security.utils.Constants.NamespaceSpecNS, "xmlns:foo",
            "http://example.org/#foo");
    root.setAttributeNS("http://example.org/#foo", "foo:attr1", "foo's test");

    root.setAttributeNS(org.apache.xml.security.utils.Constants.NamespaceSpecNS, "xmlns:apache",
            "http://www.apache.org/ns/#app1");
    doc.appendChild(root);
    root.appendChild(doc.createTextNode("Some simple text\n"));

    // Create a DOMSignContext and specify the DSA PrivateKey and
    // location of the resulting XMLSignature's parent element
    DOMSignContext dsc = new DOMSignContext(privateKey, doc.getDocumentElement());

    // Create the XMLSignature (but don't sign it yet)
    KeyInfoFactory kif = fac.getKeyInfoFactory();

    X509Data kv = kif.newX509Data(Collections.singletonList(cert));

    // Create a KeyInfo and add the KeyValue to it
    KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
    javax.xml.crypto.dsig.XMLSignature signature = fac.newXMLSignature(si, ki);

    signature.sign(dsc);

    // TODO : Verify signature ?

    // output the resulting document
    FileOutputStream f = new FileOutputStream(signatureFile);
    XMLUtils.outputDOMc14nWithComments(doc, f);
    f.close();

}

From source file:org.dhatim.delivery.dom.serialize.ContextObjectSerializationUnit.java

/**
 * Utility method for creating a &lt;context-object/&gt; element.
 * @param ownerDocument The owner document.
 * @param key The context key./*from  ww  w .  j a  v a  2s  .c  o m*/
 * @return The &lt;context-object/&gt; element.
 */
public static Element createElement(Document ownerDocument, String key) {
    Element resultElement = ownerDocument.createElementNS(Namespace.SMOOKS_URI, "context-object");
    Comment comment = ownerDocument.createComment(
            " The actual message payload is set on the associated Smooks ExecutionContext under the key '" + key
                    + "'.  Alternatively, you can use Smooks to serialize the message. ");

    resultElement.setAttribute("key", key);
    resultElement.appendChild(comment);

    return resultElement;
}

From source file:org.docx4j.template.handler.OutputConversionHTMLStyleElementHandler.java

@Override
public Element createStyleElement(OpcPackage opcPackage, Document document, String styleDefinition) {

    // See XsltHTMLFunctions, which typically generates the String styleDefinition.
    // In practice, the styles are coupled to the document content, so you're
    // less likely to override their content; just whether they are linked or inline.

    Element ret = null;/*from  w w w  . ja  v a 2s .  co  m*/
    if ((styleDefinition != null) && (styleDefinition.length() > 0)) {
        ret = document.createElement("style");
        ret.setAttribute("type", "text/css");
        ret.appendChild(document.createComment(styleDefinition));
    }

    /**Key = docx4j.Convert.Out.HTML.CssIncludeUri*/
    String cssIncludeUri = Docx4jProperties.getProperty(Docx4jConstants.DOCX4J_CONVERT_OUT_HTML_CSSINCLUDEURI);
    if ((cssIncludeUri != null) && (cssIncludeUri.length() > 0)) {
        try {
            ret = document.createElement("style");
            ret.setAttribute("type", "text/css");
            ret.appendChild(
                    document.createComment(IOUtils.toString(new URI(cssIncludeUri), Charset.defaultCharset())));
        } catch (IOException e) {
            //do nothing
        } catch (URISyntaxException e) {
            //do nothing
        }
    }
    /**Key = docx4j.Convert.Out.HTML.CssIncludePath*/
    String cssIncludePath = Docx4jProperties
            .getProperty(Docx4jConstants.DOCX4J_CONVERT_OUT_HTML_CSSINCLUDEPATH);
    if ((cssIncludePath != null) && (cssIncludePath.length() > 0)) {
        InputStream input = null;
        try {
            input = new FileInputStream(cssIncludePath);
            ret = document.createElement("style");
            ret.setAttribute("type", "text/css");
            ret.appendChild(document.createComment(IOUtils.toString(input, Charset.defaultCharset())));
        } catch (IOException e) {
            //do nothing
        } finally {
            IOUtils.closeQuietly(input);
        }
    }

    return ret;
}

From source file:org.eclipse.winery.common.ModelUtilities.java

/**
 * Generates a XSD when Winery's K/V properties are used. This method is put here instead of
 * WinerysPropertiesDefinitionResource to avoid generating the subresource
 * /*from ww w.j ava  2s  .co  m*/
 * public because of the usage by TOSCAEXportUtil
 * 
 * @return empty Document, if Winery's Properties Definition is not fully filled (e.g., no
 *         wrapping element defined)
 */
public static Document getWinerysPropertiesDefinitionXSDAsDocument(WinerysPropertiesDefinition wpd) {
    /*
     * This is a quick hack: an XML schema container is created for each element. Smarter
     * solution: create a hash from namespace to XML schema element and re-use that for each new
     * element Drawback of "smarter" solution: not a single XSD file any more
     */
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder;
    try {
        docBuilder = docFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        ModelUtilities.logger.debug(e.getMessage(), e);
        throw new IllegalStateException("Could not instantiate document builder", e);
    }
    Document doc = docBuilder.newDocument();

    if (!ModelUtilities.allRequiredFieldsNonNull(wpd)) {
        // wpd not fully filled -> valid XSD cannot be provided
        // fallback: add comment and return "empty" document
        Comment comment = doc
                .createComment("Required fields are missing in Winery's key/value properties definition.");
        doc.appendChild(comment);
        return doc;
    }

    // create XSD schema container
    Element schemaElement = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "schema");
    doc.appendChild(schemaElement);
    schemaElement.setAttribute("elementFormDefault", "qualified");
    schemaElement.setAttribute("attributeFormDefault", "unqualified");
    schemaElement.setAttribute("targetNamespace", wpd.getNamespace());

    // create XSD element itself
    Element el = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "element");
    schemaElement.appendChild(el);
    el.setAttribute("name", wpd.getElementName());
    Element el2 = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "complexType");
    el.appendChild(el2);
    el = el2;
    el2 = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "sequence");
    el.appendChild(el2);
    el = el2;

    // currently, "xsd" is a hardcoded prefix in the type definition
    el.setAttribute("xmlns:xsd", XMLConstants.W3C_XML_SCHEMA_NS_URI);

    for (PropertyDefinitionKV prop : wpd.getPropertyDefinitionKVList()) {
        el2 = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "element");
        el.appendChild(el2);
        el2.setAttribute("name", prop.getKey());
        // prop.getType has the prefix included
        el2.setAttribute("type", prop.getType());
    }

    return doc;
}

From source file:org.gvnix.addon.web.mvc.addon.jquery.JQueryOperationsImpl.java

private boolean addMomentAndDatepickerConfig(Document docTagx, Element root, String varName, String location) {

    boolean modified = false;

    // add url resolution
    modified = WebProjectUtils.addUrlToTag(docTagx, root, varName, location);

    // Add script
    Element scriptElement = XmlUtils.findFirstElement(String.format("script[@src='${%s}']", varName), root);
    if (scriptElement == null) {
        scriptElement = docTagx.createElement("script");
        scriptElement.setAttribute("src", "${".concat(varName).concat("}"));
        scriptElement.setAttribute("type", "text/javascript");
        scriptElement.appendChild(docTagx.createComment("required for FF3 and Opera"));
        root.appendChild(scriptElement);
        modified = true;//  w w w.j  a  v  a  2 s  . c  om

        // Add configuration script
        Element scriptConfigElement = docTagx.createElement("script");
        scriptConfigElement.setAttribute("type", "text/javascript");
        StringBuilder strb = new StringBuilder();
        strb.append("// set momentjs  and jQuery datetimepicker locale\n");
        strb.append("moment.locale('${jqueryLocale}');\n");
        strb.append("jQuery.datetimepicker.setLocale('${jqueryLocale}');\n");
        strb.append("\n");
        strb.append("// Define parse/format date using moment library\n");
        strb.append("Date.parseDate = function( input, format ){\n");
        strb.append("    return moment(input,format).toDate();\n");
        strb.append("};\n");
        strb.append("Date.prototype.dateFormat = function( format ){\n");
        strb.append("    return moment(this).format(format);\n");
        strb.append("};\n");
        scriptConfigElement.appendChild(docTagx.createTextNode(strb.toString()));
        root.appendChild(scriptConfigElement);
    }

    return modified;
}