List of usage examples for java.security KeyStore getInstance
public static KeyStore getInstance(String type) throws KeyStoreException
From source file:com.github.technosf.posterer.models.impl.KeyStoreBean.java
/** * Instantiates a {@code KeyStoreBean} wrapping the given keystore * <p>//from ww w . j a va 2 s . c om * Loads the Key Store file into a {@code KeyStore} and checks the password. * If the Key Store * can be accessed successfully, validation is successful.. * * @param file * the KeyStore file * @param password * the Key Store password * @throws KeyStoreBeanException * Thrown when a {@code KeyStoreBean} cannot be created. */ @SuppressWarnings("null") public KeyStoreBean(final File keyStoreFile, final String keyStorePassword) throws KeyStoreBeanException { file = keyStoreFile; password = keyStorePassword; InputStream inputStream = null; /* * Check file existence */ if (keyStoreFile == null || !keyStoreFile.exists() || !keyStoreFile.canRead()) // Key Store File cannot be read { throw new KeyStoreBeanException("Cannot read Key Store file"); } try // to get the file input stream { inputStream = Files.newInputStream(keyStoreFile.toPath(), StandardOpenOption.READ); } catch (IOException e) { throw new KeyStoreBeanException("Error reading Key Store file", e); } // Get the file name and extension fileName = FilenameUtils.getName(keyStoreFile.getName()); String fileExtension = FilenameUtils.getExtension(keyStoreFile.getName().toLowerCase()); /* * Identify keystore type, and create an instance */ try { switch (fileExtension) { case "p12": keyStore = KeyStore.getInstance("PKCS12"); break; case "jks": keyStore = KeyStore.getInstance("JKS"); break; default: throw new KeyStoreBeanException(String.format("Unknown keystore extention: [%1$s]", fileExtension)); } } catch (KeyStoreException e) { throw new KeyStoreBeanException("Cannot get keystore instance"); } /* * Load the keystore data into the keystore instance */ try { keyStore.load(inputStream, password.toCharArray()); valid = true; } catch (NoSuchAlgorithmException | CertificateException | IOException e) { throw new KeyStoreBeanException("Cannot load the KeyStore", e); } /* * Key store loaded, so config the bean */ try { type = keyStore.getType(); size = keyStore.size(); Enumeration<String> aliasIterator = keyStore.aliases(); while (aliasIterator.hasMoreElements()) { String alias = aliasIterator.nextElement(); certificates.put(alias, keyStore.getCertificate(alias)); } } catch (KeyStoreException e) { throw new KeyStoreBeanException("Cannot process the KeyStore", e); } }
From source file:org.kontalk.client.ClientHTTPConnection.java
public static SSLSocketFactory setupSSLSocketFactory(Context context, PrivateKey privateKey, X509Certificate certificate, boolean acceptAnyCertificate) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, KeyManagementException, UnrecoverableKeyException, NoSuchProviderException { // in-memory keystore KeyManager[] km = null;/* ww w.j a va 2 s . co m*/ if (privateKey != null && certificate != null) { KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(null, null); keystore.setKeyEntry("private", privateKey, null, new Certificate[] { certificate }); // key managers KeyManagerFactory kmFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmFactory.init(keystore, null); km = kmFactory.getKeyManagers(); } // trust managers TrustManager[] tm; if (acceptAnyCertificate) { tm = new TrustManager[] { new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } } }; } else { // load merged truststore (system + internal) KeyStore trustStore = InternalTrustStore.getTrustStore(context); // builtin keystore TrustManagerFactory tmFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmFactory.init(trustStore); tm = tmFactory.getTrustManagers(); } SSLContext ctx = SSLContext.getInstance("TLSv1"); ctx.init(km, tm, null); return new TlsOnlySocketFactory(ctx.getSocketFactory(), true); }
From source file:com.mgmtp.jfunk.web.ssl.JFunkSSLSocketFactory.java
private KeyStore createStore(final URL url, final char[] password, final String type) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException { log.debug("Initializing key store"); KeyStore keystore = KeyStore.getInstance(type); InputStream is = null;//from w ww .j av a 2 s . c o m try { is = url.openStream(); keystore.load(is, password); return keystore; } finally { IOUtils.closeQuietly(is); } }
From source file:com.shalzz.attendance.wrapper.MySSLSocketFactory.java
/** * Gets a KeyStore containing the Certificate * /*w ww. j av a 2s .c o m*/ * @param cert InputStream of the Certificate * @return KeyStore */ 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 { 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; }
From source file:br.com.intercomex.ws.GnreConfigUF.java
/** * This is a sample web service operation *///from w w w .j ava 2 s . c om @WebMethod(operationName = "consultar") public String consultar(@WebParam(name = "gnreDadosMsg") TConsultaConfigUf gnreDadosMsg) { String retorno = null; loadConfig(); try { //<TConsultaConfigUf xmlns=\"http://www.gnre.pe.gov.br\"><ambiente>1</ambiente><uf>MG</uf><receita>100048</receita></TConsultaConfigUf> String XML_DATA = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:gnr=\"http://www.gnre.pe.gov.br/webservice/GnreConfigUF\">" + "<soap:Header><gnr:gnreCabecMsg><gnr:versaoDados>1.00</gnr:versaoDados></gnr:gnreCabecMsg></soap:Header>" + " <soap:Body><gnr:gnreDadosMsg>" + gnreDadosMsg + "</gnr:gnreDadosMsg></soap:Body></soap:Envelope>"; System.out.println("PARAMETRO envio ==== " + gnreDadosMsg); HttpPost httpPost = new HttpPost(url); httpPost.setHeader(new BasicHeader("Content-Type", "application/soap+xml;charset=UTF-8")); httpPost.setHeader(new BasicHeader("SOAPAction", action)); StringEntity s = new StringEntity(XML_DATA, "UTF-8"); httpPost.setEntity(s); FileInputStream instream = null; FileInputStream instreamTrust = null; KeyStore keyStore = KeyStore.getInstance("PKCS12"); instream = new FileInputStream(new File(caminhoDoCertificadoDoCliente)); keyStore.load(instream, senhaDoCertificadoDoCliente.toCharArray()); KeyStore trustStore = KeyStore.getInstance("JKS"); instreamTrust = new FileInputStream(new File(arquivoCacertsGeradoParaCadaEstado)); trustStore.load(instreamTrust, senhaDoCertificadoDoCliente.toCharArray()); SSLContextBuilder builder = SSLContexts.custom().loadTrustMaterial(trustStore); builder.loadKeyMaterial(keyStore, senhaDoCertificadoDoCliente.toCharArray()); SSLContext sslcontext = builder.build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); CloseableHttpClient httpclientSLL = HttpClients.custom().setSSLSocketFactory(sslsf).build(); System.out.println("executing request" + httpPost.getRequestLine()); HttpResponse response = httpclientSLL.execute(httpPost); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); retorno = EntityUtils.toString(response.getEntity()); System.out.println(retorno); } if (entity != null) { entity.consumeContent(); } httpclient.getConnectionManager().shutdown(); } catch (UnsupportedEncodingException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (KeyStoreException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (FileNotFoundException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (CertificateException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (UnrecoverableKeyException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (KeyManagementException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } return retorno; }
From source file:org.wso2.cdm.agent.utils.HTTPConnectorUtils.java
public static HttpClient getCertifiedHttpClient(Context context) { try {/*from w ww. j a v a 2 s. co m*/ HttpClient client = null; if (CommonUtilities.SERVER_PROTOCOL.toLowerCase().equals("https://")) { Log.e("", "in"); KeyStore localTrustStore = KeyStore.getInstance("BKS"); InputStream in = context.getResources().openRawResource(R.raw.emm_truststore); localTrustStore.load(in, CommonUtilities.TRUSTSTORE_PASSWORD.toCharArray()); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); SSLSocketFactory sslSocketFactory = new SSLSocketFactory(localTrustStore); schemeRegistry.register(new Scheme("https", sslSocketFactory, 443)); HttpParams params = new BasicHttpParams(); ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); client = new DefaultHttpClient(cm, params); } else { client = new DefaultHttpClient(); } return client; } catch (Exception e) { return null; } }
From source file:org.kontalk.client.KontalkConnection.java
@SuppressLint("AllowAllHostnameVerifier") private static void setupSSL(XMPPTCPConnectionConfiguration.Builder builder, boolean direct, PrivateKey privateKey, X509Certificate bridgeCert, boolean acceptAnyCertificate, KeyStore trustStore) { try {//from w w w . java 2s . c o m SSLContext ctx = SSLContext.getInstance("TLS"); KeyManager[] km = null; if (privateKey != null && bridgeCert != null) { // in-memory keystore KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(null, null); keystore.setKeyEntry("private", privateKey, null, new Certificate[] { bridgeCert }); // key managers KeyManagerFactory kmFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmFactory.init(keystore, null); km = kmFactory.getKeyManagers(); // disable PLAIN mechanism if not upgrading from legacy if (!LegacyAuthentication.isUpgrading()) { // blacklist PLAIN mechanism SASLAuthentication.blacklistSASLMechanism("PLAIN"); } } // trust managers TrustManager[] tm; if (acceptAnyCertificate) { tm = new TrustManager[] { new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @SuppressLint("TrustAllX509TrustManager") @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @SuppressLint("TrustAllX509TrustManager") @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } } }; builder.setHostnameVerifier(new AllowAllHostnameVerifier()); } else { // builtin keystore TrustManagerFactory tmFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmFactory.init(trustStore); tm = tmFactory.getTrustManagers(); } ctx.init(km, tm, null); builder.setCustomSSLContext(ctx); if (direct) builder.setSocketFactory(ctx.getSocketFactory()); // SASL EXTERNAL is already enabled in Smack } catch (Exception e) { Log.w(TAG, "unable to setup SSL connection", e); } }
From source file:eu.europa.esig.dss.token.Pkcs12SignatureToken.java
@Override public List<DSSPrivateKeyEntry> getKeys() throws DSSException { List<DSSPrivateKeyEntry> list = new ArrayList<DSSPrivateKeyEntry>(); InputStream input = null;/*from w ww.j a v a 2s. c o m*/ try { KeyStore keyStore = KeyStore.getInstance("PKCS12"); if (pkcs12Data != null) { input = new ByteArrayInputStream(pkcs12Data); } else { input = new FileInputStream(pkcs12File); } keyStore.load(input, password); PasswordProtection pp = new KeyStore.PasswordProtection(password); Enumeration<String> aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (keyStore.isKeyEntry(alias)) { PrivateKeyEntry entry = (PrivateKeyEntry) keyStore.getEntry(alias, pp); final KSPrivateKeyEntry privateKeyEntry = new KSPrivateKeyEntry(entry); list.add(privateKeyEntry); } } } catch (Exception e) { if (e.getCause() instanceof BadPaddingException) { throw new DSSBadPasswordException(MSG.PKCS12_BAD_PASSWORD); } throw new DSSException("Can't initialize Sun PKCS#12 security provider. Reason: " + e.getMessage(), e); } finally { IOUtils.closeQuietly(input); } return list; }
From source file:org.mycontroller.restclient.core.RestHttpClient.java
private CloseableHttpClient getHttpClientTrustAll() { SSLContextBuilder builder = new SSLContextBuilder(); try {/*from ww w .ja v a 2 s. c om*/ KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); builder.loadTrustMaterial(keyStore, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] trustedCert, String nameConstraints) throws CertificateException { return true; } }); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), new AnyHostnameVerifier()); return HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultRequestConfig(customRequestConfig) .build(); } catch (Exception ex) { _logger.error("Exception, ", ex); throw new RuntimeException("Unable to create trust ANY http client. Error: " + ex.getMessage()); } }