List of usage examples for java.security KeyStore getDefaultType
public static final String getDefaultType()
From source file:org.disrupted.rumble.database.statistics.StatisticManager.java
public void onEventAsync(LinkLayerStarted event) { if (!event.linkLayerIdentifier.equals(WifiLinkLayerAdapter.LinkLayerIdentifier)) return;// w w w . j a v a 2 s . c om if (RumblePreferences.UserOkWithSharingAnonymousData(RumbleApplication.getContext()) && RumblePreferences.isTimeToSync(RumbleApplication.getContext())) { if (!NetUtil.isURLReachable("http://disruptedsystems.org/")) return; try { // generate the JSON file byte[] json = generateStatJSON().toString().getBytes(); // configure SSL CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream caInput = new BufferedInputStream( RumbleApplication.getContext().getAssets().open("certs/disruptedsystemsCA.pem")); Certificate ca = cf.generateCertificate(caInput); String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("ca", ca); String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tmf.getTrustManagers(), null); URL url = new URL("https://data.disruptedsystems.org/post"); HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.setSSLSocketFactory(sslContext.getSocketFactory()); // then configure the header urlConnection.setInstanceFollowRedirects(true); urlConnection.setRequestMethod("POST"); urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Content-Type", "application/json"); urlConnection.setRequestProperty("Accept", "application/json"); urlConnection.setRequestProperty("charset", "utf-8"); urlConnection.setRequestProperty("Content-Length", Integer.toString(json.length)); urlConnection.setUseCaches(false); // connect and send the JSON urlConnection.setConnectTimeout(10 * 1000); urlConnection.connect(); urlConnection.getOutputStream().write(json); if (urlConnection.getResponseCode() != 200) throw new IOException("request failed"); // erase the database RumblePreferences.updateLastSync(RumbleApplication.getContext()); cleanDatabase(); } catch (Exception ex) { Log.e(TAG, "Failed to establish SSL connection to server: " + ex.toString()); } } }
From source file:com.cloudbees.eclipse.core.util.Utils.java
/** * @param url//w ww.j av a 2s . c om * url to connec. Required to determine proxy settings if available. If <code>null</code> then proxy is not * configured for the client returned. * @return * @throws CloudBeesException */ public final static DefaultHttpClient getAPIClient(String url) throws CloudBeesException { DefaultHttpClient httpclient = new DefaultHttpClient(); try { HttpClientParams.setCookiePolicy(httpclient.getParams(), CookiePolicy.BROWSER_COMPATIBILITY); String version = null; if (CloudBeesCorePlugin.getDefault() != null) { version = CloudBeesCorePlugin.getDefault().getBundle().getVersion().toString(); } else { version = "n/a"; } HttpProtocolParams.setUserAgent(httpclient.getParams(), "CBEclipseToolkit/" + version); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); CloudBeesCorePlugin plugin = CloudBeesCorePlugin.getDefault(); URL truststore; if (plugin == null) { //Outside the OSGI environment, try to open the stream from the current dir. truststore = new File("truststore").toURI().toURL(); } else { truststore = plugin.getBundle().getResource("truststore"); } InputStream instream = truststore.openStream(); try { trustStore.load(instream, "123456".toCharArray()); } finally { instream.close(); } TrustStrategy trustAllStrategy = new TrustStrategy() { @Override public boolean isTrusted(final X509Certificate[] chain, final String authType) throws CertificateException { return true; } }; SSLSocketFactory socketFactory = new SSLSocketFactory(SSLSocketFactory.TLS, null, null, trustStore, null, trustAllStrategy, SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); // Override https handling to use provided truststore @SuppressWarnings("deprecation") Scheme sch = new Scheme("https", socketFactory, 443); httpclient.getConnectionManager().getSchemeRegistry().register(sch); HttpParams params = httpclient.getParams(); //TODO Make configurable from the UI? HttpConnectionParams.setConnectionTimeout(params, 10000); HttpConnectionParams.setSoTimeout(params, 10000); if (CloudBeesCorePlugin.getDefault() != null) { // exclude proxy support when running outside eclipse IProxyService ps = CloudBeesCorePlugin.getDefault().getProxyService(); if (ps.isProxiesEnabled()) { IProxyData[] pr = ps.select(new URI(url)); //NOTE! For now we use just the first proxy settings with type HTTP or HTTPS to try out the connection. If configuration has more than 1 conf then for now this likely won't work! if (pr != null) { for (int i = 0; i < pr.length; i++) { IProxyData prd = pr[i]; if (IProxyData.HTTP_PROXY_TYPE.equals(prd.getType()) || IProxyData.HTTPS_PROXY_TYPE.equals(prd.getType())) { String proxyHost = prd.getHost(); int proxyPort = prd.getPort(); String proxyUser = prd.getUserId(); String proxyPass = prd.getPassword(); HttpHost proxy = new HttpHost(proxyHost, proxyPort); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); if (prd.isRequiresAuthentication()) { List authpref = new ArrayList(); authpref.add(AuthPolicy.BASIC); AuthScope authScope = new AuthScope(proxyHost, proxyPort); httpclient.getCredentialsProvider().setCredentials(authScope, new UsernamePasswordCredentials(proxyUser, proxyPass)); } break; } } } } } /* httpclient.getHostConfiguration().setProxy(proxyHost,proxyPort); //if there are proxy credentials available, set those too Credentials proxyCredentials = null; String proxyUser = beesClientConfiguration.getProxyUser(); String proxyPassword = beesClientConfiguration.getProxyPassword(); if(proxyUser != null || proxyPassword != null) proxyCredentials = new UsernamePasswordCredentials(proxyUser, proxyPassword); if(proxyCredentials != null) client.getState().setProxyCredentials(AuthScope.ANY, proxyCredentials); */ return httpclient; } catch (Exception e) { throw new CloudBeesException("Error while initiating access to JSON APIs!", e); } }
From source file:module.signature.util.XAdESValidator.java
private static void loadNeededCerts() { try {/* w w w . ja v a 2 s . c o m*/ InputStream keyStoreIS = XAdESValidator.class.getResourceAsStream("/resources/certs/cc-keystore"); cartaoCidadaoKeyStore = KeyStore.getInstance(KeyStore.getDefaultType()); cartaoCidadaoKeyStore.load(keyStoreIS, "123456".toCharArray()); InputStream tsaCertIS = XAdESValidator.class.getResourceAsStream("/resources/certs/tsaCert.cer"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); while (tsaCertIS.available() != 0) { //not the fastest way to do it.. but who cares baos.write(tsaCertIS.read()); } tsaCert = new X509CertificateHolder(baos.toByteArray()); } catch (KeyStoreException e) { logger.error("Error loading the needed certificates", e); } catch (NoSuchAlgorithmException e) { logger.error("Error loading the needed certificates", e); } catch (CertificateException e) { logger.error("Error loading the needed certificates", e); } catch (IOException e) { logger.error("Error loading the needed certificates", e); } }
From source file:com.codingPower.framework.worker.FileNetWorker.java
/** * ?httpClient//from w w w . j av a2 s . c om * @return */ protected HttpClient getHttpClient() { try { 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:ddf.catalog.source.opensearch.SecureRemoteConnectionImpl.java
/** * Creates a new SSLSocketFactory from a truststore and keystore. This is used during SSL * communications with the server./*from w w w . j ava 2 s . c o m*/ * * @param trustStoreLoc * File path to the truststore. * @param trustStorePass * Password to the truststore. * @param keyStoreLoc * File path to the keystore. * @param keyStorePass * Password to the keystore. * @return new SSLSocketFactory instance containing the trust and key stores. * @throws KeyStoreException * @throws IOException * @throws CertificateException * @throws NoSuchAlgorithmException * @throws UnrecoverableKeyException * @throws KeyManagementException */ public SSLSocketFactory createSocket(String trustStoreLoc, String trustStorePass, String keyStoreLoc, String keyStorePass) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException, KeyManagementException { String methodName = "createSocket"; LOGGER.debug("ENTERING: " + methodName); LOGGER.debug("trustStoreLoc = " + trustStoreLoc); FileInputStream trustFIS = new FileInputStream(trustStoreLoc); LOGGER.debug("keyStoreLoc = " + keyStoreLoc); FileInputStream keyFIS = new FileInputStream(keyStoreLoc); // truststore stuff KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); try { LOGGER.debug("Loading trustStore"); trustStore.load(trustFIS, trustStorePass.toCharArray()); } finally { IOUtils.closeQuietly(trustFIS); } TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(trustStore); LOGGER.debug("trust manager factory initialized"); // keystore stuff KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); try { LOGGER.debug("Loading keyStore"); keyStore.load(keyFIS, keyStorePass.toCharArray()); } finally { IOUtils.closeQuietly(keyFIS); } KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keyStore, keyStorePass.toCharArray()); LOGGER.debug("key manager factory initialized"); // ssl context SSLContext sslCtx = SSLContext.getInstance("TLS"); sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); LOGGER.debug("EXITING: " + methodName); return sslCtx.getSocketFactory(); }
From source file:io.kodokojo.config.module.SecurityModule.java
@Provides @Singleton//from w ww . java 2 s. c o m SSLKeyPair provideSSLKeyPair(SecurityConfig securityConfig) { if (securityConfig == null) { throw new IllegalArgumentException("securityConfig must be defined."); } if (StringUtils.isNotBlank(securityConfig.wildcardPemPath())) { File pemFile = new File(securityConfig.wildcardPemPath()); try { String content = IOUtils.toString(new FileReader(pemFile)); String contentPrivate = RSAUtils.extractPrivateKey(content); String contentPublic = RSAUtils.extractPublic(content); RSAPrivateKey rsaPrivateKey = RSAUtils.readRsaPrivateKey(new StringReader(contentPrivate)); X509Certificate certificate = RSAUtils.readRsaPublicKey(new StringReader(contentPublic)); RSAPublicKey rsaPublicKey = (RSAPublicKey) certificate.getPublicKey(); X509Certificate[] certificates = new X509Certificate[1]; certificates[0] = certificate; LOGGER.info( "Using Wildcard SSL certificat {} from path {}to provide Certificat to all instances of Kodo Kojo. ", certificate.getSubjectDN().toString(), securityConfig.wildcardPemPath()); return new SSLKeyPair(rsaPrivateKey, rsaPublicKey, certificates); } catch (IOException e) { throw new IllegalArgumentException("Unable to read pem file " + pemFile.getAbsolutePath() + ".", e); } } else { try { KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(new FileInputStream(System.getProperty("javax.net.ssl.keyStore")), System.getProperty("javax.net.ssl.keyStorePassword", "").toCharArray()); RSAPrivateCrtKey key = (RSAPrivateCrtKey) ks.getKey(securityConfig.sslRootCaKsAlias(), securityConfig.sslRootCaKsPassword().toCharArray()); if (key == null) { return null; } RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent()); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(publicKeySpec); Certificate[] certificateChain = ks.getCertificateChain(securityConfig.sslRootCaKsAlias()); List<X509Certificate> x509Certificates = Arrays.asList(certificateChain).stream() .map(c -> (X509Certificate) c).collect(Collectors.toList()); LOGGER.info( "Using a CA SSL certificat {} from keystore to provide Certificat to all instances of Kodo Kojo. ", securityConfig.sslRootCaKsAlias(), System.getProperty("javax.net.ssl.keyStore")); return new SSLKeyPair(key, publicKey, x509Certificates.toArray(new X509Certificate[x509Certificates.size()])); } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | InvalidKeySpecException | CertificateException | IOException e) { throw new RuntimeException("Unable to open default Keystore", e); } } }
From source file:hu.balazsbakai.sq.util.RestUtil.java
private DefaultHttpClient getNewTrustedHttpClient() { try {/* ww w.ja va 2 s.c o m*/ KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new CustomTrustedSSLSocketFactory(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); HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(params, SOCKET_TIMEOUT); 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) { LogUtil.e("Exception", e); return new DefaultHttpClient(); } }
From source file:org.zaproxy.zap.extension.dynssl.SslCertificateUtils.java
/** * Creates a new Root CA certificate and returns private and public key as * {@link KeyStore}. The {@link KeyStore#getDefaultType()} is used. * * @return/*from w w w. java 2 s. co m*/ * @throws NoSuchAlgorithmException If no providers are found * for 'RSA' key pair generator * or 'SHA1PRNG' Secure random number generator * @throws IllegalStateException in case of errors during assembling {@link KeyStore} */ public static final KeyStore createRootCA() throws NoSuchAlgorithmException { final Date startDate = Calendar.getInstance().getTime(); final Date expireDate = new Date(startDate.getTime() + (DEFAULT_VALID_DAYS * 24L * 60L * 60L * 1000L)); final KeyPairGenerator g = KeyPairGenerator.getInstance("RSA"); g.initialize(2048, SecureRandom.getInstance("SHA1PRNG")); final KeyPair keypair = g.genKeyPair(); final PrivateKey privKey = keypair.getPrivate(); final PublicKey pubKey = keypair.getPublic(); Security.addProvider(new BouncyCastleProvider()); Random rnd = new Random(); // using the hash code of the user's name and home path, keeps anonymity // but also gives user a chance to distinguish between each other X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE); namebld.addRDN(BCStyle.CN, "OWASP Zed Attack Proxy Root CA"); namebld.addRDN(BCStyle.L, Integer.toHexString(System.getProperty("user.name").hashCode()) + Integer.toHexString(System.getProperty("user.home").hashCode())); namebld.addRDN(BCStyle.O, "OWASP Root CA"); namebld.addRDN(BCStyle.OU, "OWASP ZAP Root CA"); namebld.addRDN(BCStyle.C, "xx"); X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(namebld.build(), BigInteger.valueOf(rnd.nextInt()), startDate, expireDate, namebld.build(), pubKey); KeyStore ks = null; try { certGen.addExtension(Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(pubKey.getEncoded())); certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); certGen.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign)); KeyPurposeId[] eku = { KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth, KeyPurposeId.anyExtendedKeyUsage }; certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(eku)); final ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC") .build(privKey); final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC") .getCertificate(certGen.build(sigGen)); ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null, null); ks.setKeyEntry(SslCertificateService.ZAPROXY_JKS_ALIAS, privKey, SslCertificateService.PASSPHRASE, new Certificate[] { cert }); } catch (final Exception e) { throw new IllegalStateException("Errors during assembling root CA.", e); } return ks; }
From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java
/** * This method generates a certificate from a base64 encoded certificate string and add to the configured trust * store./*from w ww .j a v a2 s. co m*/ * * @param base64Cert : The base 64 encoded string of the server certificate. * @param alias : The alias for the certificate. * @return : ResponseCode which matches the execution result. * * Response Codes. * SUCCESS : If certificate added successfully. * INTERNAL_SERVER_ERROR : If any internal error occurred * ALIAS_EXISTS_IN_TRUST_STORE : If the alias exists in trust store. * CERTIFICATE_EXPIRED : If the given certificate is expired. */ public ResponseCode addCertificateToTrustStore(String base64Cert, String alias) { boolean isCertExists = false; boolean expired = false; InputStream serverCert = null; try { //Decode base64 encoded certificate. byte[] cert = (Base64.decodeBase64(base64Cert.getBytes(CHARSET_UTF_8))); serverCert = new ByteArrayInputStream(cert); if (serverCert.available() == 0) { log.error("Certificate is empty for the provided alias " + alias); return ResponseCode.INTERNAL_SERVER_ERROR; } //Read the client-truststore.jks into a KeyStore. File trustStoreFile = new File(TRUST_STORE); localTrustStoreStream = new FileInputStream(trustStoreFile); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(localTrustStoreStream, TRUST_STORE_PASSWORD); CertificateFactory cf = CertificateFactory.getInstance(CERTIFICATE_TYPE); while (serverCert.available() > 0) { Certificate certificate = cf.generateCertificate(serverCert); //Check whether the Alias exists in the trust store. if (trustStore.containsAlias(alias)) { isCertExists = true; } else { /* * If alias is not exists, check whether the certificate is expired or not. If expired set the * expired flag. * */ X509Certificate x509Certificate = (X509Certificate) certificate; if (x509Certificate.getNotAfter().getTime() <= System.currentTimeMillis()) { expired = true; if (log.isDebugEnabled()) { log.debug("Provided certificate is expired."); } } else { //If not expired add the certificate to trust store. trustStore.setCertificateEntry(alias, certificate); } } } fileOutputStream = new FileOutputStream(trustStoreFile); trustStore.store(fileOutputStream, TRUST_STORE_PASSWORD); responseCode = expired ? ResponseCode.CERTIFICATE_EXPIRED : isCertExists ? ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE : ResponseCode.SUCCESS; } catch (CertificateException e) { log.error("Error loading certificate.", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (FileNotFoundException e) { log.error("Error reading/ writing to the certificate file.", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (NoSuchAlgorithmException e) { log.error("Could not find the algorithm to load the certificate.", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (UnsupportedEncodingException e) { log.error("Error retrieving certificate from String", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (KeyStoreException e) { log.error("Error reading certificate contents.", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (IOException e) { log.error("Error in loading the certificate.", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } finally { closeStreams(localTrustStoreStream, fileOutputStream, serverCert); } return responseCode; }
From source file:cn.com.mozilla.sync.utils.HttpsTransport.java
public HttpsTransport() { // Create SSL socket factory if (ALLOW_INVALID_CERTS) { try {/*from w ww . j a v a2 s .c om*/ KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); mSslSocketFactory = new EasySSLSocketFactory(trustStore); } catch (GeneralSecurityException e) { Log.w("Firefoxmini", e.toString()); } catch (IOException e) { Log.w("Firefoxmini", e.toString()); } } if (mSslSocketFactory == null) { mSslSocketFactory = SSLSocketFactory.getSocketFactory(); } // Create ClientConnectionManager SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("https", mSslSocketFactory, HTTPS_PORT_DEFAULT)); mClientConMgr = new SingleClientConnManager(sHttpParams, schemeRegistry); }