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:com.solace.samples.cloudfoundry.securesession.controller.SolaceController.java

/**
 * This utility function installs a certificate into the JRE's trusted
 * store. Normally you would not do this, but this is provided to
 * demonstrate how to use TLS, and have the client validate a self-signed
 * server certificate./*from   ww  w .j  a va2  s .c  om*/
 *
 * @throws Exception
 */
private static void importCertificate() throws Exception {

    File file = new File(CERTIFICATE_FILE_NAME);
    logger.info("Loading certificate from " + file.getAbsolutePath());

    // This loads the KeyStore from the default location
    // (i.e. default for a Clound Foundry app) using the default password.
    FileInputStream is = new FileInputStream(TRUST_STORE);
    char[] password = TRUST_STORE_PASSWORD.toCharArray();
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(is, password);
    is.close();

    // Create an ByteArrayInputStream stream from the
    FileInputStream fis = new FileInputStream(CERTIFICATE_FILE_NAME);
    DataInputStream dis = new DataInputStream(fis);
    byte[] bytes = new byte[dis.available()];
    dis.readFully(bytes);
    dis.close();
    ByteArrayInputStream certstream = new ByteArrayInputStream(bytes);

    // This takes that Byte Array and creates a certificate out of it.
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    Certificate certs = cf.generateCertificate(certstream);

    // Finally, store the new certificate in the keystore.
    keystore.setCertificateEntry(CERTIFICATE_ALIAS, certs);

    // Save the new keystore contents
    FileOutputStream out = new FileOutputStream(TRUST_STORE);
    keystore.store(out, password);
    out.close();

}

From source file:com.youTransactor.uCube.mdm.MDMManager.java

public boolean setSSLCertificat(Context context, KeyStore sslKeystore) {
    try {/*from  w  w w  .  j  ava 2s  .  co m*/
        FileOutputStream out = context.openFileOutput(KEYSTORE_CLIENT_FILENAME, Context.MODE_PRIVATE);
        sslKeystore.store(out, PWD);
        out.close();

        initialize(context);

        return ready;

    } catch (Exception e) {
        return false;
    }
}

From source file:KeystoreGeneratorTest.java

@Test
public void test() throws Exception {
    File dir = null;/*  w w w  .  j ava 2 s.c o  m*/
    FileInputStream fis = null;
    try {
        dir = Files.createTempDir();
        File keystoreFile = new File(dir, KEYSTORE_NAME);

        String config = GSON.toJson(ImmutableMap.builder().put("password", KEYSTORE_PASSWORD)
                .put("entries", ImmutableList.builder()
                        .add(ImmutableMap.builder().put("label", "rsatest1").put("algorithm", "SHA256WithRSA")
                                .put("keyAlgorithm", "RSA").put("rsaKeySize", "2048").build())
                        .add(ImmutableMap.builder().put("label", "ecdsatest1")
                                .put("algorithm", "SHA256WithECDSA").put("keyAlgorithm", "ECDSA")
                                .put("ecdsaNamedCurve", "secp192r1").build())
                        .add(ImmutableMap.builder().put("label", "ecdsatest2")
                                .put("algorithm", "SHA256WithECDSA").put("keyAlgorithm", "ECDSA")
                                .put("ecdsaNamedCurve", "secp256r1").build())
                        .build())
                .build());
        // generate
        KeyStore store = new KeystoreGenerator().generate(GSON.fromJson(config, KeystoreConfig.class));
        // write to disk
        try (FileOutputStream out = new FileOutputStream(keystoreFile)) {
            store.store(out, KEYSTORE_PASSWORD.toCharArray());
        }
        // load
        fis = new FileInputStream(keystoreFile);
        KeyStore ks = KeyStore.getInstance("PKCS12", "SunJSSE");
        ks.load(fis, KEYSTORE_PASSWORD.toCharArray());
        Enumeration<String> aliases = ks.aliases();
        while (aliases.hasMoreElements()) {
            String al = aliases.nextElement();
            System.out.println("Label: [" + al + "]");
            X509Certificate cert = (X509Certificate) ks.getCertificate(al);
            System.out.println("  Algorithm: [" + cert.getSigAlgName() + "]");
            PublicKey key = cert.getPublicKey();
            if (key instanceof ECKey) {
                ECKey eckey = (ECKey) key;
                ECParameterSpec spec = eckey.getParams();
                System.out.println("  EC spec: [" + spec + "]");
            }
        }
    } finally {
        closeQuietly(fis);
        FileUtils.deleteDirectory(dir);
    }
}

From source file:com.thoughtworks.go.security.KeyStoreManager.java

private void writeStore(KeyStore store, File storeFile, String password) throws Exception {
    FileOutputStream fileOutputStream = null;
    try {//from w w  w  .j  a  v a2s  .c o m
        fileOutputStream = maybeOutputStream(storeFile);
        store.store(fileOutputStream, maybePassword(password));
    } finally {
        IOUtils.closeQuietly(fileOutputStream);
    }
}

From source file:org.lockss.util.KeyStoreUtil.java

