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:com.piusvelte.taplock.server.TapLockServer.java

protected static void setPassphrase(String passphrase) {
    Properties prop = new Properties();
    try {/* ww  w .  ja  v  a 2s  .  c  o  m*/
        prop.load(new FileInputStream(sProperties));
        prop.setProperty(sPassphraseKey, passphrase);
        prop.store(new FileOutputStream(sProperties), null);
    } catch (FileNotFoundException e) {
        writeLog("prop load: " + e.getMessage());
    } catch (IOException e) {
        writeLog("prop load: " + e.getMessage());
    }
    if (OS == OS_WIN) {
        KeyStore ks = getKeyStore();
        if (ks != null) {
            SecretKey sk = getSecretKey(ks);
            if (ks != null) {
                try {
                    ks.setKeyEntry(TAP_LOCK, sk, sPassphrase.toCharArray(), null);
                    ks.store(new FileOutputStream(sKeystore), sPassphrase.toCharArray());
                } catch (KeyStoreException e) {
                    writeLog("change key password: " + e.getMessage());
                } catch (NoSuchAlgorithmException e) {
                    writeLog("change key password: " + e.getMessage());
                } catch (CertificateException e) {
                    writeLog("change key password: " + e.getMessage());
                } catch (FileNotFoundException e) {
                    writeLog("change key password: " + e.getMessage());
                } catch (IOException e) {
                    writeLog("change key password: " + e.getMessage());
                }
            }
        }
    }
    sPassphrase = passphrase;
}

From source file:org.panbox.core.pairing.file.PanboxFilePairingUtils.java

/**
 * Stores a pairing file at the specified path for the specified device and
 * type//from  ww  w  . j  a  v  a 2s .  c om
 * 
 * @param outputFile
 *            Pairing file to be saved
 * @param devicename
 *            Name of the device that should be paired
 * @param password
 *            Password of the identity
 */
