List of usage examples for java.security KeyStore getInstance
public static KeyStore getInstance(String type) throws KeyStoreException
From source file:com.myJava.file.driver.remote.ftp.SecuredSocketFactory.java
public SecuredSocketFactory(String protocol, String protection, boolean checkServerCertificate, boolean implicit, InputStream certificateInputStream, String certificatePassword, FTPSClient client) { Logger.defaultLogger().info("Initializing secured socket factory ..."); acceptProtocol(protocol);// w w w . ja va2 s. c o m this.protocol = protocol; this.protection = protection; if (protection == null || (!protection.equals("C") && !protection.equals("P"))) { throw new IllegalArgumentException( "Illegal protection method : [" + protection + "]. Only \"C\" and \"P\" are accepted."); } this.implicit = implicit; this.client = client; TrustManager tm[] = null; KeyManager km[] = null; // Init the keyStore if needed if (certificateInputStream != null) { try { Logger.defaultLogger().info("Loading certificate ..."); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEY_ALGORITHM); KeyStore ks = KeyStore.getInstance(KEY_TYPE); char[] pwdChars = (certificatePassword == null ? null : certificatePassword.toCharArray()); ks.load(certificateInputStream, pwdChars); kmf.init(ks, pwdChars); km = kmf.getKeyManagers(); } catch (Exception e) { Logger.defaultLogger().error(e); } } // Init the trustmanager if needed if (!checkServerCertificate) { Logger.defaultLogger().info("Disabling server identification ..."); tm = NO_CHECK_TM; } try { sslContext = SSLContext.getInstance(protocol); sslContext.init(km, tm, null); } catch (NoSuchAlgorithmException e) { Logger.defaultLogger().error(e); } catch (KeyManagementException e) { Logger.defaultLogger().error(e); } }
From source file:slash.navigation.rest.ssl.SSLConnectionManagerFactory.java
private KeyStore getKeyStore() throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException { KeyStore keyStore = KeyStore.getInstance("JKS"); InputStream inputStream = getClass().getResourceAsStream("letsencrypt.truststore"); try {/*w w w . j a v a2 s. c om*/ keyStore.load(inputStream, "letsencrypt".toCharArray()); } finally { closeQuietly(inputStream); } 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 ww w .j av 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:it.jnrpe.server.CBindingThread.java
/** * Returns the SSL factory to be used to create the Server Socket * @throws KeyStoreException //from www . ja v a2 s . c o m * @throws IOException * @throws FileNotFoundException * @throws CertificateException * @throws UnrecoverableKeyException * @throws KeyManagementException * * @see it.intesa.fi2.client.network.ISSLObjectsFactory#getSSLSocketFactory(String, String, String) */ public SSLServerSocketFactory getSSLSocketFactory(String sKeyStoreFile, String sKeyStorePwd, String sKeyStoreType) throws KeyStoreException, CertificateException, FileNotFoundException, IOException, UnrecoverableKeyException, KeyManagementException { if (sKeyStoreFile == null) throw new KeyStoreException("KEYSTORE HAS NOT BEEN SPECIFIED"); if (this.getClass().getClassLoader().getResourceAsStream(sKeyStoreFile) == null) throw new KeyStoreException("COULD NOT FIND KEYSTORE '" + sKeyStoreFile + "'"); if (sKeyStorePwd == null) throw new KeyStoreException("KEYSTORE PASSWORD HAS NOT BEEN SPECIFIED"); SSLContext ctx; KeyManagerFactory kmf; try { ctx = SSLContext.getInstance("SSLv3"); kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); //KeyStore ks = getKeystore(sKeyStoreFile, sKeyStorePwd, sKeyStoreType); KeyStore ks = KeyStore.getInstance(sKeyStoreType); ks.load(this.getClass().getClassLoader().getResourceAsStream(sKeyStoreFile), sKeyStorePwd.toCharArray()); char[] passphrase = sKeyStorePwd.toCharArray(); kmf.init(ks, passphrase); ctx.init(kmf.getKeyManagers(), null, new java.security.SecureRandom()); } catch (NoSuchAlgorithmException e) { throw new SSLException("Unable to initialize SSLSocketFactory.\n" + e.getMessage()); } return ctx.getServerSocketFactory(); }
From source file:com.google.samples.apps.abelana.AbelanaThings.java
public AbelanaThings(Context ctx, String phint) { final JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); final HttpTransport httpTransport = new NetHttpTransport(); Resources r = ctx.getResources(); byte[] android, server; byte[] password = new byte[32]; android = Base64.decode("vW7CmbQWdPjpdfpBU39URsjHQV50KEKoSfafHdQPSh8", Base64.URL_SAFE + Base64.NO_PADDING + Base64.NO_WRAP); server = Base64.decode(phint, Base64.URL_SAFE); int i = 0;//w ww . j ava 2 s .c o m for (byte b : android) { password[i] = (byte) (android[i] ^ server[i]); i++; } byte[] pw = Base64.encode(password, Base64.URL_SAFE + Base64.NO_PADDING + Base64.NO_WRAP); String pass = new String(pw); if (storage == null) { try { KeyStore keystore = KeyStore.getInstance("PKCS12"); keystore.load(r.openRawResource(R.raw.abelananew), pass.toCharArray()); credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory) .setServiceAccountId(r.getString(R.string.service_account)) .setServiceAccountScopes(Collections.singleton(StorageScopes.DEVSTORAGE_FULL_CONTROL)) .setServiceAccountPrivateKey((PrivateKey) keystore.getKey("privatekey", pass.toCharArray())) .build(); storage = new Storage.Builder(httpTransport, jsonFactory, credential) .setApplicationName(r.getString(R.string.app_name) + "/1.0").build(); } catch (CertificateException e) { e.printStackTrace(); } catch (UnrecoverableKeyException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("loaded"); } }
From source file:com.amazon.alexa.avs.auth.companionservice.CompanionServiceClient.java
/** * Loads the CA certificate into an in-memory keystore and creates an {@link SSLSocketFactory}. * * @return SSLSocketFactory//ww w.j a v a 2s . c o m */ public SSLSocketFactory getPinnedSSLSocketFactory() { InputStream caCertInputStream = null; InputStream clientKeyPair = null; try { // Load the CA certificate into memory CertificateFactory cf = CertificateFactory.getInstance("X.509"); caCertInputStream = new FileInputStream(deviceConfig.getCompanionServiceInfo().getSslCaCert()); Certificate caCert = cf.generateCertificate(caCertInputStream); // Load the CA certificate into the trusted KeyStore KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); trustStore.setCertificateEntry("myca", caCert); // Create a TrustManagerFactory with the trusted KeyStore TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); // Load the client certificate and private key into another KeyStore KeyStore keyStore = KeyStore.getInstance("PKCS12"); clientKeyPair = new FileInputStream(deviceConfig.getCompanionServiceInfo().getSslClientKeyStore()); keyStore.load(clientKeyPair, deviceConfig.getCompanionServiceInfo().getSslClientKeyStorePassphrase().toCharArray()); // Create a TrustManagerFactory with the client key pair KeyStore KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, deviceConfig.getCompanionServiceInfo().getSslClientKeyStorePassphrase().toCharArray()); // Initialize the SSLContext and return an SSLSocketFactory; SSLContext sc = SSLContext.getInstance("TLS"); sc.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); return sc.getSocketFactory(); } catch (CertificateException | KeyStoreException | UnrecoverableKeyException | NoSuchAlgorithmException | IOException | KeyManagementException e) { throw new RuntimeException("The KeyStore for contacting the Companion Service could not be loaded.", e); } finally { IOUtils.closeQuietly(caCertInputStream); IOUtils.closeQuietly(clientKeyPair); } }
From source file:groovyx.net.http.AuthConfig.java
/** * Sets a certificate to be used for SSL authentication. See * {@link Class#getResource(String)} for how to get a URL from a resource * on the classpath.//from w w w . j av a2 s. com * @param certURL URL to a JKS keystore where the certificate is stored. * @param password password to decrypt the keystore */ public void certificate(String certURL, String password) throws GeneralSecurityException, IOException { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); InputStream jksStream = new URL(certURL).openStream(); try { keyStore.load(jksStream, password.toCharArray()); } finally { jksStream.close(); } SSLSocketFactory ssl = new SSLSocketFactory(keyStore, password); ssl.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); builder.getClient().getConnectionManager().getSchemeRegistry().register(new Scheme("https", ssl, 443)); }
From source file:com.vkassin.mtrade.CSPLicense.java
public HttpClient getNewHttpClient() { try {/* w w w . j a va2 s.c o m*/ KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new MySSLSocketFactory(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); return new DefaultHttpClient(ccm, params); } catch (Exception e) { return new DefaultHttpClient(); } }
From source file:br.ufsc.das.gtscted.shibbauth.Connection.java
public Connection() throws ClientProtocolException, IOException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException { SSLSocketFactory socketFactory; httpClient = new DefaultHttpClient(); KeyStore trustStore;/*ww w. ja v a 2 s . c om*/ trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); // usando a nova SSLSocketFactory. Ver links abaixo: // http://groups.google.com/group/android-developers/browse_thread/thread/d9b914c0dca5a702 // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4523989 // http://exampledepot.com/egs/javax.net.ssl/TrustAll.html // http://stackoverflow.com/questions/2642777/trusting-all-certificates-using-httpclient-over-https // http://stackoverflow.com/questions/2899079/custom-ssl-handling-stopped-working-on-android-2-2-froyo socketFactory = new MySSLSocketFactory(trustStore); Scheme scheme = new Scheme("https", socketFactory, 443); httpClient.getConnectionManager().getSchemeRegistry().register(scheme); }
From source file:at.gv.egovernment.moa.id.demoOA.Configuration.java
public KeyStore getPVP2KeyStore() throws ConfigurationException { try {//from ww w . j a v a2 s .c o m if (keyStore == null) { String keystoretype = getPVP2MetadataKeystoreType(); if (MiscUtil.isEmpty(keystoretype)) { keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); } else { keyStore = KeyStore.getInstance(keystoretype); } String file = getPVP2MetadataKeystoreURL(); if (MiscUtil.isEmpty(file)) { throw new ConfigurationException("KeyStoreURL is empty"); } FileInputStream inputStream = new FileInputStream(file); keyStore.load(inputStream, getPVP2MetadataKeystorePassword().toCharArray()); inputStream.close(); } return keyStore; } catch (Exception e) { throw new ConfigurationException("KeyStore intialization FAILED", e); } }