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.brienwheeler.apps.tomcat.TomcatBean.java

private void configureNetwork() throws Exception {
    if (port > 0) {
        tomcat.setPort(port);/*w  w w.  j av  a2  s  .c  om*/
    } else {
        tomcat.getService().removeConnector(tomcat.getConnector());
    }

    if (sslPort > 0) {
        StringBuffer randomPass = new StringBuffer();
        for (int i = 0; i < 10; i++)
            randomPass.append(characters.charAt((int) (characters.length() * Math.random())));
        String keystorePass = randomPass.toString();

        RSAPrivateKey privateKey = readKeyFile();
        log.info("successfully read SSL private key from " + sslKeyFile.getAbsolutePath());
        X509Certificate certificate = readCertFile();
        log.info("successfully read SSL certificate from " + sslCertFile.getAbsolutePath());

        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null);
        keyStore.setCertificateEntry("cert-alias", certificate);
        keyStore.setKeyEntry("key-alias", privateKey, keystorePass.toCharArray(),
                new Certificate[] { certificate });
        File keyStoreFile = new File("tcks");
        keyStore.store(new FileOutputStream(keyStoreFile), keystorePass.toCharArray());

        Connector sslConnector = new Connector();
        sslConnector.setPort(sslPort);
        sslConnector.setSecure(true);
        sslConnector.setScheme("https");
        sslConnector.setAttribute("keystoreFile", keyStoreFile.getAbsolutePath());
        sslConnector.setAttribute("keystorePass", keystorePass);
        sslConnector.setAttribute("clientAuth", "false");
        sslConnector.setAttribute("sslProtocol", "TLS");
        sslConnector.setAttribute("SSLEnabled", true);
        tomcat.getService().addConnector(sslConnector);
    }
}

From source file:org.objectweb.proactive.extensions.ssl.KeyStoreCreator.java

/**
 * Create a keystore with a certificate/*from   w  w  w . j av  a 2 s  . c  o m*/
 */
private boolean create(String keyStore) {
    try {
        // Create a certificate
        CertificateGenerator gen = new CertificateGenerator();
        KeyPair pair = gen.generateRSAKeyPair();
        X509Certificate cert = gen.generateCertificate(SslHelpers.DEFAULT_SUBJET_DN, pair);

        // Create the keystore
        KeyStore ks = KeyStore.getInstance("PKCS12", SslHelpers.BC_NAME);
        ks.load(null, null);

        ks.setKeyEntry(SslHelpers.DEFAULT_SUBJET_DN, pair.getPrivate(),
                SslHelpers.DEFAULT_KS_PASSWD.toCharArray(), new X509Certificate[] { cert });

        // Write the keystore
        FileOutputStream fos = new FileOutputStream(new File(keyStore));
        ks.store(fos, SslHelpers.DEFAULT_KS_PASSWD.toCharArray());
        fos.close();
        return true;
    } catch (Exception e) {
        System.err.println("Failed to create the keystore " + keyStore + ": " + e);
        return false;
    }
}

From source file:org.opendaylight.aaa.cert.impl.ODLKeyTool.java