public static PanboxFilePairingWriteReturnContainer storePairingFile(File outputFile, String devicename,
        char[] password, PairingType type, DeviceType devType, String eMail, String firstName, String lastName,
        PrivateKey privEncKey, X509Certificate encCert, PrivateKey privSignKey, X509Certificate signCert,
        Map<String, X509Certificate> devices, Collection<VCard> contacts)
        throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException {
    logger.debug("PanboxFilePairingUtils : storePairingFile : Storing pairing container to: "
            + outputFile.getAbsolutePath());

    ZipArchiveOutputStream out = new ZipArchiveOutputStream(new FileOutputStream(outputFile));

    // 1. add device name to pairing file
    ZipArchiveEntry entry = new ZipArchiveEntry("devicename");
    entry.setSize(devicename.getBytes().length);
    out.putArchiveEntry(entry);

    out.write(devicename.getBytes());
    out.flush();

    out.closeArchiveEntry();

    // 2. add device name to pairing file
    entry = new ZipArchiveEntry("email");
    entry.setSize(eMail.getBytes().length);
    out.putArchiveEntry(entry);

    out.write(eMail.getBytes());
    out.flush();

    out.closeArchiveEntry();

    // 3. add device name to pairing file
    entry = new ZipArchiveEntry("firstname");
    entry.setSize(firstName.getBytes().length);
    out.putArchiveEntry(entry);

    out.write(firstName.getBytes());
    out.flush();

    out.closeArchiveEntry();

    // 4. add device name to pairing file
    entry = new ZipArchiveEntry("lastname");
    entry.setSize(lastName.getBytes().length);
    out.putArchiveEntry(entry);

    out.write(lastName.getBytes());
    out.flush();

    out.closeArchiveEntry();

    // 5. generate and add a new device key + cert for the newly device
    KeyPair devKey = CryptCore.generateKeypair();
    X509Certificate devCert = CryptCore.createSelfSignedX509Certificate(devKey.getPrivate(), devKey.getPublic(),
            new PairingIPersonDummy(eMail, firstName, lastName));

    KeyStore devKeyStore = KeyStore.getInstance("PKCS12");
    devKeyStore.load(null, null);
    devKeyStore.setKeyEntry(devicename, (Key) devKey.getPrivate(), password, new Certificate[] { devCert });
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    devKeyStore.store(baos, password);
    baos.flush();

    byte[] data = baos.toByteArray();
    entry = new ZipArchiveEntry("devicekey.p12");
    entry.setSize(data.length);
    out.putArchiveEntry(entry);
    out.write(data);
    out.flush();

    out.closeArchiveEntry();

    // 6. add device certs and names for all known devices

    baos = new ByteArrayOutputStream();
    ByteArrayOutputStream deviceNamesFile = new ByteArrayOutputStream();
    KeyStore deviceKeyStore = KeyStore.getInstance("BKS");
    deviceKeyStore.load(null, null);
    int i = 0;

    for (Entry<String, X509Certificate> device : devices.entrySet()) {
        deviceKeyStore.setCertificateEntry("device" + i, device.getValue());
        deviceNamesFile.write(("device" + i + DELIMITER + device.getKey() + "\n").getBytes());
        ++i;
    }

    deviceKeyStore.store(baos, password);
    baos.flush();
    deviceNamesFile.flush();

    byte[] data2 = deviceNamesFile.toByteArray();
    entry = new ZipArchiveEntry("knownDevices.list");
    entry.setSize(data2.length);
    out.putArchiveEntry(entry);
    out.write(data2);
    out.flush();

    data = baos.toByteArray();
    entry = new ZipArchiveEntry("knownDevices.bks");
    entry.setSize(data.length);
    out.putArchiveEntry(entry);
    out.write(data);
    out.flush();

    // 7. add vcard for all known contacts

    File tempContacts = File.createTempFile("panboxContacts", null);
    AbstractAddressbookManager.exportContacts(contacts, tempContacts);
    FileInputStream fis = new FileInputStream(tempContacts);
    data = new byte[(int) tempContacts.length()];
    fis.read(data);
    fis.close();
    tempContacts.delete();

    entry = new ZipArchiveEntry("contacts.vcard");
    entry.setSize(data.length);
    out.putArchiveEntry(entry);
    out.write(data);
    out.flush();

    // 8. add owner certs or keys in case of main/restricted
    KeyStore ownerKeyStore = null;
    if (type == PairingType.MASTER) {
        ownerKeyStore = KeyStore.getInstance("PKCS12");
        ownerKeyStore.load(null, null);
        ownerKeyStore.setKeyEntry("ownerEncKey", privEncKey, password, new Certificate[] { encCert });
        ownerKeyStore.setKeyEntry("ownerSignKey", privSignKey, password, new Certificate[] { signCert });
        entry = new ZipArchiveEntry("ownerKeys.p12");
    } else {
        ownerKeyStore = KeyStore.getInstance("BKS");
        ownerKeyStore.load(null, null);
        ownerKeyStore.setCertificateEntry("ownerEncCert", encCert);
        ownerKeyStore.setCertificateEntry("ownerSignCert", signCert);
        entry = new ZipArchiveEntry("ownerCerts.bks");
    }
    baos = new ByteArrayOutputStream();
    ownerKeyStore.store(baos, password);
    baos.flush();

    data = baos.toByteArray();
    entry.setSize(data.length);
    out.putArchiveEntry(entry);
    out.write(data);
    out.flush();

    out.closeArchiveEntry();

    out.flush();
    out.close();
    logger.debug("PanboxFilePairingUtils : storePairingFile : Storing pairing container finished.");

    return new PanboxFilePairingWriteReturnContainer(devicename, devCert, devType);
}

From source file:org.wso2.emm.agent.utils.CommonUtils.java

/**
 * Generates keys, CSR and certificates for the devices.
 * @param context - Application context.
 * @param listener - DeviceCertCreationListener which provide device .
 *///from   w w w  .ja v  a  2  s.c o  m
