Example usage for java.security KeyStore getKey

List of usage examples for java.security KeyStore getKey

Introduction

In this page you can find the example usage for java.security KeyStore getKey.

Prototype

public final Key getKey(String alias, char[] password)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException 

Source Link

Document

Returns the key associated with the given alias, using the given password to recover it.

Usage

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

/**
 * Method main//ww w  . j  ava 2 s.  c om
 *
 * @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:com.peterphi.std.crypto.keygen.CaHelper.java

public static void main(String[] args) throws Exception {

    String casubject = "C=UK, O=SOMEORG, OU=Org Unit, CN=Example Certificate Authority";

    X509Certificate cacert = null;
    PrivateKey caPrivateKey = null;

    if (true) {//  www . j ava 2  s  .c o m
        KeyStore ks = KeyStore.getInstance("PKCS12", "BC");

        ks.load(new FileInputStream(new File("/tmp/someorg-ca.p12")), new char[] {});
        caPrivateKey = (PrivateKey) ks.getKey("ca", new char[] {});

        cacert = (X509Certificate) ks.getCertificate("ca");
    } else {
        KeyPair cakeys = generateKeyPair(2048);
        caPrivateKey = cakeys.getPrivate();
        cacert = generateCaCertificate(casubject, cakeys, (BigInteger) null, new X509Name(casubject));
    }

    {
        // CA .p12
        {
            KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
            ks.load(null);
            //ks.setCertificateEntry("ca", cacert);
            ks.setKeyEntry("ca", caPrivateKey, new char[] {}, new java.security.cert.Certificate[] { cacert });

            ks.store(new FileOutputStream("/tmp/someorg-ca.p12"), new char[] {});
        }

        // CA .jks (public key only)
        {
            KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(null);
            ks.setCertificateEntry("ca", cacert);

            ks.store(new FileOutputStream("/tmp/ca-public.jks"), new char[] {});
        }

        // CA .pem (public key only)
        {
            PEMWriter pem = new PEMWriter(new FileWriter(new File("/tmp/d3ca.crt")));

            pem.writeObject(cacert);
            pem.close();
        }
    }

    /*
    // User
    {
       String user = "C=UK, O=SOMEORG, OU=Org Unit, L=SomeCompany, CN=Some User (test)";
       KeyPair keys = generateKeyPair(1024);
       X509Certificate cert = generateClientCertificate(keys.getPublic(), caPrivateKey, new X509Name(subject),
     new X509Name(user));
            
       {
    KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
    ks.load(null);
    ks.setCertificateEntry("issuer", cacert);
    ks.setCertificateEntry("me", cert);
    ks.setKeyEntry("me", keys.getPrivate(), new char[] {}, new java.security.cert.Certificate[] { cert, cacert });
            
    ks.store(new FileOutputStream("/tmp/someorg-someuser.p12"), "SomeCompanysecurity".toCharArray());
       }
            
       {
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null);
    ks.setKeyEntry("me", keys.getPrivate(), new char[] {}, new java.security.cert.Certificate[] { cert, cacert });
    // ks.setCertificateEntry("issuer", cacert);
    // ks.setCertificateEntry("me", cert);
            
    ks.store(new FileOutputStream("/tmp/someorg-someuser.jks"), new char[] {});
       }
    }//*/

    // examplehost hostkey:
    {
        String user = "C=UK, O=SOMEORG, OU=Org Unit, L=SomeCompany, CN=examplehost.example.com";
        KeyPair keys = generateKeyPair(1024);
        X509Certificate cert = generateServerCertificate(keys.getPublic(), caPrivateKey,
                new X509Name(casubject), new X509Name(user));

        {
            KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(null);
            ks.setKeyEntry("me", keys.getPrivate(), new char[] {},
                    new java.security.cert.Certificate[] { cert, cacert });
            // ks.setCertificateEntry("issuer", cacert);
            // ks.setCertificateEntry("me", cert);

            ks.store(new FileOutputStream("/tmp/host.jks"), new char[] {});
        }

        {
            KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
            ks.load(null);
            ks.setCertificateEntry("issuer", cacert);
            ks.setCertificateEntry("me", cert);
            ks.setKeyEntry("me", keys.getPrivate(), new char[] {},
                    new java.security.cert.Certificate[] { cert, cacert });

            ks.store(new FileOutputStream("/tmp/host.p12"), new char[] {});
        }
    }
}

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

