List of usage examples for java.security KeyStore load
public final void load(InputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException
From source file:org.appenders.log4j2.elasticsearch.jest.JKSCertInfo.java
@Override public void applyTo(HttpClientConfig.Builder clientConfigBuilder) { try (FileInputStream keystoreFile = new FileInputStream(new File(keystorePath)); FileInputStream truststoreFile = new FileInputStream(new File(truststorePath))) { KeyStore keyStore = KeyStore.getInstance("jks"); keyStore.load(keystoreFile, keystorePassword.toCharArray()); KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, keystorePassword.toCharArray()); KeyStore trustStore = KeyStore.getInstance("jks"); trustStore.load(truststoreFile, truststorePassword.toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); // TODO: add support for hostname verification modes clientConfigBuilder.sslSocketFactory(new SSLConnectionSocketFactory(sslContext)); clientConfigBuilder//from w ww.j a v a 2s . co m .httpsIOSessionStrategy(new SSLIOSessionStrategy(sslContext, new NoopHostnameVerifier())); } catch (IOException | GeneralSecurityException e) { throw new ConfigurationException(configExceptionMessage, e); } }
From source file:edu.internet2.middleware.subject.provider.LdapPEMSocketFactory.java
protected void initManagers() { // trust managers try {/* ww w . ja v a2 s .c o m*/ X509Certificate cert = null; if (caFilename != null) cert = readCertificate(caFilename); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null, null); ks.setCertificateEntry("CACERT", cert); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); trustManagers = tmf.getTrustManagers(); } catch (Exception e) { log.error("ldap source cacert error: " + e); } // key managers if (certFilename != null && keyFilename != null) { char[] pw = new char[] { 0 }; try { X509Certificate cert = readCertificate(certFilename); PKCS1 pkcs = new PKCS1(); PrivateKey key = pkcs.readKey(keyFilename); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null, null); X509Certificate[] chain = new X509Certificate[1]; chain[0] = cert; ks.setKeyEntry("CERT", (Key) key, pw, chain); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, pw); keyManagers = kmf.getKeyManagers(); } catch (Exception e) { log.error("ldap source cert/key error: " + e); } } }
From source file:com.android.volley.toolbox.https.SslHttpClient.java
@Override protected ClientConnectionManager createClientConnectionManager() { SchemeRegistry registry = new SchemeRegistry(); PlainSocketFactory pfs = PlainSocketFactory.getSocketFactory(); Scheme s = new Scheme(HTTP_SCHEME, pfs, HTTP_DEFAULT_PORT); registry.register(s);//ww w . j a v a 2 s. co m ThreadSafeClientConnManager ret = null; try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new MySSLSocketFactory(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); registry.register(new Scheme(HTTP_SSL_SCHEME, sf, mHttpsPort)); ret = new ThreadSafeClientConnManager(new BasicHttpParams(), registry); } catch (GeneralSecurityException e) { throw new IllegalStateException(e); } catch (IOException e) { e.printStackTrace(); } return ret; }
From source file:com.spotify.docker.client.DockerCertificates.java
private DockerCertificates(final Builder builder) throws DockerCertificateException { try {//from w w w . j a v a 2 s. com final CertificateFactory cf = CertificateFactory.getInstance("X.509"); final Certificate caCert = cf.generateCertificate(Files.newInputStream(builder.caCertPath)); final Certificate clientCert = cf.generateCertificate(Files.newInputStream(builder.clientCertPath)); final PEMKeyPair clientKeyPair = (PEMKeyPair) new PEMParser( Files.newBufferedReader(builder.clientKeyPath, Charset.defaultCharset())).readObject(); final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec( clientKeyPair.getPrivateKeyInfo().getEncoded()); final KeyFactory kf = KeyFactory.getInstance("RSA"); final PrivateKey clientKey = kf.generatePrivate(spec); final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); trustStore.setEntry("ca", new KeyStore.TrustedCertificateEntry(caCert), null); final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); keyStore.setCertificateEntry("client", clientCert); keyStore.setKeyEntry("key", clientKey, KEY_STORE_PASSWORD, new Certificate[] { clientCert }); this.sslContext = SSLContexts.custom().loadTrustMaterial(trustStore) .loadKeyMaterial(keyStore, KEY_STORE_PASSWORD).useTLS().build(); } catch (CertificateException | IOException | NoSuchAlgorithmException | InvalidKeySpecException | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) { throw new DockerCertificateException(e); } }
From source file:org.authme.android.util.AuthMeHttpClient.java
private SSLSocketFactory newSslSocketFactory() { try {/*w w w . j a v a 2 s . co m*/ // Get an instance of the Bouncy Castle KeyStore format KeyStore trusted = KeyStore.getInstance("BKS"); // Could probably load the main keystore and then append, but this works trusted.load(null, null); InputStream is = context.getResources().openRawResource(R.raw.cacert_root); CertificateFactory certificateFactory = CertificateFactory.getInstance("X509"); Certificate certificate = certificateFactory.generateCertificate(is); trusted.setCertificateEntry("CACertRoot", certificate); // Now continue on using this keystore SSLSocketFactory sf = new SSLSocketFactory(trusted); // Hostname verification from certificate // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506 sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); return sf; } catch (Exception e) { throw new AssertionError(e); } }
From source file:com.spotify.sshagenttls.CertHttpsHandler.java
public void handle(final HttpsURLConnection conn) { final CertKey certKey; try {/*from ww w. j a v a 2 s . c om*/ certKey = createCertKey(); } catch (IOException | GeneralSecurityException e) { if (failOnCertError) { throw new RuntimeException(e); } else { LOG.warn("Error when setting up client certificates fromPaths {}. Error was '{}'. " + "No cert will be sent with request.", getCertSource(), e.toString()); LOG.debug("full exception fromPaths setting up ClientCertificate follows", e); return; } } final Certificate cert = certKey.cert(); final PrivateKey key = certKey.key(); // Generate a keystore password. // Do all this locally to not make copies of the password in memory. final SecureRandom random = new SecureRandom(); final int numBytes = 60; final char[] keyStorePassword = new char[numBytes]; for (int i = 0; i < numBytes; i++) { // Only use ASCII characters for the password. The corresponding integer range is [32, 126]. keyStorePassword[i] = (char) (random.nextInt(95) + 32); } try { // We're creating a keystore in memory and putting the cert & key into it. // The keystore needs a password when we put the key into it, even though it's only going to // exist for the lifetime of the process. So we just have some random password that we use. final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); keyStore.setCertificateEntry("client", cert); keyStore.setKeyEntry("key", key, keyStorePassword, new Certificate[] { cert }); // build an SSLContext based on our keystore, and then get an SSLSocketFactory fromPaths that final SSLContext sslContext = SSLContexts.custom().useProtocol("TLS") .loadKeyMaterial(keyStore, keyStorePassword).build(); // Clear out arrays that had password Arrays.fill(keyStorePassword, '\0'); conn.setSSLSocketFactory(sslContext.getSocketFactory()); } catch (CertificateException | IOException | NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) { // so many dumb ways to die. see https://www.youtube.com/watch?v=IJNR2EpS0jw for more. throw new RuntimeException(e); } }
From source file:com.trsst.Command.java
public static final KeyPair readKeyPairFromFile(String alias, File file, char[] pwd) { FileInputStream input = null; try {/*from w ww. j a v a 2s . c o m*/ KeyStore keyStore = KeyStore.getInstance("PKCS12"); input = new FileInputStream(file); keyStore.load(new FileInputStream(file), pwd); input.close(); KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, new KeyStore.PasswordProtection(pwd)); PrivateKey privateKey = pkEntry.getPrivateKey(); PublicKey publicKey = pkEntry.getCertificate().getPublicKey(); return new KeyPair(publicKey, privateKey); } catch (/* javax.crypto.BadPaddingException */IOException bpe) { log.error("Passphrase could not decrypt key: " + bpe.getMessage()); } catch (Throwable e) { log.error("Unexpected error while reading key: " + e.getMessage(), e); } finally { if (input != null) { try { input.close(); } catch (IOException e) { // ignore while closing log.trace("Error while closing: " + e.getMessage(), e); } } } return null; }
From source file:io.pivotal.springcloud.ssl.CloudFoundryCertificateTruster.java
/** * import trust from truststore file//from w w w. j av a 2 s .co m * * @param applicationContext * @param trustStore * @param trustStorePassword */ private void trustCertificatesFromStoreInternal(ConfigurableApplicationContext applicationContext, String trustStore, String trustStorePassword) { if (trustStore != null) { try { KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(applicationContext.getResource(trustStore).getInputStream(), trustStorePassword.toCharArray()); Enumeration<String> aliases = keystore.aliases(); List<X509Certificate> certCollect = new ArrayList<X509Certificate>(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); Certificate[] certs = keystore.getCertificateChain(alias); if (certs != null && certs.length > 0) for (Certificate cert : certs) if (cert instanceof X509Certificate) certCollect.add((X509Certificate) cert); Certificate cert = keystore.getCertificate(alias); if (cert != null && cert instanceof X509Certificate) { certCollect.add((X509Certificate) cert); } } if (certCollect.size() > 0) sslCertificateTruster.appendToTruststoreInternal(certCollect.toArray(new X509Certificate[0])); } catch (Exception e) { log.error("trusting trustore at {}:{} failed", trustStore, trustStorePassword, e); } } }
From source file:br.com.ararati.operacoes.SocketFactory.java
public TrustManager[] createTrustManagers() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { KeyStore trustStore = KeyStore.getInstance("JKS"); trustStore.load(new FileInputStream(fileCacerts), "changeit".toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); return trustManagerFactory.getTrustManagers(); }
From source file:com.shekhargulati.reactivex.docker.client.ssl.DockerCertificates.java
private DockerCertificates(final Builder builder) throws DockerCertificateException { if ((builder.caCertPath == null) || (builder.clientCertPath == null) || (builder.clientKeyPath == null)) { throw new DockerCertificateException( "caCertPath, clientCertPath, and clientKeyPath must all be specified"); }//w w w . j a v a2s . c o m try { final CertificateFactory cf = CertificateFactory.getInstance("X.509"); final Certificate caCert = cf.generateCertificate(Files.newInputStream(builder.caCertPath)); final Certificate clientCert = cf.generateCertificate(Files.newInputStream(builder.clientCertPath)); final PEMKeyPair clientKeyPair = (PEMKeyPair) new PEMParser( Files.newBufferedReader(builder.clientKeyPath, Charset.defaultCharset())).readObject(); final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec( clientKeyPair.getPrivateKeyInfo().getEncoded()); final KeyFactory kf = KeyFactory.getInstance("RSA"); final PrivateKey clientKey = kf.generatePrivate(spec); final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); trustStore.setEntry("ca", new KeyStore.TrustedCertificateEntry(caCert), null); final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, KEY_STORE_PASSWORD); keyStore.setCertificateEntry("client", clientCert); keyStore.setKeyEntry("key", clientKey, KEY_STORE_PASSWORD, new Certificate[] { clientCert }); this.sslContext = SSLContexts.custom().loadTrustMaterial(trustStore) .loadKeyMaterial(keyStore, KEY_STORE_PASSWORD).useTLS().build(); } catch (CertificateException | IOException | NoSuchAlgorithmException | InvalidKeySpecException | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) { throw new DockerCertificateException(e); } }