public static void generateDeviceCertificate(final Context context, final DeviceCertCreationListener listener)
        throws AndroidAgentException {

    if (context.getFileStreamPath(Constants.DEVICE_CERTIFCATE_NAME).exists()) {
        try {
            listener.onDeviceCertCreated(
                    new BufferedInputStream(context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME)));
        } catch (FileNotFoundException e) {
            Log.e(TAG, e.getMessage());
        }
    } else {

        try {
            ServerConfig utils = new ServerConfig();
            final KeyPair deviceKeyPair = KeyPairGenerator.getInstance(Constants.DEVICE_KEY_TYPE)
                    .generateKeyPair();
            X500Principal subject = new X500Principal(Constants.DEVICE_CSR_INFO);
            PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Constants.DEVICE_KEY_ALGO, subject,
                    deviceKeyPair.getPublic(), null, deviceKeyPair.getPrivate());

            EndPointInfo endPointInfo = new EndPointInfo();
            endPointInfo.setHttpMethod(org.wso2.emm.agent.proxy.utils.Constants.HTTP_METHODS.POST);
            endPointInfo.setEndPoint(utils.getAPIServerURL(context) + Constants.SCEP_ENDPOINT);
            endPointInfo.setRequestParams(Base64.encodeToString(csr.getEncoded(), Base64.DEFAULT));

            new APIController().invokeAPI(endPointInfo, new APIResultCallBack() {
                @Override
                public void onReceiveAPIResult(Map<String, String> result, int requestCode) {
                    try {
                        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
                        InputStream in = new ByteArrayInputStream(
                                Base64.decode(result.get("response"), Base64.DEFAULT));
                        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in);
                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                        KeyStore keyStore = KeyStore.getInstance("PKCS12");
                        keyStore.load(null);
                        keyStore.setKeyEntry(Constants.DEVICE_CERTIFCATE_ALIAS,
                                (Key) deviceKeyPair.getPrivate(),
                                Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray(),
                                new java.security.cert.Certificate[] { cert });
                        keyStore.store(byteArrayOutputStream,
                                Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray());
                        FileOutputStream outputStream = context.openFileOutput(Constants.DEVICE_CERTIFCATE_NAME,
                                Context.MODE_PRIVATE);
                        outputStream.write(byteArrayOutputStream.toByteArray());
                        byteArrayOutputStream.close();
                        outputStream.close();
                        try {
                            listener.onDeviceCertCreated(new BufferedInputStream(
                                    context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME)));
                        } catch (FileNotFoundException e) {
                            Log.e(TAG, e.getMessage());
                        }
                    } catch (CertificateException e) {
                        Log.e(TAG, e.getMessage());
                    } catch (KeyStoreException e) {
                        e.printStackTrace();
                    } catch (NoSuchAlgorithmException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }, Constants.SCEP_REQUEST_CODE, context, true);

        } catch (NoSuchAlgorithmException e) {
            throw new AndroidAgentException("No algorithm for key generation", e);
        } catch (SignatureException e) {
            throw new AndroidAgentException("Invalid Signature", e);
        } catch (NoSuchProviderException e) {
            throw new AndroidAgentException("Invalid provider", e);
        } catch (InvalidKeyException e) {
            throw new AndroidAgentException("Invalid key", e);
        }

    }

}

From source file:com.cloud.utils.security.CertificateHelper.java

public static byte[] buildAndSaveKeystore(List<Ternary<String, String, String>> certs, String storePassword)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
        InvalidKeySpecException {
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, storePassword != null ? storePassword.toCharArray() : null);

    //name,cert,key
    for (Ternary<String, String, String> cert : certs) {
        if (cert.third() == null) {
            Certificate c = buildCertificate(cert.second());
            ks.setCertificateEntry(cert.first(), c);
        } else {//from   www  .ja  v  a 2  s.c om
            Certificate[] c = new Certificate[certs.size()];
            int i = certs.size();
            for (Ternary<String, String, String> ct : certs) {
                c[i - 1] = buildCertificate(ct.second());
                i--;
            }
            ks.setKeyEntry(cert.first(), buildPrivateKey(cert.third()),
                    storePassword != null ? storePassword.toCharArray() : null, c);
        }
    }

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ks.store(os, storePassword != null ? storePassword.toCharArray() : null);
    os.close();
    return os.toByteArray();
}

