List of usage examples for java.security KeyStore getInstance
public static KeyStore getInstance(String type) throws KeyStoreException
From source file:com.amalto.workbench.utils.SSLContextProvider.java
private static KeyManager[] buildKeyManagers(String path, String storePass, String keytype) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException { InputStream stream = null;/*from w ww . j a v a 2 s. c o m*/ try { if (StringUtils.isEmpty(path)) { return null; } if (!new File(path).exists()) { throw new KeyStoreException(Messages.bind(Messages.noKeystoreFile_error, path)); } stream = new FileInputStream(path); KeyStore tks = KeyStore.getInstance(keytype); tks.load(stream, storePass.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); //$NON-NLS-1$ kmf.init(tks, storePass.toCharArray()); return kmf.getKeyManagers(); } finally { IOUtils.closeQuietly(stream); } }
From source file:net.openwatch.acluaz.http.AZHttpClient.java
private SSLSocketFactory newSslSocketFactory() { try {//from ww w.ja va 2 s .com // Get an instance of the Bouncy Castle KeyStore format KeyStore trusted = KeyStore.getInstance("BKS"); // Get the raw resource, which contains the keystore with // your trusted certificates (root and any intermediate certs) InputStream in = context.getResources().openRawResource(R.raw.azkeystore); try { // Initialize the keystore with the provided trusted certificates // Also provide the password of the keystore trusted.load(in, SECRETS.SSL_KEYSTORE_PASS.toCharArray()); } finally { in.close(); } // Pass the keystore to the SSLSocketFactory. The factory is responsible // for the verification of the server certificate. 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.openmeap.util.SSLUtils.java
static public HttpClient getRelaxedSSLVerificationHttpClient() { try {/*from www. ja v a 2 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, FormConstants.CHAR_ENC_DEFAULT); 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:org.authme.android.util.AuthMeHttpClient.java
private SSLSocketFactory newSslSocketFactory() { try {/*from w w w.j a v a2 s . com*/ // 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:org.apache.airavata.datacat.agent.dispatcher.MetadataDispatcher.java
private MetadataDispatcher() throws Exception { KeyStore keyStore = KeyStore.getInstance("JKS"); KeyStore trustStore = KeyStore.getInstance("JKS"); // set up security context if (new File("../security/" + AgentProperties.getInstance().getProperty(Constants.KEYSTORE_FILE, "")) .exists()) {/*from w ww .j a v a 2 s .c o m*/ keyStore.load( new FileInputStream(new File("../security/" + AgentProperties.getInstance().getProperty(Constants.KEYSTORE_FILE, ""))), AgentProperties.getInstance().getProperty(Constants.KEYSTORE_PWD, "").toCharArray()); } else { ; keyStore.load( ClassLoader.getSystemResourceAsStream( "security/" + AgentProperties.getInstance().getProperty(Constants.KEYSTORE_FILE, "")), AgentProperties.getInstance().getProperty(Constants.KEYSTORE_PWD, "").toCharArray()); } if (new File("../security/" + AgentProperties.getInstance().getProperty(Constants.TRUSTSTORE_FILE, "")) .exists()) { keyStore.load( new FileInputStream(new File("../security/" + AgentProperties.getInstance().getProperty(Constants.TRUSTSTORE_FILE, ""))), AgentProperties.getInstance().getProperty(Constants.TRUSTSTORE_PWD, "").toCharArray()); } else { keyStore.load( ClassLoader.getSystemResourceAsStream( "security/" + AgentProperties.getInstance().getProperty(Constants.TRUSTSTORE_FILE, "")), AgentProperties.getInstance().getProperty(Constants.TRUSTSTORE_PWD, "").toCharArray()); } SSLContext sslContext = SSLContexts.custom() .loadKeyMaterial(keyStore, AgentProperties.getInstance().getProperty(Constants.KEYSTORE_PWD, "").toCharArray()) .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build(); sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); rabbitMQPublisher = new RabbitMQPublisher(); }
From source file:com.github.restdriver.clientdriver.integration.SecureClientDriverRuleTest.java
private static KeyStore getKeystore() { try {/* w w w . ja v a2 s . co m*/ ClassLoader loader = SecureClientDriverTest.class.getClassLoader(); byte[] binaryContent = IOUtils.toByteArray(loader.getResourceAsStream("keystore.jks")); KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new ByteArrayInputStream(binaryContent), "password".toCharArray()); return keyStore; } catch (Exception e) { throw new ClientDriverSetupException("Key store could not be loaded.", e); } }
From source file:org.apache.cxf.fediz.integrationtests.HTTPTestUtils.java
public static String sendHttpGet(String url, String user, String password, int returnCodeIDP, int returnCodeRP, int idpPort) throws Exception { CloseableHttpClient httpClient = null; try {//from w w w . j av a2s . c o m CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope("localhost", idpPort), new UsernamePasswordCredentials(user, password)); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks")); try { trustStore.load(instream, "clientpass".toCharArray()); } finally { try { instream.close(); } catch (Exception ex) { ex.printStackTrace(); } } SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()); sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray()); SSLContext sslContext = sslContextBuilder.build(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setDefaultCredentialsProvider(credsProvider); httpClientBuilder.setSSLSocketFactory(sslSocketFactory); httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy()); httpClient = httpClientBuilder.build(); HttpGet httpget = new HttpGet(url); HttpResponse response = httpClient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } Assert.assertTrue("IDP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: " + returnCodeIDP + "]", returnCodeIDP == response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() != 200) { return null; } // Redirect to a POST is not supported without user interaction // http://www.ietf.org/rfc/rfc2616.txt // If the 301 status code is received in response to a request other // than GET or HEAD, the user agent MUST NOT automatically redirect the // request unless it can be confirmed by the user, since this might // change the conditions under which the request was issued. Source source = new Source(EntityUtils.toString(entity)); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); FormFields formFields = source.getFormFields(); List<Element> forms = source.getAllElements(HTMLElementName.FORM); Assert.assertEquals("Only one form expected but got " + forms.size(), 1, forms.size()); String postUrl = forms.get(0).getAttributeValue("action"); Assert.assertNotNull("Form field 'wa' not found", formFields.get("wa")); Assert.assertNotNull("Form field 'wresult' not found", formFields.get("wresult")); for (FormField formField : formFields) { if (formField.getUserValueCount() != 0) { nvps.add(new BasicNameValuePair(formField.getName(), formField.getValues().get(0))); } } HttpPost httppost = new HttpPost(postUrl); httppost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); response = httpClient.execute(httppost); entity = response.getEntity(); System.out.println(response.getStatusLine()); Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: " + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } return EntityUtils.toString(entity); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources if (httpClient != null) { httpClient.close(); } } }
From source file:com.netscape.cmstools.pkcs11.PKCS11KeyFindCLI.java
public void execute(String[] args) throws Exception { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("help")) { printHelp();/*from w w w . j a v a2s.c om*/ return; } if (cmd.hasOption("verbose")) { PKILogger.setLevel(PKILogger.Level.INFO); } else if (cmd.hasOption("debug")) { PKILogger.setLevel(PKILogger.Level.DEBUG); } String tokenName = getConfig().getTokenName(); CryptoToken token = CryptoUtil.getKeyStorageToken(tokenName); KeyStore ks = KeyStore.getInstance("pkcs11"); ks.load(new JSSLoadStoreParameter(token)); Enumeration<String> aliases = ks.aliases(); boolean first = true; while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (ks.isCertificateEntry(alias)) { continue; } Key key = ks.getKey(alias, null); if (key == null) { continue; } if (first) { first = false; } else { System.out.println(); } PKCS11KeyCLI.printKeyInfo(alias, key); } }
From source file:com.netscape.cmstools.pkcs11.PKCS11CertFindCLI.java
public void execute(String[] args) throws Exception { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("help")) { printHelp();/* w ww. j a v a 2 s . c o m*/ return; } if (cmd.hasOption("verbose")) { PKILogger.setLevel(PKILogger.Level.INFO); } else if (cmd.hasOption("debug")) { PKILogger.setLevel(PKILogger.Level.DEBUG); } String tokenName = getConfig().getTokenName(); CryptoToken token = CryptoUtil.getKeyStorageToken(tokenName); KeyStore ks = KeyStore.getInstance("pkcs11"); ks.load(new JSSLoadStoreParameter(token)); Enumeration<String> aliases = ks.aliases(); boolean first = true; while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); Certificate cert = ks.getCertificate(alias); if (cert == null) { continue; } if (first) { first = false; } else { System.out.println(); } PKCS11CertCLI.printCertInfo(alias, cert); } }
From source file:com.vmware.bdd.cli.http.DefaultTrustManager.java
@PostConstruct protected void initKeystore() throws KeyStoreException { this.keyStore = KeyStore.getInstance("jks"); }