public boolean createKeyStoreWithSelfSignCert(final String keyStoreName, final String keyStorePwd,
        final String dName, final String keyAlias, final int validity) {
    try {/*from  www  .  jav a 2 s  . c  o  m*/
        final KeyPairGenerator keyPairGenerator = KeyPairGenerator
                .getInstance(KeyStoreConstant.DEFAULT_KEY_ALG);
        keyPairGenerator.initialize(KeyStoreConstant.DEFAULT_KEY_SIZE);
        final KeyPair keyPair = keyPairGenerator.generateKeyPair();
        final X509V3CertificateGenerator x509V3CertGen = new X509V3CertificateGenerator();
        x509V3CertGen.setSerialNumber(getSecureRandomeInt());
        x509V3CertGen.setIssuerDN(new X509Principal(dName));
        x509V3CertGen.setNotBefore(new Date(System.currentTimeMillis()));
        x509V3CertGen
                .setNotAfter(new Date(System.currentTimeMillis() + (KeyStoreConstant.DAY_TIME * validity)));
        x509V3CertGen.setSubjectDN(new X509Principal(dName));
        x509V3CertGen.setPublicKey(keyPair.getPublic());
        x509V3CertGen.setSignatureAlgorithm(KeyStoreConstant.DEFAULT_SIGN_ALG);
        final X509Certificate x509Cert = x509V3CertGen.generateX509Certificate(keyPair.getPrivate());
        final KeyStore ctlKeyStore = KeyStore.getInstance("JKS");
        ctlKeyStore.load(null, keyStorePwd.toCharArray());
        ctlKeyStore.setKeyEntry(keyAlias, keyPair.getPrivate(), keyStorePwd.toCharArray(),
                new java.security.cert.Certificate[] { x509Cert });
        final FileOutputStream fOutputStream = new FileOutputStream(workingDir + keyStoreName);
        ctlKeyStore.store(fOutputStream, keyStorePwd.toCharArray());
        LOG.info("{} is created", keyStoreName);
        return true;
    } catch (NoSuchAlgorithmException | InvalidKeyException | SecurityException | SignatureException
            | KeyStoreException | CertificateException | IOException e) {
        LOG.error("Fatal error creating key", e);
        return false;
    }
}

From source file:com.streamsets.pipeline.lib.remote.FTPAndSSHDUnitTest.java

protected File generateCertificateKeystore(KeyStoreType keystoreType) throws Exception {
    KeyPair keyPair = generateKeyPair();
    X509Certificate cert = generateCertificate(keyPair);

    KeyStore keyStore = KeyStore.getInstance(keystoreType.getJavaValue());
    keyStore.load(null, KEYSTORE_PASSWORD.toCharArray());
    keyStore.setKeyEntry("foo", keyPair.getPrivate(), KEYSTORE_PASSWORD.toCharArray(),
            new Certificate[] { cert });
    File keystoreFile = keystoreFolder.newFile("keystore " + System.currentTimeMillis() + ".jks");
    try (FileOutputStream fos = new FileOutputStream(keystoreFile)) {
        keyStore.store(fos, KEYSTORE_PASSWORD.toCharArray());
    }/*from w  w  w  . ja  va  2s  .  c om*/
    return keystoreFile;
}

From source file:com.kixeye.chassis.transport.shared.JettyConnectorRegistry.java

/**
 * Register to listen to HTTPS.//from ww w. ja  va  2  s .c om
 * 
 * @param server
 * @param address
 * @throws Exception 
 */