private static void writeKeyStore(String domainNames[], KeyStore kss[], String passwords[], int i, File outDir)
        throws FileNotFoundException {
    String domainName = domainNames[i];
    KeyStore ks = kss[i];
    String password = passwords[i];
    if (domainName == null || ks == null || password == null) {
        return;/*from  w w w.  ja  v a  2 s .c  o  m*/
    }
    if (!outDir.exists() || !outDir.isDirectory()) {
        log.error("No directory " + outDir);
        throw new FileNotFoundException("No directory " + outDir);
    }
    File keyStoreFile = new File(outDir, domainName + ".jceks");
    File passwordFile = new File(outDir, domainName + ".pass");
    String keyStorePassword = domainName;
    try {
        log.debug("Writing KeyStore to " + keyStoreFile);
        FileOutputStream fos = new FileOutputStream(keyStoreFile);
        ks.store(fos, keyStorePassword.toCharArray());
        fos.close();
        log.debug("Done storing KeyStore in " + keyStoreFile);
    } catch (Exception e) {
        log.debug("ks.store(" + keyStoreFile + ") threw " + e);
    }
    writePasswordFile(passwordFile, password);
}

From source file:eu.europa.esig.dss.x509.KeyStoreCertificateSource.java

private void persistKeyStore(KeyStore keyStore) {
    OutputStream os = null;//from   ww w.j a va  2  s .co  m
    try {
        os = new FileOutputStream(keyStoreFile);
        keyStore.store(os, password.toCharArray());
    } catch (Exception e) {
        logger.error("Unable to persist the keystore : " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(os);
    }
}

From source file:org.jumpmind.security.SecurityService.java

protected void saveKeyStore(KeyStore ks, String password) throws Exception {
    FileOutputStream os = new FileOutputStream(System.getProperty(SecurityConstants.SYSPROP_KEYSTORE));
    ks.store(os, password.toCharArray());
    os.close();/*from   w w w.  ja  va  2s. c  om*/
}

From source file:xtremweb.communications.HTTPServer.java

/**
 * This initializes the secured layer/*from   ww  w  .  ja v  a 2s. c  om*/
 * 
 * @param prop
 * @throws IOException
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws KeyStoreException
 */
private void initSecuredLayer(final XWConfigurator prop)
        throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException {
    final String password = prop.getProperty(XWPropertyDefs.SSLKEYPASSWORD);
    final String passphrase = prop.getProperty(XWPropertyDefs.SSLKEYPASSPHRASE);
    final File fstore = File.createTempFile("xwcacert", null);
    try (final FileOutputStream sstore = new FileOutputStream(fstore)) {
        final int httpsPort = Integer.parseInt(prop.getProperty(Connection.HTTPSPORT.toString()));
        setPort(httpsPort);

        fstore.deleteOnExit();
        final KeyStore store = prop.getKeyStore();
        store.store(sstore, password.toCharArray());
        getLogger().debug("HTTPS keystore = " + fstore.getAbsolutePath());
        final SslContextFactory sslContextFactory = new SslContextFactory(fstore.getAbsolutePath());
        sslContextFactory.setKeyStorePassword(password);
        sslContextFactory.setKeyManagerPassword(passphrase);
        sslContextFactory.setTrustStore(store);
        sslContextFactory.setTrustStorePassword(password);
        sslContextFactory.setWantClientAuth(true);

        final HttpConfiguration http_config = new HttpConfiguration();
        http_config.setSecureScheme("https");
        http_config.setSecurePort(getPort());
        http_config.setOutputBufferSize(32768);

        final HttpConfiguration https_config = new HttpConfiguration(http_config);
        final SecureRequestCustomizer src = new SecureRequestCustomizer();
        src.setStsMaxAge(2000);
        src.setStsIncludeSubDomains(true);
        https_config.addCustomizer(src);

        final ServerConnector https = new ServerConnector(httpServer,
                new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.toString()),
                new HttpConnectionFactory(https_config));
        https.setPort(getPort());
        https.setIdleTimeout(500000);

        httpServer.setConnectors(new Connector[] { https });

    }
}

From source file:org.apache.hadoop.gateway.services.security.impl.BaseKeystoreService.java

protected void createKeystore(String filename, String keystoreType) throws KeystoreServiceException {
    try {//from w  w w . j  ava 2 s  . c om
        FileOutputStream out = createKeyStoreFile(filename);
        KeyStore ks = KeyStore.getInstance(keystoreType);
        ks.load(null, null);
        ks.store(out, masterService.getMasterSecret());
    } catch (KeyStoreException e) {
        LOG.failedToCreateKeystore(filename, keystoreType, e);
        throw new KeystoreServiceException(e);
    } catch (NoSuchAlgorithmException e) {
        LOG.failedToCreateKeystore(filename, keystoreType, e);
        throw new KeystoreServiceException(e);
    } catch (CertificateException e) {
        LOG.failedToCreateKeystore(filename, keystoreType, e);
        throw new KeystoreServiceException(e);
    } catch (FileNotFoundException e) {
        LOG.failedToCreateKeystore(filename, keystoreType, e);
        throw new KeystoreServiceException(e);
    } catch (IOException e) {
        LOG.failedToCreateKeystore(filename, keystoreType, e);
        throw new KeystoreServiceException(e);
    }
}

From source file:org.metaeffekt.dcc.agent.AuthenticationKeyGenerator.java

private void persistKeyStore(KeyStore keyStoreObject, File file, char[] password)
        throws GeneralSecurityException, IOException {
    OutputStream out = null;//from w  w  w.j a va 2s . c  om
    try {
        out = new BufferedOutputStream(new FileOutputStream(file));

        keyStoreObject.store(out, password);
    } finally {
        IOUtils.closeQuietly(out);
    }
}