List of usage examples for java.security KeyStore load
public final void load(LoadStoreParameter param) throws IOException, NoSuchAlgorithmException, CertificateException
From source file:com.cloudbees.tftwoway.Client.java
public static KeyManager[] getKeyManager() throws Exception { KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); KeyStore store = KeyStore.getInstance("JKS"); PrivateKey clientKey = loadRSAKey(PRIVATE_KEY); X509Certificate clientCert = loadX509Key(CERTIFICATE); store.load(null); store.setKeyEntry("key", clientKey, "123123".toCharArray(), new Certificate[] { clientCert }); keyManagerFactory.init(store, "123123".toCharArray()); return keyManagerFactory.getKeyManagers(); }
From source file:Main.java
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) private static KeyStore getKeyStore(Context context) { KeyStore keyStore = null; try {//from w w w . j av a 2 s. co m keyStore = KeyStore.getInstance(KEY_PROVIDER); keyStore.load(null); if (!keyStore.containsAlias(KEY_ALIAS)) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // for api level 23+ generateNewKey(); } else { // for api level 18 - 22 generateNewKeyOld(context); } } } catch (KeyStoreException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } 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.// www. ja v a2s.c o 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:org.gw2InfoViewer.factories.HttpsConnectionFactory.java
public static HttpClient getHttpsClient(Certificate[] sslCertificate) { DefaultHttpClient httpClient;/* w w w . j av a2s . c o m*/ httpClient = new DefaultHttpClient(); try { TrustManagerFactory tf = TrustManagerFactory.getInstance("X509"); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null); for (int i = 0; i < sslCertificate.length; i++) { ks.setCertificateEntry("StartCom" + i, sslCertificate[i]); } tf.init(ks); TrustManager[] tm = tf.getTrustManagers(); SSLContext sslCon = SSLContext.getInstance("SSL"); sslCon.init(null, tm, new SecureRandom()); SSLSocketFactory socketFactory = new SSLSocketFactory(ks); Scheme sch = new Scheme("https", 443, socketFactory); httpClient.getConnectionManager().getSchemeRegistry().register(sch); } catch (CertificateException | NoSuchAlgorithmException | KeyStoreException | IOException | KeyManagementException | UnrecoverableKeyException ex) { Logger.getLogger(HttpsConnectionFactory.class.getName()).log(Level.SEVERE, null, ex); } return httpClient; }
From source file:org.gw2InfoViewer.factories.HttpsConnectionFactory.java
public static HttpClient getHttpsClient(byte[] sslCertificateBytes) { DefaultHttpClient httpClient;/*from w w w .j a v a 2 s. c o m*/ Certificate[] sslCertificate; httpClient = new DefaultHttpClient(); try { sslCertificate = convertByteArrayToCertificate(sslCertificateBytes); TrustManagerFactory tf = TrustManagerFactory.getInstance("X509"); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null); for (int i = 0; i < sslCertificate.length; i++) { ks.setCertificateEntry("StartCom" + i, sslCertificate[i]); } tf.init(ks); TrustManager[] tm = tf.getTrustManagers(); SSLContext sslCon = SSLContext.getInstance("SSL"); sslCon.init(null, tm, new SecureRandom()); SSLSocketFactory socketFactory = new SSLSocketFactory(ks); Scheme sch = new Scheme("https", 443, socketFactory); httpClient.getConnectionManager().getSchemeRegistry().register(sch); } catch (CertificateException | NoSuchAlgorithmException | KeyStoreException | IOException | KeyManagementException | UnrecoverableKeyException ex) { Logger.getLogger(HttpsConnectionFactory.class.getName()).log(Level.SEVERE, null, ex); } return httpClient; }
From source file:org.gw2InfoViewer.factories.HttpsConnectionFactory.java
public static HttpClient getHttpsClientWithProxy(Certificate[] sslCertificate, String proxyAddress, int proxyPort) { DefaultHttpClient httpClient;/*from ww w . ja va 2 s .c om*/ HttpHost proxy; httpClient = new DefaultHttpClient(); try { TrustManagerFactory tf = TrustManagerFactory.getInstance("X509"); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null); for (int i = 0; i < sslCertificate.length; i++) { ks.setCertificateEntry("StartCom" + i, sslCertificate[i]); } tf.init(ks); TrustManager[] tm = tf.getTrustManagers(); SSLContext sslCon = SSLContext.getInstance("SSL"); sslCon.init(null, tm, new SecureRandom()); SSLSocketFactory socketFactory = new SSLSocketFactory(ks); Scheme sch = new Scheme("https", 443, socketFactory); proxy = new HttpHost(proxyAddress, proxyPort, "https"); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); httpClient.getConnectionManager().getSchemeRegistry().register(sch); } catch (CertificateException | NoSuchAlgorithmException | KeyStoreException | IOException | KeyManagementException | UnrecoverableKeyException ex) { Logger.getLogger(HttpsConnectionFactory.class.getName()).log(Level.SEVERE, null, ex); } return httpClient; }
From source file:org.gw2InfoViewer.factories.HttpsConnectionFactory.java
public static HttpClient getHttpsClientWithProxy(byte[] sslCertificateBytes, String proxyAddress, int proxyPort) { DefaultHttpClient httpClient;/* w ww . j ava 2 s. c om*/ Certificate[] sslCertificate; HttpHost proxy; httpClient = new DefaultHttpClient(); try { sslCertificate = convertByteArrayToCertificate(sslCertificateBytes); TrustManagerFactory tf = TrustManagerFactory.getInstance("X509"); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null); for (int i = 0; i < sslCertificate.length; i++) { ks.setCertificateEntry("StartCom" + i, sslCertificate[i]); } tf.init(ks); TrustManager[] tm = tf.getTrustManagers(); SSLContext sslCon = SSLContext.getInstance("SSL"); sslCon.init(null, tm, new SecureRandom()); SSLSocketFactory socketFactory = new SSLSocketFactory(ks); Scheme sch = new Scheme("https", 443, socketFactory); proxy = new HttpHost(proxyAddress, proxyPort, "https"); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); httpClient.getConnectionManager().getSchemeRegistry().register(sch); } catch (CertificateException | NoSuchAlgorithmException | KeyStoreException | IOException | KeyManagementException | UnrecoverableKeyException ex) { Logger.getLogger(HttpsConnectionFactory.class.getName()).log(Level.SEVERE, null, ex); } return httpClient; }
From source file:com.machinepublishers.jbrowserdriver.StreamConnectionClient.java
private static SSLContext sslContext() { final String property = SettingsManager.settings().ssl(); if (property != null && !property.isEmpty() && !"null".equals(property)) { if ("trustanything".equals(property)) { try { return SSLContexts.custom().loadTrustMaterial(KeyStore.getInstance(KeyStore.getDefaultType()), new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; }/*from ww w. j a va 2s .c o m*/ }).build(); } catch (Throwable t) { LogsServer.instance().exception(t); } } else { try { String location = property; location = location.equals("compatible") ? "https://raw.githubusercontent.com/bagder/ca-bundle/master/ca-bundle.crt" : location; File cachedPemFile = new File("./pemfile_cached"); boolean remote = location.startsWith("https://") || location.startsWith("http://"); if (remote && cachedPemFile.exists() && (System.currentTimeMillis() - cachedPemFile.lastModified() < 48 * 60 * 60 * 1000)) { location = cachedPemFile.getAbsolutePath(); remote = false; } String pemBlocks = null; if (remote) { HttpURLConnection remotePemFile = (HttpURLConnection) StreamHandler .defaultConnection(new URL(location)); remotePemFile.setRequestMethod("GET"); remotePemFile.connect(); pemBlocks = Util.toString(remotePemFile.getInputStream(), Util.charset(remotePemFile)); cachedPemFile.delete(); Files.write(Paths.get(cachedPemFile.getAbsolutePath()), pemBlocks.getBytes("utf-8")); } else { pemBlocks = new String(Files.readAllBytes(Paths.get(new File(location).getAbsolutePath())), "utf-8"); } KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null); CertificateFactory cf = CertificateFactory.getInstance("X.509"); Matcher matcher = pemBlock.matcher(pemBlocks); boolean found = false; while (matcher.find()) { String pemBlock = matcher.group(1).replaceAll("[\\n\\r]+", ""); ByteArrayInputStream byteStream = new ByteArrayInputStream( Base64.getDecoder().decode(pemBlock)); java.security.cert.X509Certificate cert = (java.security.cert.X509Certificate) cf .generateCertificate(byteStream); String alias = cert.getSubjectX500Principal().getName("RFC2253"); if (alias != null && !keyStore.containsAlias(alias)) { found = true; keyStore.setCertificateEntry(alias, cert); } } if (found) { KeyManagerFactory keyManager = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManager.init(keyStore, null); TrustManagerFactory trustManager = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManager.init(keyStore); SSLContext context = SSLContext.getInstance("TLS"); context.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null); return context; } } catch (Throwable t) { LogsServer.instance().exception(t); } } } return SSLContexts.createSystemDefault(); }
From source file:gov.niem.ws.util.SecurityUtil.java
public static KeyManager[] createKeyManagers(KeyPair clientKey, X509Certificate clientCert) throws GeneralSecurityException, IOException { // Create a new empty key store. KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null); Certificate[] chain = { clientCert }; // The KeyStore requires a password for key entries. char[] password = { ' ' }; // Since we never write out the key store, we don't bother protecting // the key./* w w w .j a v a 2s. c o m*/ ks.setEntry("client-key", new KeyStore.PrivateKeyEntry(clientKey.getPrivate(), chain), new KeyStore.PasswordProtection(password)); // Shove the key store in a KeyManager. KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, password); return kmf.getKeyManagers(); }
From source file:br.gov.serpro.cert.AuthSSLProtocolSocketFactory.java
private static KeyStore createKeyStore(final URL[] urls, final String[] passwords) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(null); if (urls == null) { throw new IllegalArgumentException("Keystore urls may not be null"); }/* w w w.j av a2s .c o m*/ if (passwords != null && passwords.length != urls.length) { throw new IllegalArgumentException("Urls and passwords arrays must have the same size"); } LOG.debug("Initializing key store"); for (int i = 0; i < urls.length; i++) { LOG.debug("Adding " + urls[i].toString() + " to internal keystore"); KeyStore ks = KeyStore.getInstance("jks"); InputStream is = null; try { is = urls[i].openStream(); if (passwords == null) { ks.load(is, null); } else { ks.load(is, passwords[i] != null ? passwords[i].toCharArray() : null); } for (Enumeration<String> e = ks.aliases(); e.hasMoreElements();) { X509Certificate cert = (X509Certificate) ks.getCertificate(e.nextElement()); keystore.setCertificateEntry(cert.getSubjectX500Principal().getName(), cert); } } catch (IOException e) { if (AuthSSLProtocolSocketFactory.setup.getParameter("debug").equalsIgnoreCase("true")) { System.out.println("Erro ao abrir URL: " + urls[i].toExternalForm()); } } finally { if (is != null) is.close(); } } return keystore; }