/**
 * Method main/*from  w  w w  .j  a  v a  2s .  co  m*/
 *
 * @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("merlinsSixteenRecreatedNoRetrievalMethod.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.CreateMerlinsExampleTwentyThree.java

/**
 * Method main/*from  ww w  . j a  va  2  s. co  m*/
 *
 * @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:PKCS12Import.java

public static void main(String[] args) throws Exception {
    if (args.length < 1) {
        System.err.println("usage: java PKCS12Import {pkcs12file} [newjksfile]");
        System.exit(1);/* w  w  w  .  j a  v a2s.c o  m*/
    }

    File fileIn = new File(args[0]);
    File fileOut;
    if (args.length > 1) {
        fileOut = new File(args[1]);
    } else {
        fileOut = new File("newstore.jks");
    }

    if (!fileIn.canRead()) {
        System.err.println("Unable to access input keystore: " + fileIn.getPath());
        System.exit(2);
    }

    if (fileOut.exists() && !fileOut.canWrite()) {
        System.err.println("Output file is not writable: " + fileOut.getPath());
        System.exit(2);
    }

    KeyStore kspkcs12 = KeyStore.getInstance("pkcs12");
    KeyStore ksjks = KeyStore.getInstance("jks");

    System.out.print("Enter input keystore passphrase: ");
    char[] inphrase = readPassphrase();
    System.out.print("Enter output keystore passphrase: ");
    char[] outphrase = readPassphrase();

    kspkcs12.load(new FileInputStream(fileIn), inphrase);

    ksjks.load((fileOut.exists()) ? new FileInputStream(fileOut) : null, outphrase);

    Enumeration eAliases = kspkcs12.aliases();
    int n = 0;
    while (eAliases.hasMoreElements()) {
        String strAlias = (String) eAliases.nextElement();
        System.err.println("Alias " + n++ + ": " + strAlias);

        if (kspkcs12.isKeyEntry(strAlias)) {
            System.err.println("Adding key for alias " + strAlias);
            Key key = kspkcs12.getKey(strAlias, inphrase);

            Certificate[] chain = kspkcs12.getCertificateChain(strAlias);

            ksjks.setKeyEntry(strAlias, key, outphrase, chain);
        }
    }

    OutputStream out = new FileOutputStream(fileOut);
    ksjks.store(out, outphrase);
    out.close();
}

From source file:createSod.java

/**
 * @param args//from   w  ww.  j  a  v a2s . c o  m
 * @throws CMSException 
 */
public static void main(String[] args) throws Exception {

    try {
        CommandLine options = verifyArgs(args);
        String privateKeyLocation = options.getOptionValue("privatekey");
        String keyPassword = options.getOptionValue("keypass");
        String certificate = options.getOptionValue("certificate");
        String sodContent = options.getOptionValue("content");
        String sod = "";
        if (options.hasOption("out")) {
            sod = options.getOptionValue("out");
        }

        // CHARGEMENT DU FICHIER PKCS#12

        KeyStore ks = null;
        char[] password = null;

        Security.addProvider(new BouncyCastleProvider());
        try {
            ks = KeyStore.getInstance("PKCS12");
            // Password pour le fichier personnal_nyal.p12
            password = keyPassword.toCharArray();
            ks.load(new FileInputStream(privateKeyLocation), password);
        } catch (Exception e) {
            System.out.println("Erreur: fichier " + privateKeyLocation
                    + " n'est pas un fichier pkcs#12 valide ou passphrase incorrect");
            return;
        }

        // RECUPERATION DU COUPLE CLE PRIVEE/PUBLIQUE ET DU CERTIFICAT PUBLIQUE

        X509Certificate cert = null;
        PrivateKey privatekey = null;
        PublicKey publickey = null;

        try {
            Enumeration en = ks.aliases();
            String ALIAS = "";
            Vector vectaliases = new Vector();

            while (en.hasMoreElements())
                vectaliases.add(en.nextElement());
            String[] aliases = (String[]) (vectaliases.toArray(new String[0]));
            for (int i = 0; i < aliases.length; i++)
                if (ks.isKeyEntry(aliases[i])) {
                    ALIAS = aliases[i];
                    break;
                }
            privatekey = (PrivateKey) ks.getKey(ALIAS, password);
            cert = (X509Certificate) ks.getCertificate(ALIAS);
            publickey = ks.getCertificate(ALIAS).getPublicKey();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        // Chargement du certificat  partir du fichier

        InputStream inStream = new FileInputStream(certificate);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        cert = (X509Certificate) cf.generateCertificate(inStream);
        inStream.close();

        // Chargement du fichier qui va tre sign

        File file_to_sign = new File(sodContent);
        byte[] buffer = new byte[(int) file_to_sign.length()];
        DataInputStream in = new DataInputStream(new FileInputStream(file_to_sign));
        in.readFully(buffer);
        in.close();

        // Chargement des certificats qui seront stocks dans le fichier .p7
        // Ici, seulement le certificat personnal_nyal.cer sera associ.
        // Par contre, la chane des certificats non.

        ArrayList certList = new ArrayList();
        certList.add(cert);
        CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList),
                "BC");

        CMSSignedDataGenerator signGen = new CMSSignedDataGenerator();

        // privatekey correspond  notre cl prive rcupre du fichier PKCS#12
        // cert correspond au certificat publique personnal_nyal.cer
        // Le dernier argument est l'algorithme de hachage qui sera utilis

        signGen.addSigner(privatekey, cert, CMSSignedDataGenerator.DIGEST_SHA1);
        signGen.addCertificatesAndCRLs(certs);
        CMSProcessable content = new CMSProcessableByteArray(buffer);

        // Generation du fichier CMS/PKCS#7
        // L'argument deux permet de signifier si le document doit tre attach avec la signature
        //     Valeur true:  le fichier est attach (c'est le cas ici)
        //     Valeur false: le fichier est dtach

        CMSSignedData signedData = signGen.generate(content, true, "BC");
        byte[] signeddata = signedData.getEncoded();

        // Ecriture du buffer dans un fichier.   

        if (sod.equals("")) {
            System.out.print(signeddata.toString());
        } else {
            FileOutputStream envfos = new FileOutputStream(sod);
            envfos.write(signeddata);
            envfos.close();
        }

    } catch (OptionException oe) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(NAME, getOptions());
        System.exit(-1);
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }

}

