Example usage for java.security KeyStore setKeyEntry

List of usage examples for java.security KeyStore setKeyEntry

Introduction

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

Prototype

public final void setKeyEntry(String alias, Key key, char[] password, Certificate[] chain)
        throws KeyStoreException 

Source Link

Document

Assigns the given key to the given alias, protecting it with the given password.

Usage

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    String cacert = "mytest.cer";
    String lfcert = "lf_signed.cer";
    String lfstore = "lfkeystore";
    char[] lfstorepass = "wshr.ut".toCharArray();
    char[] lfkeypass = "wshr.ut".toCharArray();
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    FileInputStream in1 = new FileInputStream(cacert);
    java.security.cert.Certificate cac = cf.generateCertificate(in1);
    in1.close();/* w w w.  java2 s.co m*/
    FileInputStream in2 = new FileInputStream(lfcert);
    java.security.cert.Certificate lfc = cf.generateCertificate(in2);
    in2.close();
    java.security.cert.Certificate[] cchain = { lfc, cac };
    FileInputStream in3 = new FileInputStream(lfstore);
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(in3, lfstorepass);
    PrivateKey prk = (PrivateKey) ks.getKey("lf", lfkeypass);
    ks.setKeyEntry("lf_signed", prk, lfstorepass, cchain);
    FileOutputStream out4 = new FileOutputStream("lfnewstore");
    ks.store(out4, "newpass".toCharArray());
    out4.close();
}

From source file:org.openanzo.security.keystore.TestSecretKeyEncoder.java

/**
 * Main method used to generate a keystore. Useful for bootstrapping the first time.
 * /*from w  w w. j a v  a 2  s .  c  o  m*/
 * @param args
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    File file = new File("testKeystore");
    System.out.println("Generating new keystore to:" + file.getAbsolutePath());

    KeyStore keyStore = KeyStore.getInstance("JCEKS");
    keyStore.load(null, TEST_KEYSTORE_PASSWORD);
    KeyGenerator kgen = KeyGenerator.getInstance(ALGORITHM);
    Key key = kgen.generateKey();
    keyStore.setKeyEntry(KEY_NAME, key, TEST_KEYSTORE_PASSWORD, new Certificate[0]);
    keyStore.store(FileUtils.openOutputStream(file), TEST_KEYSTORE_PASSWORD);
    System.out.println("Done generating keystore.");
}

