List of usage examples for java.security KeyStore load
public final void load(InputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException
From source file:com.google.jenkins.plugins.credentials.oauth.P12ServiceAccountConfig.java
private KeyStore getP12KeyStore() throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException { FileInputStream in = null;/*from w ww . j a v a2 s. c o m*/ try { KeyStore keyStore = KeyStore.getInstance("PKCS12"); KeyUtils.updatePermissions(new File(p12KeyFile)); in = new FileInputStream(p12KeyFile); keyStore.load(in, DEFAULT_P12_SECRET.toCharArray()); return keyStore; } finally { IOUtils.closeQuietly(in); } }
From source file:com.mymed.android.myjam.controller.CallManager.java
protected SchemeRegistry createSchemeRegistry(Context context) { InputStream certInStream = context.getResources().openRawResource(R.raw.mymed_truststore); SchemeRegistry schemeRegistry = new SchemeRegistry(); // Create and initialize scheme registry schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); SSLSocketFactory sslf = null; try {/*from w w w . jav a 2 s. com*/ KeyStore mymedTrusted = KeyStore.getInstance("BKS"); mymedTrusted.load(certInStream, "alcotra".toCharArray()); sslf = new SSLSocketFactory(mymedTrusted); sslf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } catch (KeyStoreException e) { Log.e(TAG, "Wrong keystore type.", e); } catch (KeyManagementException e) { Log.e(TAG, "Error creating SSLSocketFactory.", e); } catch (NoSuchAlgorithmException e) { Log.e(TAG, "Error creating SSLSocketFactory.", e); } catch (UnrecoverableKeyException e) { Log.e(TAG, "Error creating SSLSocketFactory.", e); } catch (CertificateException e) { Log.e(TAG, "Error loading keystore certificate.", e); } catch (IOException e) { Log.e(TAG, "Error creating scheme registry.", e); } finally { if (sslf != null) { schemeRegistry.register(new Scheme("https", sslf, 8081)); } try { certInStream.close(); } catch (IOException e) { Log.e(TAG, "Error closing the certificate stream.", e); } } return schemeRegistry; }
From source file:br.com.intercomex.ws.GnreConfigUF.java
/** * This is a sample web service operation *///from w w w . j a v a 2 s . c o m @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.muhia.app.psi.integ.config.ke.shared.SharedWsClientConfiguration.java
@Bean(name = "sharedSecureHttpClient") public CloseableHttpClient secureHttpClient() { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); try {// w w w. ja v a2 s. c om /* TODO: Modify to accept only specific certificates, test implementation is as below, TODO: need to find a way of determining if server url is https or not TODO: Whether we have imported the certificate or not */ KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); Resource resource = loaderService.getResource(properties.getSharedKeystorePath()); keyStore.load(resource.getInputStream(), hasher.getDecryptedValue(properties.getSharedKeystorePassword()).toCharArray()); SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()) .loadKeyMaterial(keyStore, hasher.getDecryptedValue(properties.getSharedKeystorePassword()).toCharArray()) .build(); // SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true).build(); RequestConfig config = RequestConfig.custom() .setConnectTimeout(properties.getSharedTransportConnectionTimeout()) .setConnectionRequestTimeout(properties.getSharedTransportConnectionRequestTimeout()) .setSocketTimeout(properties.getSharedTransportReadTimeout()).build(); CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials( sharedDataDTO.getTransportUsername(), sharedDataDTO.getTransportPassword()); provider.setCredentials(AuthScope.ANY, credentials); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); connManager.setMaxTotal(properties.getSharedPoolMaxHost()); connManager.setDefaultMaxPerRoute(properties.getSharedPoolDefaultmaxPerhost()); connManager.setValidateAfterInactivity(properties.getSharedPoolValidateAfterInactivity()); httpClient = HttpClientBuilder.create().setSSLContext(sslContext) .setSSLHostnameVerifier(new NoopHostnameVerifier()).setDefaultRequestConfig(config) .setDefaultCredentialsProvider(provider).setConnectionManager(connManager) .evictExpiredConnections().addInterceptorFirst(new RemoveHttpHeadersInterceptor()).build(); } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException | CertificateException | IOException | UnrecoverableKeyException e) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, e.getMessage(), e); } return httpClient; }
From source file:org.drugis.addis.config.MainConfig.java
@Bean public HttpClient httpClient(RequestConfig requestConfig) throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException { KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream(KEYSTORE_PATH), KEYSTORE_PASSWORD.toCharArray()); String ADDIS_LOCAL = System.getenv("ADDIS_LOCAL"); SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadKeyMaterial(keyStore, KEYSTORE_PASSWORD.toCharArray()); if (ADDIS_LOCAL != null) { String TRUSTSTORE_PATH = WebConstants.loadSystemEnv("TRUSTSTORE_PATH"); sslContextBuilder.loadTrustMaterial(new File(TRUSTSTORE_PATH)); }//from ww w. ja v a 2s . c o m sslContextBuilder.build(); SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory( sslContextBuilder.build()); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", connectionSocketFactory).register("http", new PlainConnectionSocketFactory()) .build(); HttpClientConnectionManager clientConnectionManager = new PoolingHttpClientConnectionManager(registry); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); return httpClientBuilder.setConnectionManager(clientConnectionManager).setMaxConnTotal(20) .setMaxConnPerRoute(2).setDefaultRequestConfig(requestConfig).build(); }
From source file:org.godotengine.godot.utils.HttpRequester.java
private HttpClient getNewHttpClient() { try {//from w ww .ja va 2s . c om KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new CustomSSLSocketFactory(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:com.vmware.identity.idm.server.ClientCertTestUtils.java
private KeyStore loadKeyStoreWithType(String keyStoreFile, String pass, String storeType) { KeyStore ks = null; try {/*from ww w.jav a 2 s . c o m*/ ks = KeyStore.getInstance(storeType); ks.load(getClass().getClassLoader().getResourceAsStream(keyStoreFile), pass.toCharArray()); } catch (FileNotFoundException fnfe) { throw new IllegalArgumentException(String.format("keystore file [%s] not found", keyStoreFile), fnfe); } catch (IOException ioe) { String errMsg = ioe.getCause() instanceof UnrecoverableKeyException ? "Wrong keystore password" : ""; throw new IllegalArgumentException(errMsg, ioe); } catch (Exception e) { throw new IllegalStateException(e); } return ks; }
From source file:com.thoughtworks.go.server.util.HttpTestUtil.java
private void prepareCertStore(File serverKeyStore) { KeyPair keyPair = generateKeyPair(); X509Certificate cert = generateCert(keyPair); FileOutputStream os = null;//ww w . ja v a2 s . c o m try { KeyStore store = KeyStore.getInstance("JKS"); store.load(null, null); store.setKeyEntry("test", keyPair.getPrivate(), STORE_PASSWORD.toCharArray(), new Certificate[] { cert }); os = new FileOutputStream(serverKeyStore); store.store(os, STORE_PASSWORD.toCharArray()); } catch (Exception e) { throw new RuntimeException(e); } finally { if (os != null) { IOUtils.closeQuietly(os); } } }
From source file:se.vgregion.delegation.server.Server.java
/** * This method sets up the security./*from w ww.j a v a 2 s.c om*/ * * @param port * @throws IOException * @throws GeneralSecurityException */ private void setupServerEngineFactory(int port) throws IOException, GeneralSecurityException { TLSServerParameters tlsParams = new TLSServerParameters(); String userhome = System.getProperty("user.home"); String certFilePath = userhome + "/.delegation-service/" + propertiesBean.getCertFileName(); // String trustStoreFilePath = userhome + "/.delegation-service/prod-truststore.jks"; String trustStoreFilePath = userhome + "/.delegation-service/" + propertiesBean.getClientAuthCertFilename(); InputStream resourceAsStream = new FileInputStream(certFilePath); KeyStore keyStore = KeyStore.getInstance("PKCS12"); try { keyStore.load(resourceAsStream, propertiesBean.getCertPass().toCharArray()); } finally { resourceAsStream.close(); } KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509"); keyManagerFactory.init(keyStore, propertiesBean.getCertPass().toCharArray()); tlsParams.setKeyManagers(keyManagerFactory.getKeyManagers()); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509"); // trustManagerFactory.init(keyStore); InputStream is = new FileInputStream(trustStoreFilePath); KeyStore trustStore = KeyStore.getInstance("JKS"); // trustStore.load(is, "password".toCharArray()); trustStore.load(is, propertiesBean.getClientAuthCertPass().toCharArray()); trustManagerFactory.init(trustStore); TrustManager[] trustMgrs = trustManagerFactory.getTrustManagers(); tlsParams.setTrustManagers(trustMgrs); // FiltersType filter = new FiltersType(); // filter.getInclude().add(".*"); // tlsParams.setCipherSuitesFilter(filter); ClientAuthentication clientAuth = new ClientAuthentication(); // clientAuth.setRequired(true); // clientAuth.setWant(true); clientAuth.setRequired(true); clientAuth.setWant(false); tlsParams.setClientAuthentication(clientAuth); // if (propertiesBean.isClientCertSecurityActive()) { // CertificateConstraintsType constraints = new CertificateConstraintsType(); // DNConstraintsType constraintsType = new DNConstraintsType(); // // constraintsType.setCombinator(CombinatorType.ANY); // System.out.println("propertiesBean.getRegularExpressionClientCert() " // + propertiesBean.getRegularExpressionClientCert()); // String regularExpression = propertiesBean.getRegularExpressionClientCert(); // // constraintsType.getRegularExpression().add(regularExpression); // constraints.setSubjectDNConstraints(constraintsType); // tlsParams.setCertConstraints(constraints); // } engineFactory = new JettyHTTPServerEngineFactory(); engineFactory.setTLSServerParametersForPort(port, tlsParams); }
From source file:com.adito.keystore.actions.ShowKeyStoreDispatchAction.java
/** * @param mapping//from ww w. j a v a 2 s . c o m * @param form * @param request * @param response * @return ActionForward * @throws Exception */ public ActionForward exportPrivate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String sel = ((ShowKeyStoreForm) form).getSelectedItem(); KeyStore systemClientStore = ((ShowKeyStoreForm) form).getSelectedKeyStore().getKeyStore(); FileDownloadPageInterceptListener l = (FileDownloadPageInterceptListener) CoreUtil .getPageInterceptListenerById(request.getSession(), "fileDownload"); if (l == null) { l = new FileDownloadPageInterceptListener(); CoreUtil.addPageInterceptListener(request.getSession(), l); } File clientCertFile = new File(CoreUtil.getTempDownloadDirectory(getSessionInfo(request)), sel + ".p12"); FileOutputStream out = new FileOutputStream(clientCertFile); char[] password = ((ShowKeyStoreForm) form).getSelectedKeyStore().getKeyStorePassword().toCharArray(); if (systemClientStore.isKeyEntry(sel)) { PrivateKey keypair = ((ShowKeyStoreForm) form).getSelectedKeyStore().getPrivateKey(sel, password); KeyStore userStore = KeyStore.getInstance("PKCS12", "BC"); userStore.load(null, null); userStore.setKeyEntry(sel, keypair, ((ShowKeyStoreForm) form).getPassword().toCharArray(), ((ShowKeyStoreForm) form).getSelectedKeyStore().getCertificateChain(sel)); userStore.store(out, ((ShowKeyStoreForm) form).getPassword().toCharArray()); out.close(); } l.addDownload(new CSRDownload(clientCertFile, clientCertFile.getName(), "application/octet-stream", mapping.findForward("success"), "exportPrivateKey.message", "keystore", sel)); return mapping.findForward("success"); }