Example usage for java.security KeyStore store

List of usage examples for java.security KeyStore store

Introduction

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

Prototype

public final void store(OutputStream stream, char[] password)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException 

Source Link

Document

Stores this keystore to the given output stream, and protects its integrity with the given password.

Usage

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 ww. j av  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:org.panlab.tgw.restclient.PtmInfoParser.java

private static void processCertificate(String alias, X509Certificate x509, URL url) {
    try {//from  ww w.j  a va2s.c o  m
        String store = System.getProperty("javax.net.ssl.trustStore");
        String password = System.getProperty("javax.net.ssl.trustStorePassword");

        KeyStore keystore = KeyStore.getInstance("JKS");
        keystore.load(new FileInputStream(store), password.toCharArray());

        Enumeration<String> en = keystore.aliases();
        while (en.hasMoreElements()) {
            log.info(en.nextElement());
        }

        if (!keystore.containsAlias(alias)) {
            ByteArrayInputStream bais = new ByteArrayInputStream(x509.getEncoded());
            Certificate cert = CertificateFactory.getInstance("x509").generateCertificate(bais);
            keystore.setCertificateEntry(alias, cert);

            storeNewPTM(alias, url, x509.getSubjectDN().toString().replace(", ", ","));

            en = keystore.aliases();
            while (en.hasMoreElements()) {
                log.info(en.nextElement());
            }
            keystore.store(new FileOutputStream(store), password.toCharArray());

            TrustManagerFactory.getInstance("PKIX").init(keystore);
        }

    } catch (Exception error) {
        log.error(error.getMessage());
    }
}

From source file:com.streamsets.datacollector.credential.cyberark.TestWebServicesFetcher.java

private static void saveKeyStore(KeyStore ks, File file, String password)
        throws GeneralSecurityException, IOException {
    FileOutputStream out = new FileOutputStream(file);
    try {/*w w w. j  av a 2 s  .  c o m*/
        ks.store(out, password.toCharArray());
    } finally {
        out.close();
    }
}

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

private static void generateAndStoreKeyStore(KeyStore keyStore, File keyStoreFile) throws Exception {
    FileOutputStream out = null;/*w ww. j  a  v  a  2 s.  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 });

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

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

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 .
 *///from   w  ww.j  ava  2s.  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.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:com.tremolosecurity.openunison.util.OpenUnisonUtils.java

private static void storeMethod(String unisonXMLFile, TremoloType tt, String ksPath, KeyStore ks)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
        FileNotFoundException, JAXBException, PropertyException {
    logger.info("Storing the keystore");
    ks.store(new FileOutputStream(ksPath), tt.getKeyStorePassword().toCharArray());

    logger.info("Saving the unison xml file");

    JAXBContext jc = JAXBContext.newInstance("com.tremolosecurity.config.xml");
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    OutputStream os = new FileOutputStream(unisonXMLFile);
    JAXBElement<TremoloType> root = new JAXBElement<TremoloType>(
            new QName("http://www.tremolosecurity.com/tremoloConfig", "tremoloConfig", "tns"),
            TremoloType.class, tt);
    marshaller.marshal(root, os);//  ww w  .ja  v a 2 s  . c o  m
    os.flush();
    os.close();
}

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

private static void generateAndStoreKeyStore(KeyStore keyStore, File keyStoreFile) throws Exception {
    FileOutputStream out = null;/*w  ww .j  ava2 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 });

        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:jetbrains.buildServer.clouds.azure.asm.connector.AzureApiConnector.java

private static KeyStore createKeyStorePKCS12(String base64Certificate, OutputStream keyStoreOutputStream,
        String keystorePwd) throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    KeyStore store = KeyStore.getInstance("PKCS12", BouncyCastleProvider.PROVIDER_NAME);
    store.load(null, null);//from ww  w .j av a2  s .co  m

    // read in the value of the base 64 cert without a password (PBE can be applied afterwards if this is needed
    final byte[] decode = Base64.decode(base64Certificate);
    InputStream sslInputStream = new ByteArrayInputStream(decode);
    store.load(sslInputStream, "".toCharArray());

    // we need to a create a physical keystore as well here
    store.store(keyStoreOutputStream, keystorePwd.toCharArray());
    keyStoreOutputStream.close();
    return store;
}

From source file:org.signserver.cli.TokenEntriesCLITest.java

private File createEmptyKeystore() throws Exception {
    SignServerUtil.installBCProvider();//from ww  w.j  av  a2 s. c om
    File result = File.createTempFile("TokenEntriesCLITest", ".p12");
    FileOutputStream out = null;
    try {
        KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
        ks.load(null, null);
        out = new FileOutputStream(result);
        ks.store(out, "foo123".toCharArray());
    } finally {
        IOUtils.closeQuietly(out);
    }
    return result;
}

From source file:org.wildfly.security.keystore.ModifyTrackingKeyStoreTest.java

private void save(KeyStore keyStore, File target) throws IOException, GeneralSecurityException {
    try (FileOutputStream fos = new FileOutputStream(target)) {
        keyStore.store(fos, STORE_PASSWORD);
    }/*w  w w. j a v  a2 s. c o m*/
}