public static void registerHttpsConnector(Server server, InetSocketAddress address, boolean selfSigned,
        boolean mutualSsl, String keyStorePath, String keyStoreData, String keyStorePassword,
        String keyManagerPassword, String trustStorePath, String trustStoreData, String trustStorePassword,
        String[] excludedCipherSuites) throws Exception {
    // SSL Context Factory
    SslContextFactory sslContextFactory = new SslContextFactory();

    if (selfSigned) {
        char[] passwordChars = UUID.randomUUID().toString().toCharArray();

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

        keyStore.load(null, passwordChars);

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

        v3CertGen.setSerialNumber(BigInteger.valueOf(new SecureRandom().nextInt()).abs());
        v3CertGen.setIssuerDN(new X509Principal("CN=" + "kixeye.com" + ", OU=None, O=None L=None, C=None"));
        v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
        v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)));
        v3CertGen.setSubjectDN(new X509Principal("CN=" + "kixeye.com" + ", OU=None, O=None L=None, C=None"));

        v3CertGen.setPublicKey(keyPair.getPublic());
        v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption");

        X509Certificate privateKeyCertificate = v3CertGen.generateX509Certificate(keyPair.getPrivate());

        keyStore.setKeyEntry("selfSigned", keyPair.getPrivate(), passwordChars,
                new java.security.cert.Certificate[] { privateKeyCertificate });

        ByteArrayOutputStream keyStoreBaos = new ByteArrayOutputStream();
        keyStore.store(keyStoreBaos, passwordChars);

        keyStoreData = new String(Hex.encode(keyStoreBaos.toByteArray()), Charsets.UTF_8);
        keyStorePassword = new String(passwordChars);
        keyManagerPassword = keyStorePassword;

        sslContextFactory.setTrustAll(true);
    }

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

    if (StringUtils.isNotBlank(keyStoreData)) {
        keyStore.load(new ByteArrayInputStream(Hex.decode(keyStoreData)), keyStorePassword.toCharArray());
    } else if (StringUtils.isNotBlank(keyStorePath)) {
        try (InputStream inputStream = new DefaultResourceLoader().getResource(keyStorePath).getInputStream()) {
            keyStore.load(inputStream, keyStorePassword.toCharArray());
        }
    }

    sslContextFactory.setKeyStore(keyStore);
    sslContextFactory.setKeyStorePassword(keyStorePassword);
    if (StringUtils.isBlank(keyManagerPassword)) {
        keyManagerPassword = keyStorePassword;
    }
    sslContextFactory.setKeyManagerPassword(keyManagerPassword);
    KeyStore trustStore = null;
    if (StringUtils.isNotBlank(trustStoreData)) {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(new ByteArrayInputStream(Hex.decode(trustStoreData)), trustStorePassword.toCharArray());
    } else if (StringUtils.isNotBlank(trustStorePath)) {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        try (InputStream inputStream = new DefaultResourceLoader().getResource(trustStorePath)
                .getInputStream()) {
            trustStore.load(inputStream, trustStorePassword.toCharArray());
        }
    }
    if (trustStore != null) {
        sslContextFactory.setTrustStore(trustStore);
        sslContextFactory.setTrustStorePassword(trustStorePassword);
    }
    sslContextFactory.setNeedClientAuth(mutualSsl);
    sslContextFactory.setExcludeCipherSuites(excludedCipherSuites);

    // SSL Connector
    ServerConnector connector = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.toString()),
            new HttpConnectionFactory());
    connector.setHost(address.getHostName());
    connector.setPort(address.getPort());

    server.addConnector(connector);
}

From source file:mitm.common.tools.CreateCA.java

public void generateCA(String password, File p12File) throws Exception {
    KeyStore keyStore = securityFactory.createKeyStore("PKCS12");

    keyStore.load(null);/*from ww w  .ja  va  2 s . c  om*/

    generateRoot();
    generateIntermediate();

    keyStore.setKeyEntry("root", rootKeyPair.getPrivate(), null, new Certificate[] { rootCertificate });

    keyStore.setKeyEntry("intermediate", intermediateKeyPair.getPrivate(), null,
            new Certificate[] { intermediateCertificate, rootCertificate });

    FileOutputStream output = new FileOutputStream(p12File);

    keyStore.store(output, password.toCharArray());

    output.close();
}

From source file:org.apache.accumulo.test.util.CertUtils.java

public void createSelfSignedCert(File targetKeystoreFile, String keyName, String keystorePassword)
        throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException,
        OperatorCreationException, AccumuloSecurityException, NoSuchProviderException {
    if (targetKeystoreFile.exists()) {
        throw new FileExistsException(targetKeystoreFile);
    }/*  www  .ja  v  a2s.c  om*/

    KeyPair kp = generateKeyPair();

    X509CertificateObject cert = generateCert(keyName, kp, true, kp.getPublic(), kp.getPrivate());

    char[] password = keystorePassword.toCharArray();
    KeyStore keystore = KeyStore.getInstance(keystoreType);
    keystore.load(null, null);
    keystore.setCertificateEntry(keyName + "Cert", cert);
    keystore.setKeyEntry(keyName + "Key", kp.getPrivate(), password, new Certificate[] { cert });
    try (FileOutputStream fos = new FileOutputStream(targetKeystoreFile)) {
        keystore.store(fos, password);
    }
}

