Example usage for java.security KeyStore setCertificateEntry

List of usage examples for java.security KeyStore setCertificateEntry

Introduction

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

Prototype

public final void setCertificateEntry(String alias, Certificate cert) throws KeyStoreException 

Source Link

Document

Assigns the given trusted certificate to the given alias.

Usage

From source file:org.zaproxy.zap.extension.dynssl.SslCertificateUtils.java

/**
 * Code c/o http://stackoverflow.com/questions/12501117/programmatically-obtain-keystore-from-pem
 * @param pemFile//from  w  w  w .  j a  va2 s.  co  m
 * @return
 * @throws IOException
 * @throws CertificateException
 * @throws InvalidKeySpecException
 * @throws NoSuchAlgorithmException
 * @throws KeyStoreException
 */
public static KeyStore pem2Keystore(File pemFile) throws IOException, CertificateException,
        InvalidKeySpecException, NoSuchAlgorithmException, KeyStoreException {
    byte[] certAndKey = FileUtils.readFileToByteArray(pemFile);
    byte[] certBytes = parseDERFromPEM(certAndKey, "-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----");
    byte[] keyBytes = parseDERFromPEM(certAndKey, "-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----");

    X509Certificate cert = generateCertificateFromDER(certBytes);
    RSAPrivateKey key = generatePrivateKeyFromDER(keyBytes);

    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(null);
    keystore.setCertificateEntry("cert-alias", cert);
    keystore.setKeyEntry(SslCertificateService.ZAPROXY_JKS_ALIAS, key, SslCertificateService.PASSPHRASE,
            new Certificate[] { cert });
    return keystore;
}

From source file:io.vertx.config.vault.utils.Certificates.java

/**
 * Constructs a Java truststore in JKS format, containing the Vault server certificate generated by
 * {@link #createVaultCertAndKey()}, so that Vault clients configured with this JKS will trust that
 * certificate./*from  w  w  w . j  a  v  a  2  s  .co m*/
 */
public static void createClientCertAndKey() throws Exception {
    if (SSL_DIRECTORY.isDirectory() && CLIENT_CERT_PEMFILE.isFile()) {
        return;
    }

    // Store the Vault's server certificate as a trusted cert in the truststore
    final KeyStore trustStore = KeyStore.getInstance("jks");
    trustStore.load(null);
    trustStore.setCertificateEntry("cert", vaultCertificate);
    try (final FileOutputStream keystoreOutputStream = new FileOutputStream(CLIENT_TRUSTSTORE)) {
        trustStore.store(keystoreOutputStream, "password".toCharArray());
    }

    // Generate a client certificate, and store it in a Java keystore
    final KeyPair keyPair = generateKeyPair();
    final X509Certificate clientCertificate = generateCert(keyPair,
            "C=AU, O=The Legion of the Bouncy Castle, OU=Client Certificate, CN=localhost");
    final KeyStore keyStore = KeyStore.getInstance("jks");
    keyStore.load(null);
    keyStore.setKeyEntry("privatekey", keyPair.getPrivate(), "password".toCharArray(),
            new java.security.cert.Certificate[] { clientCertificate });
    keyStore.setCertificateEntry("cert", clientCertificate);
    try (final FileOutputStream keystoreOutputStream = new FileOutputStream(CLIENT_KEYSTORE)) {
        keyStore.store(keystoreOutputStream, "password".toCharArray());
    }

    // Also write the client certificate to a PEM file, so it can be registered with Vault
    writeCertToPem(clientCertificate, CLIENT_CERT_PEMFILE);
    writePrivateKeyToPem(keyPair.getPrivate(), CLIENT_PRIVATE_KEY_PEMFILE);
}

From source file:Main.java

public static SSLSocketFactory setCertificates(InputStream... certificates) {
    try {/*from ww  w. ja  v  a2 s.c o  m*/
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null);
        int index = 0;
        for (InputStream certificate : certificates) {
            String certificateAlias = Integer.toString(index++);
            keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));
            try {
                if (certificate != null)
                    certificate.close();
            } catch (IOException e) {
            }
        }
        SSLContext sslContext = SSLContext.getInstance("TLS");
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
        socketFactory = sslContext.getSocketFactory();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return socketFactory;
}

From source file:com.owncloud.android.lib.common.network.NetworkUtils.java

public static String addCertToKnownServersStore(Certificate cert, Context context)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {

    KeyStore knownServers = getKnownServersStore(context);
    String alias = Integer.toString(cert.hashCode());
    knownServers.setCertificateEntry(alias, cert);
    FileOutputStream fos = null;/*from  w  w w .  ja  v a 2 s .c  o m*/
    try {
        fos = context.openFileOutput(LOCAL_TRUSTSTORE_FILENAME, Context.MODE_PRIVATE);
        knownServers.store(fos, LOCAL_TRUSTSTORE_PASSWORD.toCharArray());
    } finally {
        fos.close();
    }
    return alias;
}