From source file:net.firejack.platform.web.security.x509.KeyUtils.java

public static void add(File keystore, KeyPair pair, String domain) {
    if (keystore == null) {
        throw new IllegalArgumentException("Key Store file should not be null.");
    }/*from w w  w. j  av a2 s .com*/

    try {
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        if (keystore.exists()) {
            FileInputStream stream = new FileInputStream(keystore);
            ks.load(stream, SECRET);
            IOUtils.closeQuietly(stream);
        } else {
            ks.load(null, SECRET);
        }

        if (!ks.containsAlias(ALIAS)) {
            X509Certificate certificate = generateCertificate(domain, 1, pair);

            ks.setKeyEntry(ALIAS, pair.getPrivate(), SECRET, new Certificate[] { certificate });

            FileOutputStream stream = new FileOutputStream(keystore);
            ks.store(stream, SECRET);
            IOUtils.closeQuietly(stream);
        }
    } catch (Throwable th) {
        logger.error("Failed to initialize key store");
        throw new OpenFlameRuntimeException(th.getMessage(), th);
    }
}

From source file:org.wso2.iot.agent.utils.CommonUtils.java

/**
 * Generates keys, CSR and certificates for the devices.
 * @param context - Application context.
 * @param listener - DeviceCertCreationListener which provide device .
 *//*  w ww .  j a v a 2s .  co  m*/
public static void generateDeviceCertificate(final Context context, final DeviceCertCreationListener listener)
        throws AndroidAgentException {

    if (context.getFileStreamPath(Constants.DEVICE_CERTIFCATE_NAME).exists()) {
        try {
            listener.onDeviceCertCreated(
                    new BufferedInputStream(context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME)));
        } catch (FileNotFoundException e) {
            Log.e(TAG, e.getMessage());
        }
    } else {

        try {
            ServerConfig utils = new ServerConfig();
            final KeyPair deviceKeyPair = KeyPairGenerator.getInstance(Constants.DEVICE_KEY_TYPE)
                    .generateKeyPair();
            X500Principal subject = new X500Principal(Constants.DEVICE_CSR_INFO);
            PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Constants.DEVICE_KEY_ALGO, subject,
                    deviceKeyPair.getPublic(), null, deviceKeyPair.getPrivate());

            EndPointInfo endPointInfo = new EndPointInfo();
            endPointInfo.setHttpMethod(org.wso2.iot.agent.proxy.utils.Constants.HTTP_METHODS.POST);
            endPointInfo.setEndPoint(utils.getAPIServerURL(context) + Constants.SCEP_ENDPOINT);
            endPointInfo.setRequestParams(Base64.encodeToString(csr.getEncoded(), Base64.DEFAULT));

            new APIController().invokeAPI(endPointInfo, new APIResultCallBack() {
                @Override
                public void onReceiveAPIResult(Map<String, String> result, int requestCode) {
                    try {
                        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
                        InputStream in = new ByteArrayInputStream(
                                Base64.decode(result.get("response"), Base64.DEFAULT));
                        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in);
                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                        KeyStore keyStore = KeyStore.getInstance("PKCS12");
                        keyStore.load(null);
                        keyStore.setKeyEntry(Constants.DEVICE_CERTIFCATE_ALIAS,
                                (Key) deviceKeyPair.getPrivate(),
                                Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray(),
                                new java.security.cert.Certificate[] { cert });
                        keyStore.store(byteArrayOutputStream,
                                Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray());
                        FileOutputStream outputStream = context.openFileOutput(Constants.DEVICE_CERTIFCATE_NAME,
                                Context.MODE_PRIVATE);
                        outputStream.write(byteArrayOutputStream.toByteArray());
                        byteArrayOutputStream.close();
                        outputStream.close();
                        try {
                            listener.onDeviceCertCreated(new BufferedInputStream(
                                    context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME)));
                        } catch (FileNotFoundException e) {
                            Log.e(TAG, e.getMessage());
                        }
                    } catch (CertificateException | KeyStoreException | NoSuchAlgorithmException
                            | IOException e) {
                        Log.e(TAG, e.getMessage(), e);
                    }
                }
            }, Constants.SCEP_REQUEST_CODE, context, true);

        } catch (NoSuchAlgorithmException e) {
            throw new AndroidAgentException("No algorithm for key generation", e);
        } catch (SignatureException e) {
            throw new AndroidAgentException("Invalid Signature", e);
        } catch (NoSuchProviderException e) {
            throw new AndroidAgentException("Invalid provider", e);
        } catch (InvalidKeyException e) {
            throw new AndroidAgentException("Invalid key", e);
        }
    }
}