From source file:com.streamreduce.util.CAGenerator.java

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

    KeyStore store = KeyStore.getInstance("JKS");
    //        store.load(CAGenerator.class.getResourceAsStream("/mmc-keystore.jks"), "ion-mmc".toCharArray());
    store.load(null);// ww w .  ja v a 2  s  .  c om

    KeyPair keypair = generateKeyPair();

    X509Certificate cert = generateCACert(keypair);

    char[] password = "nodeable-agent".toCharArray();
    store.setKeyEntry("nodeable", keypair.getPrivate(), password, new Certificate[] { cert });
    store.store(new FileOutputStream("nodeable-keystore.jks"), password);
    byte[] certBytes = getCertificateAsBytes(cert);
    FileOutputStream output = new FileOutputStream("nodeable.crt");
    IOUtils.copy(new ByteArrayInputStream(certBytes), output);
    output.close();
}

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  ww.  j  av a2  s .c  om
    }

    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: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) {/* w  ww  .  ja va2 s.co 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:ImportKey.java

/**
 * <p>//w w  w  . java  2 s . c o  m
 * Takes two file names for a key and the certificate for the key, and
 * imports those into a keystore. Optionally it takes an alias for the key.
 * <p>
 * The first argument is the filename for the key. The key should be in
 * PKCS8-format.
 * <p>
 * The second argument is the filename for the certificate for the key.
 * <p>
 * If a third argument is given it is used as the alias. If missing, the key
 * is imported with the alias importkey
 * <p>
 * The name of the keystore file can be controlled by setting the keystore
 * property (java -Dkeystore=mykeystore). If no name is given, the file is
 * named <code>keystore.ImportKey</code> and placed in your home directory.
 * 
 * @param args
 *            [0] Name of the key file, [1] Name of the certificate file [2]
 *            Alias for the key.
 **/
public static void main(String args[]) {

    // change this if you want another password by default
    String keypass = "password";

    // change this if you want another alias by default
    String defaultalias = "tomcat";

    // change this if you want another keystorefile by default
    String keystorename = null;

    // parsing command line input
    String keyfile = "";
    String certfile = "";
    if (args.length < 3 || args.length > 4) {
        System.out.println("Usage: java comu.ImportKey keystore keyfile certfile [alias]");
        System.exit(0);
    } else {
        keystorename = args[0];
        keyfile = args[1];
        certfile = args[2];
        if (args.length > 3)
            defaultalias = args[3];
    }

    try {
        // initializing and clearing keystore
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        ks.load(null, keypass.toCharArray());
        System.out.println("Using keystore-file : " + keystorename);
        ks.store(new FileOutputStream(keystorename), keypass.toCharArray());
        ks.load(new FileInputStream(keystorename), keypass.toCharArray());

        // loading Key
        InputStream fl = fullStream(keyfile);
        byte[] key = new byte[fl.available()];
        KeyFactory kf = KeyFactory.getInstance("RSA");
        fl.read(key, 0, fl.available());
        fl.close();
        PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(key);
        PrivateKey ff = kf.generatePrivate(keysp);

        // loading CertificateChain
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream certstream = fullStream(certfile);

        Collection c = cf.generateCertificates(certstream);
        Certificate[] certs = new Certificate[c.toArray().length];

        if (c.size() == 1) {
            certstream = fullStream(certfile);
            System.out.println("One certificate, no chain.");
            Certificate cert = cf.generateCertificate(certstream);
            certs[0] = cert;
        } else {
            System.out.println("Certificate chain length: " + c.size());
            certs = (Certificate[]) c.toArray(new Certificate[c.size()]);
        }

        // storing keystore
        ks.setKeyEntry(defaultalias, ff, keypass.toCharArray(), certs);
        System.out.println("Key and certificate stored.");
        System.out.println("Alias:" + defaultalias + "  Password:" + keypass);
        ks.store(new FileOutputStream(keystorename), keypass.toCharArray());
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    String keystoreFile = "keyStoreFile.bin";
    String caAlias = "caAlias";
    String certToSignAlias = "cert";
    String newAlias = "newAlias";

    char[] password = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' };
    char[] caPassword = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' };
    char[] certPassword = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' };

    FileInputStream input = new FileInputStream(keystoreFile);
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(input, password);//  w w  w .j  a v  a  2s .  c  om
    input.close();

    PrivateKey caPrivateKey = (PrivateKey) keyStore.getKey(caAlias, caPassword);
    java.security.cert.Certificate caCert = keyStore.getCertificate(caAlias);

    byte[] encoded = caCert.getEncoded();
    X509CertImpl caCertImpl = new X509CertImpl(encoded);

    X509CertInfo caCertInfo = (X509CertInfo) caCertImpl.get(X509CertImpl.NAME + "." + X509CertImpl.INFO);

    X500Name issuer = (X500Name) caCertInfo.get(X509CertInfo.SUBJECT + "." + CertificateIssuerName.DN_NAME);

    java.security.cert.Certificate cert = keyStore.getCertificate(certToSignAlias);
    PrivateKey privateKey = (PrivateKey) keyStore.getKey(certToSignAlias, certPassword);
    encoded = cert.getEncoded();
    X509CertImpl certImpl = new X509CertImpl(encoded);
    X509CertInfo certInfo = (X509CertInfo) certImpl.get(X509CertImpl.NAME + "." + X509CertImpl.INFO);

    Date firstDate = new Date();
    Date lastDate = new Date(firstDate.getTime() + 365 * 24 * 60 * 60 * 1000L);
    CertificateValidity interval = new CertificateValidity(firstDate, lastDate);

    certInfo.set(X509CertInfo.VALIDITY, interval);

    certInfo.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber((int) (firstDate.getTime() / 1000)));

    certInfo.set(X509CertInfo.ISSUER + "." + CertificateSubjectName.DN_NAME, issuer);

    AlgorithmId algorithm = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid);
    certInfo.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, algorithm);
    X509CertImpl newCert = new X509CertImpl(certInfo);

    newCert.sign(caPrivateKey, "MD5WithRSA");

    keyStore.setKeyEntry(newAlias, privateKey, certPassword, new java.security.cert.Certificate[] { newCert });

    FileOutputStream output = new FileOutputStream(keystoreFile);
    keyStore.store(output, password);
    output.close();

}

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);
    }/*w w w . j av  a  2s .com*/

    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:com.google.jenkins.plugins.credentials.oauth.P12ServiceAccountConfigTestUtil.java

private static KeyStore createKeyStore(KeyPair keyPair) throws KeyStoreException, CertificateException,
        NoSuchAlgorithmException, IOException, OperatorCreationException, NoSuchProviderException {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(null, null);/*from   w w  w . j  a  v  a2  s  . com*/
    keyStore.setKeyEntry(DEFAULT_P12_ALIAS, keyPair.getPrivate(), DEFAULT_P12_SECRET.toCharArray(),
            new Certificate[] { generateCertificate(keyPair) });
    return keyStore;
}

From source file:com.aqnote.shared.cryptology.cert.util.KeyStoreUtil.java

public static KeyStore getPKCS12KeyStore(String alias, Certificate[] certChain, KeyPair keyPair, char[] passwd)
        throws Exception {

    PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) keyPair.getPrivate();
    bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias));
    SubjectKeyIdentifier pubKeyId = new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic());
    bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, pubKeyId);
    KeyStore store = KeyStore.getInstance(KEY_STORE_TYPE, JCE_PROVIDER);
    store.load(null, null);/*from www.  ja va2s .c  o m*/
    store.setKeyEntry(alias, keyPair.getPrivate(), passwd, certChain);
    return store;
}