From source file:Main.java

private static TrustManager[] prepareTrustManager(InputStream... certificates) {
    if (certificates == null || certificates.length <= 0)
        return null;
    try {//from   w  ww  . j  a v a  2 s .co  m

        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null);
        int index = 0;
        for (InputStream certificate : certificates) {
            String certificateAlias = Integer.toString(index++);
            keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));
            try {
                if (certificate != null)
                    certificate.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        TrustManagerFactory trustManagerFactory = null;

        trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);

        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

        return trustManagers;
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;

}

From source file:Main.java

private static TrustManager[] prepareTrustManager(InputStream... certificates) {
    if (certificates == null || certificates.length <= 0)
        return null;
    try {//  ww w .jav  a  2  s .c  om

        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null);
        int index = 0;
        for (InputStream certificate : certificates) {
            String certificateAlias = Integer.toString(index++);
            keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));
            try {
                if (certificate != null)
                    certificate.close();
            } catch (IOException e)

            {
            }
        }
        TrustManagerFactory trustManagerFactory = null;

        trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);

        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

        return trustManagers;
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;

}

From source file:io.fabric8.utils.cxf.WebClients.java

public static KeyStore createTrustStore(String caCertData, File caCertFile) throws Exception {
    try (InputStream pemInputStream = getInputStreamFromDataOrFile(caCertData, caCertFile)) {
        CertificateFactory certFactory = CertificateFactory.getInstance("X509");
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(pemInputStream);

        KeyStore trustStore = KeyStore.getInstance("JKS");
        trustStore.load(null);/*from w  w  w.  j  av  a 2  s  .  c o  m*/

        String alias = cert.getSubjectX500Principal().getName();
        trustStore.setCertificateEntry(alias, cert);

        return trustStore;
    }
}

From source file:me.xiaopan.android.gohttp.httpclient.MySSLSocketFactory.java

/**
 * Gets a KeyStore containing the Certificate
 *
 * @param cert InputStream of the Certificate
 * @return KeyStore/*from ww  w.j a v a 2  s.co m*/
 */
public static KeyStore getKeystoreOfCA(InputStream cert) {

    // Load CAs from an InputStream
    InputStream caInput = null;
    Certificate ca = null;
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        caInput = new BufferedInputStream(cert);
        ca = (Certificate) cf.generateCertificate(caInput);
    } catch (CertificateException e1) {
        e1.printStackTrace();
    } finally {
        try {
            caInput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = null;
    try {
        keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", (Certificate) ca);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return keyStore;
}

From source file:test.SAMLAttributeQueryExample.java

/**
 * Build the HTTP client./*from  w  w  w.  ja  va2s  .  c om*/
 * 
 * @param idpCertificateFile path to idp certificate file
 * @param clientPrivateKeyFile path to client private key file
 * @param clientCertificateFile path to client certificate file
 * @return the HTTP client
 * @throws Exception if an error occurs
 */
@Nonnull
public static HttpClient buildHttpClient(@Nonnull final String idpCertificateFile,
        @Nonnull final String clientPrivateKeyFile, @Nonnull final String clientCertificateFile)
        throws Exception {

    X509Certificate idpCert = CertUtil.readCertificate(idpCertificateFile);
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null, null);
    trustStore.setCertificateEntry("idp", idpCert);

    PrivateKey clientPrivateKey = KeyPairUtil.readPrivateKey(clientPrivateKeyFile);
    X509Certificate clientCert = CertUtil.readCertificate(clientCertificateFile);
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(null, null);
    keyStore.setKeyEntry("me", clientPrivateKey, "secret".toCharArray(), new Certificate[] { clientCert });

    SSLContextBuilder sslContextBuilder = SSLContexts.custom();
    sslContextBuilder.loadTrustMaterial(trustStore);
    sslContextBuilder.loadKeyMaterial(keyStore, "secret".toCharArray());
    SSLContext sslcontext = sslContextBuilder.build();

    CloseableHttpClient httpClient = HttpClients.custom().setSslcontext(sslcontext).build();

    return httpClient;
}

From source file:cn.com.loopj.android.http.MySSLSocketFactory.java

/**
 * Gets a KeyStore containing the Certificate
 *
 * @param cert InputStream of the Certificate
 * @return KeyStore//  w w w  .  j a v a  2s .c  o  m
 */
public static KeyStore getKeystoreOfCA(InputStream cert) {

    // Load CAs from an InputStream
    InputStream caInput = null;
    Certificate ca = null;
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        caInput = new BufferedInputStream(cert);
        ca = cf.generateCertificate(caInput);
    } catch (CertificateException e1) {
        e1.printStackTrace();
    } finally {
        try {
            if (caInput != null) {
                caInput.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = null;
    try {
        keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", ca);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return keyStore;
}