From source file:it.cnr.icar.eric.client.xml.registry.util.CertificateUtil.java

/**
 * Generate a self signed certificate and store it in the keystore.
 * //from w w  w.j  a v a  2  s .  c  o  m
 * @param userRegInfo
 * @throws JAXRException
 */
public static void generateRegistryIssuedCertificate(UserRegistrationInfo userRegInfo) throws JAXRException {
    User user = userRegInfo.getUser();
    LifeCycleManager lcm = user.getLifeCycleManager();
    String dname = getDNameFromUser(userRegInfo);
    File keystoreFile = KeystoreUtil.getKeystoreFile();
    KeystoreUtil.createKeystoreDirectory(keystoreFile);
    String keystoreType = ProviderProperties.getInstance().getProperty("jaxr-ebxml.security.storetype", "JKS");
    String storePassStr = new String(userRegInfo.getStorePassword());
    String keyPassStr = new String(userRegInfo.getKeyPassword());
    String alias = userRegInfo.getAlias();
    String keyAlg = "RSA"; // XWSS does not support DSA which is default is
    // KeyTool. Hmm. Weird.

    String[] args = { "-genkey", "-keyAlg", keyAlg, "-alias", alias, "-keypass", keyPassStr, "-keystore",
            keystoreFile.getAbsolutePath(), "-storepass", storePassStr, "-storetype", keystoreType, "-dname",
            dname };

    try {
        KeyTool keytool = new KeyTool();
        keytool.run(args, System.out);

        // Now load the KeyStore and get the cert
        FileInputStream fis = new FileInputStream(keystoreFile);

        KeyStore keyStore = KeyStore.getInstance(keystoreType);
        keyStore.load(fis, storePassStr.toCharArray());
        fis.close();

        X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
        Certificate[] certChain = getCertificateSignedByRegistry(lcm, cert);
        Key key = keyStore.getKey(alias, userRegInfo.getKeyPassword());

        // Now overwrite original cert with signed cert
        keyStore.deleteEntry(alias);

        // keyStore.setCertificateEntry(alias, cert);
        keyStore.setKeyEntry(alias, key, userRegInfo.getKeyPassword(), certChain);
        FileOutputStream fos = new java.io.FileOutputStream(keystoreFile);
        keyStore.store(fos, storePassStr.toCharArray());
        fos.flush();
        fos.close();
    } catch (Exception e) {
        throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.CertGenFailed"), e);
    }

    log.debug(JAXRResourceBundle.getInstance().getString("message.StoredUserInKeyStore",
            new Object[] { alias, keystoreFile.getAbsolutePath() }));

    try {
        // Export registry issued cert to certFile so it can be available
        // for import into a web browser for SSL access to registry
        exportRegistryIssuedCert(userRegInfo);
    } catch (Exception e) {
        String msg = JAXRResourceBundle.getInstance().getString(
                "message.UnableToExportCertificateSeeNextExceptionNoteThatThisFeatureRequiresUseOfJDK5");
        log.warn(msg, e);
        // Do not throw exception as user reg can be done despite not
        // exporting the p12 file for the web browser.
    }
}

From source file:nl.surfnet.spring.security.opensaml.util.KeyStoreUtil.java