From source file:org.gvnix.service.roo.addon.addon.security.GvNix509TrustManager.java

/**
 * Import certs in this.chain to the keystore given by the file passed.
 * //www .  j  a  v a 2  s. c o m
 * @param host
 * @param keystore
 * @param pass
 * @return
 * @throws Exception
 */
public X509Certificate[] addCerts(String host, File keystore, char[] pass) throws Exception {

    // Specific Exceptions thrown in this code: NoSuchAlgorithmException,
    // KeyStoreException, CertificateException, IOException

    X509Certificate[] chain = this.chain;
    if (chain == null) {
        return null;
    }

    KeyStore ks = loadKeyStore(keystore, pass);

    String alias = host;
    for (int i = 0; i < chain.length; i++) {

        X509Certificate cert = chain[i];
        alias = alias.concat("-" + (i + 1));
        ks.setCertificateEntry(alias, cert);
        alias = host;
    }

    if (keystore.canWrite()) {

        OutputStream out = null;
        try {
            out = new FileOutputStream(keystore);
            ks.store(out, pass);
        } finally {
            IOUtils.closeQuietly(out);
        }

    } else {

        throw new Exception(keystore.getAbsolutePath().concat(" is not writable. ")
                .concat("You should to import needed certificates in your")
                .concat(" JVM trustcacerts keystore.\n").concat("You have them in src/main/resources/*.cer.\n")
                .concat("Use keytool for that: ")
                .concat("http://download.oracle.com/javase/6/docs/technotes/tools/solaris/keytool.html"));
    }

    return chain;
}

From source file:org.forgerock.openidm.security.impl.EntryResourceProviderTest.java

private File createTemporaryKeyStore()
        throws CertificateException, NoSuchAlgorithmException, IOException, KeyStoreException {
    final File keystoreFile = File.createTempFile(CLASS_NAME, null, temporaryFolder());
    keystoreFile.deleteOnExit();/*from  w ww. j a  v a 2s  .co m*/
    KeyStore ks = KeyStore.getInstance(KEY_STORE_TYPE);

    char[] password = KEY_STORE_PASSWORD.toCharArray();
    ks.load(null, password);

    FileOutputStream fos = new FileOutputStream(keystoreFile);
    ks.store(fos, password);
    fos.close();

    return keystoreFile;
}

From source file:org.apache.accumulo.test.util.CertUtils.java

public void createSignedCert(File targetKeystoreFile, String keyName, String keystorePassword,
        String signerKeystorePath, String signerKeystorePassword) throws KeyStoreException,
        CertificateException, NoSuchAlgorithmException, IOException, OperatorCreationException,
        AccumuloSecurityException, UnrecoverableKeyException, NoSuchProviderException {
    KeyStore signerKeystore = KeyStore.getInstance(keystoreType);
    char[] signerPasswordArray = signerKeystorePassword.toCharArray();
    try (FileInputStream fis = new FileInputStream(signerKeystorePath)) {
        signerKeystore.load(fis, signerPasswordArray);
    }// w  ww  .java 2s . co  m
    Certificate signerCert = findCert(signerKeystore);
    PrivateKey signerKey = findPrivateKey(signerKeystore, signerPasswordArray);

    KeyPair kp = generateKeyPair();
    X509CertificateObject cert = generateCert(keyName, kp, false, signerCert.getPublicKey(), signerKey);

    char[] password = keystorePassword.toCharArray();
    KeyStore keystore = KeyStore.getInstance(keystoreType);
    keystore.load(null, null);
    keystore.setCertificateEntry(keyName + "Cert", cert);
    keystore.setKeyEntry(keyName + "Key", kp.getPrivate(), password, new Certificate[] { cert, signerCert });
    try (FileOutputStream fos = new FileOutputStream(targetKeystoreFile)) {
        keystore.store(fos, password);
    }
}