From source file:com.tremolosecurity.openunison.util.OpenUnisonUtils.java

public static void main(String[] args) throws Exception {

    logger = org.apache.logging.log4j.LogManager.getLogger(OpenUnisonUtils.class.getName());

    Options options = new Options();
    options.addOption("unisonXMLFile", true, "The full path to the Unison xml file");
    options.addOption("keystorePath", true, "The full path to the Unison keystore");
    options.addOption("chainName", true, "The name of the authentication chain");
    options.addOption("mechanismName", true, "The name of the authentication mechanism for SAML2");
    options.addOption("idpName", true, "The name of the identity provider application");
    options.addOption("pathToMetaData", true, "The full path to the saml2 metadata file");
    options.addOption("createDefault", false, "If set, add default parameters");
    options.addOption("action", true,
            "export-sp-metadata, import-sp-metadata, export-secretkey, print-secretkey, import-idp-metadata, export-idp-metadata, clear-dlq, import-secretkey, create-secretkey");
    options.addOption("urlBase", true, "Base URL, no URI; https://host:port");
    options.addOption("alias", true, "Key alias");
    options.addOption("newKeystorePath", true, "Path to the new keystore");
    options.addOption("newKeystorePassword", true, "Password for the new keystore");
    options.addOption("help", false, "Prints this message");
    options.addOption("signMetadataWithKey", true, "Signs the metadata with the specified key");
    options.addOption("dlqName", true, "The name of the dead letter queue");
    options.addOption("upgradeFrom106", false, "Updates workflows from 1.0.6");
    options.addOption("secretkey", true, "base64 encoded secret key");
    options.addOption("envFile", true, "Environment variables for parmaterized configs");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args, true);

    if (args.length == 0 || cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("OpenUnisonUtils", options);
    }/*from  w  w w. ja v  a 2 s.c o  m*/

    logger.info("Loading Unison Configuration");
    String unisonXMLFile = loadOption(cmd, "unisonXMLFile", options);
    TremoloType ttRead = loadTremoloType(unisonXMLFile, cmd, options);

    String action = loadOption(cmd, "action", options);
    TremoloType ttWrite = null;
    if (action.equalsIgnoreCase("import-sp-metadata") || action.equalsIgnoreCase("import-idp-metadata")) {
        ttWrite = loadTremoloType(unisonXMLFile);
    }

    logger.info("Configuration loaded");

    logger.info("Loading the keystore...");
    String ksPath = loadOption(cmd, "keystorePath", options);

    KeyStore ks = loadKeyStore(ksPath, ttRead);

    logger.info("...loaded");

    if (action.equalsIgnoreCase("import-sp-metadata")) {

        importMetaData(options, cmd, unisonXMLFile, ttRead, ttWrite, ksPath, ks);
    } else if (action.equalsIgnoreCase("export-sp-metadata")) {
        exportSPMetaData(options, cmd, ttRead, ks);

    } else if (action.equalsIgnoreCase("print-secretkey")) {
        printSecreyKey(options, cmd, ttRead, ks);
    } else if (action.equalsIgnoreCase("import-secretkey")) {
        importSecreyKey(options, cmd, ttRead, ks, ksPath);
    } else if (action.equalsIgnoreCase("create-secretkey")) {
        Security.addProvider(new BouncyCastleProvider());
        logger.info("Creating AES-256 secret key");
        String alias = loadOption(cmd, "alias", options);
        logger.info("Alias : '" + alias + "'");
        KeyGenerator kg = KeyGenerator.getInstance("AES", "BC");
        kg.init(256, new SecureRandom());
        SecretKey sk = kg.generateKey();
        ks.setKeyEntry(alias, sk, ttRead.getKeyStorePassword().toCharArray(), null);
        logger.info("Saving key");
        ks.store(new FileOutputStream(ksPath), ttRead.getKeyStorePassword().toCharArray());
        logger.info("Finished");
    } else if (action.equalsIgnoreCase("export-secretkey")) {
        logger.info("Export Secret Key");

        logger.info("Loading key");
        String alias = loadOption(cmd, "alias", options);
        SecretKey key = (SecretKey) ks.getKey(alias, ttRead.getKeyStorePassword().toCharArray());
        logger.info("Loading new keystore path");
        String pathToNewKeystore = loadOption(cmd, "newKeystorePath", options);
        logger.info("Loading new keystore password");
        String ksPassword = loadOption(cmd, "newKeystorePassword", options);

        KeyStore newKS = KeyStore.getInstance("PKCS12");
        newKS.load(null, ttRead.getKeyStorePassword().toCharArray());
        newKS.setKeyEntry(alias, key, ksPassword.toCharArray(), null);
        newKS.store(new FileOutputStream(pathToNewKeystore), ksPassword.toCharArray());
        logger.info("Exported");
    } else if (action.equalsIgnoreCase("import-idp-metadata")) {
        importIdpMetadata(options, cmd, unisonXMLFile, ttRead, ttWrite, ksPath, ks);

    } else if (action.equalsIgnoreCase("export-idp-metadata")) {
        exportIdPMetadata(options, cmd, ttRead, ks);
    } else if (action.equalsIgnoreCase("clear-dlq")) {
        logger.info("Getting the DLQ Name...");
        String dlqName = loadOption(cmd, "dlqName", options);
        QueUtils.emptyDLQ(ttRead, dlqName);
    } else if (action.equalsIgnoreCase("upgradeFrom106")) {
        logger.info("Upgrading OpenUnison's configuration from 1.0.6");

        String backupFileName = unisonXMLFile + ".bak";

        logger.info("Backing up to '" + backupFileName + "'");

        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(unisonXMLFile)));
        PrintWriter out = new PrintWriter(new FileOutputStream(backupFileName));
        String line = null;
        while ((line = in.readLine()) != null) {
            out.println(line);
        }
        out.flush();
        out.close();
        in.close();

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        AddChoiceToTasks.convert(new FileInputStream(unisonXMLFile), bout);
        FileOutputStream fsout = new FileOutputStream(unisonXMLFile);
        fsout.write(bout.toByteArray());
        fsout.flush();
        fsout.close();

    }

}