/**
 * Append a certificate and private key to a keystore.
 *
 * @param keyStore        where to append the certificate and private key to
 * @param keyAlias        the alias of the key
 * @param certificateInputStream the inputStream containing the certificate in the PEM format
 * @param privatekeyInputStream  the input stream containing the private key in the DER format
 * @param password        the password on the key
 *                        <p/>/*ww  w . j av  a  2  s. co m*/
 *                        Generate your private key: openssl genrsa -out something.key 1024
 *                        <p/>
 *                        Show the PEM private key: openssl asn1parse -inform pem -dump -i
 *                        -in something.key
 *                        <p/>
 *                        Translate the key to pkcs8 DER format: openssl pkcs8 -topk8
 *                        -inform PEM -outform DER -in something.key -nocrypt >
 *                        something.pkcs8.der
 *                        <p/>
 *                        Show the DER private key: openssl asn1parse -inform der -dump -i
 *                        -in something.pkcs8.der
 *                        <p/>
 *                        Generate a certificate request: openssl req -new -key
 *                        something.key -out something.csr
 *                        <p/>
 *                        Generate a certificate: openssl x509 -req -days 365 -in
 *                        something.csr -signkey something.key -out something.crt
 */

public static void appendKeyToKeyStore(KeyStore keyStore, String keyAlias, InputStream certificateInputStream,
        InputStream privatekeyInputStream, char[] password) throws IOException {

    CertificateFactory certFact;
    Certificate cert;
    try {
        certFact = CertificateFactory.getInstance("X.509");
        cert = certFact.generateCertificate(certificateInputStream);
    } catch (CertificateException e) {
        throw new RuntimeException("Could not instantiate cert", e);
    }
    ArrayList<Certificate> certs = new ArrayList<Certificate>();
    certs.add(cert);

    byte[] privKeyBytes = IOUtils.toByteArray(privatekeyInputStream);

    try {
        KeySpec ks = new PKCS8EncodedKeySpec(privKeyBytes);
        RSAPrivateKey privKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(ks);
        keyStore.setKeyEntry(keyAlias, privKey, password, certs.toArray(new Certificate[certs.size()]));
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException(e);
    } catch (KeyStoreException e) {
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.wisdom.framework.vertx.ssl.FakeKeyStore.java

private static void generateAndStoreKeyStore(KeyStore keyStore, File keyStoreFile) throws Exception {
    FileOutputStream out = null;//from www .ja  v  a 2s.  c om
    try {
        LOGGER.info("Generating HTTPS key pair in " + keyStoreFile.getAbsolutePath() + " - this may take some"
                + " time. If nothing happens, try moving the mouse/typing on the keyboard to generate some entropy.");

        // Generate the key pair
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        // Generate a self signed certificate
        X509Certificate cert = createSelfSignedCertificate(keyPair);

        // Create the key store, first set the store pass
        keyStore.load(null, "".toCharArray());
        keyStore.setKeyEntry("wisdom-generated", keyPair.getPrivate(), "".toCharArray(),
                new X509Certificate[] { cert });

        keyStoreFile.getParentFile().mkdirs();
        out = new FileOutputStream(keyStoreFile);
        keyStore.store(out, "".toCharArray());

        LOGGER.info("Key Store generated in " + keyStoreFile.getAbsoluteFile());
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:org.wisdom.engine.ssl.FakeKeyStore.java

private static void generateAndStoreKeyStore(KeyStore keyStore, File keyStoreFile) throws Exception {
    FileOutputStream out = null;/*from w w w. j  av a 2  s . c  o  m*/
    try {
        LOGGER.info("Generating HTTPS key pair in " + keyStoreFile.getAbsolutePath() + " - this may take some"
                + " time. If nothing happens, try moving the mouse/typing on the keyboard to generate some entropy.");

        // Generate the key pair
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        // Generate a self signed certificate
        X509Certificate cert = createSelfSignedCertificate(keyPair);

        // Create the key store, first set the store pass
        keyStore.load(null, "".toCharArray());
        keyStore.setKeyEntry("wisdom-generated", keyPair.getPrivate(), "".toCharArray(),
                new X509Certificate[] { cert });

        out = new FileOutputStream(keyStoreFile);
        keyStore.store(out, "".toCharArray());

        LOGGER.info("Key Store generated in " + keyStoreFile.getAbsoluteFile());
    } finally {
        IOUtils.closeQuietly(out);
    }
}