From source file:org.apache.abdera.security.util.KeyHelper.java

@SuppressWarnings("unchecked")
public static <T extends Key> T getKey(KeyStore ks, String alias, String pass)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
    return (T) ks.getKey(alias, pass.toCharArray());
}

From source file:Main.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private static String decryptStringImpl(Context context, final String encryptedText) {
    String plainText = null;/*from w  w  w . j  a v a  2  s .  co m*/
    try {
        final KeyStore keyStore = getKeyStore(context);

        PrivateKey privateKey = (PrivateKey) keyStore.getKey(KEY_ALIAS, null);

        String algorithm = ALGORITHM_OLD;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            algorithm = ALGORITHM;
        }
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        CipherInputStream cipherInputStream = new CipherInputStream(
                new ByteArrayInputStream(Base64.decode(encryptedText, Base64.DEFAULT)), cipher);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int b;
        while ((b = cipherInputStream.read()) != -1) {
            outputStream.write(b);
        }
        outputStream.close();
        plainText = outputStream.toString("UTF-8");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return plainText;
}

From source file:com.threerings.getdown.tools.Digester.java

/**
 * Creates a digest file in the specified application directory.
 *//*from w  w w  .j a va2s . co m*/
public static void signDigest(File appdir, File storePath, String storePass, String storeAlias)
        throws IOException, GeneralSecurityException {
    File inputFile = new File(appdir, Digest.DIGEST_FILE);
    File signatureFile = new File(appdir, Digest.DIGEST_FILE + Application.SIGNATURE_SUFFIX);

    FileInputStream storeInput = null, dataInput = null;
    FileOutputStream signatureOutput = null;
    try {
        // initialize the keystore
        KeyStore store = KeyStore.getInstance("JKS");
        storeInput = new FileInputStream(storePath);
        store.load(storeInput, storePass.toCharArray());
        PrivateKey key = (PrivateKey) store.getKey(storeAlias, storePass.toCharArray());

        // sign the digest file
        Signature sig = Signature.getInstance("SHA1withRSA");
        dataInput = new FileInputStream(inputFile);
        byte[] buffer = new byte[8192];
        int length;

        sig.initSign(key);
        while ((length = dataInput.read(buffer)) != -1) {
            sig.update(buffer, 0, length);
        }

        // Write out the signature
        signatureOutput = new FileOutputStream(signatureFile);
        String signed = new String(Base64.encodeBase64(sig.sign()));
        signatureOutput.write(signed.getBytes("utf8"));

    } finally {
        StreamUtil.close(signatureOutput);
        StreamUtil.close(dataInput);
        StreamUtil.close(storeInput);
    }
}