List of usage examples for java.security KeyStore getDefaultType
public static final String getDefaultType()
From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java
/** * Method to update the certificate which matches the given alias. * * @param certificate: The base64 encoded certificate string. * @param alias : Alias of the certificate that should be retrieved. * @return :/* w ww .j a v a 2s . com*/ */ public ResponseCode updateCertificate(String certificate, String alias) throws CertificateManagementException { InputStream certificateStream = null; try { File trustStoreFile = new File(TRUST_STORE); localTrustStoreStream = new FileInputStream(trustStoreFile); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(localTrustStoreStream, TRUST_STORE_PASSWORD); if (trustStore.getCertificate(alias) == null) { log.error("Could not update the certificate. The certificate for alias '" + alias + "' is not found" + " in the trust store."); return ResponseCode.CERTIFICATE_NOT_FOUND; } //Generate the certificate from the input string. byte[] cert = (Base64.decodeBase64(certificate.getBytes(CHARSET_UTF_8))); certificateStream = new ByteArrayInputStream(cert); if (certificateStream.available() == 0) { log.error("Certificate is empty for the provided alias " + alias); return ResponseCode.INTERNAL_SERVER_ERROR; } CertificateFactory certificateFactory = CertificateFactory.getInstance(CERTIFICATE_TYPE); Certificate newCertificate = certificateFactory.generateCertificate(certificateStream); X509Certificate x509Certificate = (X509Certificate) newCertificate; if (x509Certificate.getNotAfter().getTime() <= System.currentTimeMillis()) { log.error("Could not update the certificate. The certificate expired."); return ResponseCode.CERTIFICATE_EXPIRED; } // If the certificate is not expired, delete the existing certificate and add the new cert. trustStore.deleteEntry(alias); //Store the certificate in the trust store. trustStore.setCertificateEntry(alias, newCertificate); fileOutputStream = new FileOutputStream(trustStoreFile); trustStore.store(fileOutputStream, TRUST_STORE_PASSWORD); } catch (IOException e) { throw new CertificateManagementException("Error updating certificate.", e); } catch (CertificateException e) { throw new CertificateManagementException("Error generating the certificate.", e); } catch (NoSuchAlgorithmException e) { throw new CertificateManagementException("Error loading the keystore.", e); } catch (KeyStoreException e) { throw new CertificateManagementException("Error updating the certificate in the keystore.", e); } finally { closeStreams(fileOutputStream, certificateStream, localTrustStoreStream); } return ResponseCode.SUCCESS; }
From source file:it.greenvulcano.gvesb.virtual.rest.RestCallOperation.java
private HttpsURLConnection openSecureConnection(URL url) throws Exception { InputStream keyStream = new FileInputStream(truststorePath); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(keyStream, Optional.ofNullable(truststorePassword).orElse("").toCharArray()); TrustManagerFactory trustFactory = TrustManagerFactory.getInstance( Optional.ofNullable(truststoreAlgorithm).orElseGet(TrustManagerFactory::getDefaultAlgorithm)); trustFactory.init(keystore);/*ww w.j a v a2 s . com*/ SSLContext context = SSLContext.getInstance("TLS"); context.init(null, trustFactory.getTrustManagers(), null); HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection(); httpsURLConnection.setSSLSocketFactory(context.getSocketFactory()); httpsURLConnection.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); return httpsURLConnection; }
From source file:org.seedstack.seed.crypto.internal.EncryptionServiceFactoryTest.java
/** * Test method for// w ww.j ava 2s . co m * {@link org.seedstack.seed.crypto.internal.EncryptionServiceFactory#createEncryptionService(org.seedstack.seed.crypto.internal.KeyStoreDefinition, org.seedstack.seed.crypto.internal.CertificateDefinition)} * . Test a bad password to load the keystore. * * @throws Exception if an error occurred */ @Test(expected = RuntimeException.class) public void testCreateEncryptionServiceWithCloseError(@Mocked final KeyStoreDefinition keyStoreDefinition, @Mocked final CertificateDefinition certificateDefinition, @Mocked final KeyStore keyStore, @Mocked final FileInputStream file, @SuppressWarnings("unused") @Mocked final EncryptionServiceImpl asymetricCrypting) throws Exception { new Expectations() { final String pathToKeystore = "pathToKeystore"; final String password = "password"; { keyStoreDefinition.getPath(); returns(pathToKeystore); KeyStore.getInstance(KeyStore.getDefaultType()); returns(keyStore); new FileInputStream(pathToKeystore); result = file; keyStoreDefinition.getPassword(); returns(password); file.close(); result = new IOException("dummy exception"); } }; EncryptionServiceFactory factory = new EncryptionServiceFactory(); factory.createEncryptionService(keyStoreDefinition, certificateDefinition); }
From source file:org.openecomp.sdnc.sli.aai.AAIService.java
public AAIService(URL propURL) { LOG.info("Entered AAIService.ctor"); String runtime = System.getProperty("aaiclient.runtime"); if (runtime != null && runtime.equals("OSGI")) { runtimeOSGI = true;//ww w . j a v a 2 s.co m } else { runtimeOSGI = false; } Properties props = null; try { props = initialize(propURL); AAIRequest.setProperties(props, this); } catch (Exception exc) { LOG.error("AicAAIResource.static", exc); } executor = new AAIRequestExecutor(); user_name = props.getProperty(CLIENT_NAME); user_password = props.getProperty(CLIENT_PWWD); if (user_name == null || user_name.isEmpty()) { LOG.debug("Basic user name is not set"); } if (user_password == null || user_password.isEmpty()) { LOG.debug("Basic password is not set"); } truststore_path = props.getProperty(TRUSTSTORE_PATH); truststore_password = props.getProperty(TRUSTSTORE_PSSWD); keystore_path = props.getProperty(KEYSTORE_PATH); keystore_password = props.getProperty(KEYSTORE_PSSWD); target_uri = props.getProperty(TARGET_URI); query_path = props.getProperty(QUERY_PATH); update_path = props.getProperty(UPDATE_PATH); String applicationId = props.getProperty(APPLICATION_ID); if (applicationId == null || applicationId.isEmpty()) { applicationId = "SDNC"; } application_id = applicationId; // connection timeout int tmpConnectionTimeout = 30000; int tmpReadTimeout = 30000; try { String tmpValue = null; tmpValue = props.getProperty(CONNECTION_TIMEOUT, "30000"); tmpConnectionTimeout = Integer.parseInt(tmpValue); tmpValue = props.getProperty(READ_TIMEOUT, "30000"); tmpReadTimeout = Integer.parseInt(tmpValue); } catch (Exception exc) { LOG.error("Failed setting connection timeout", exc); tmpConnectionTimeout = 30000; tmpReadTimeout = 30000; } connection_timeout = tmpConnectionTimeout; read_timeout = tmpReadTimeout; network_vserver_path = props.getProperty(NETWORK_VSERVER_PATH); svc_instance_path = props.getProperty(SVC_INSTANCE_PATH); // "/aai/v1/business/customers/customer/{customer-id}/service-subscriptions/service-subscription/{service-type}/service-instances"); // "/aai/v1/business/customers/customer/ma9181-203-customerid/service-subscriptions/service-subscription/ma9181%20Hosted%20Voice/service-instances"; // svc_inst_qry_path = props.getProperty(SVC_INST_QRY_PATH, "/aai/v1/search/generic-query?key=service-instance.service-instance-id:ma9181-204-instance&start-node-type=service-instance&include=service-instance"); svc_inst_qry_path = props.getProperty(SVC_INST_QRY_PATH); // "/aai/v1/search/generic-query?key=service-instance.service-instance-id:{svc-instance-id}&start-node-type=service-instance&include=service-instance"); param_service_type = props.getProperty(PARAM_SERVICE_TYPE, "service-type"); // P-Interfaces p_interface_path = props.getProperty(P_INTERFACE_PATH); vnf_image_query_path = props.getProperty(VNF_IMAGE_QUERY_PATH); ubb_notify_path = props.getProperty(UBB_NOTIFY_PATH); selflink_avpn = props.getProperty(SELFLINK_AVPN); selflink_fqdn = props.getProperty(SELFLINK_FQDN); service_path = props.getProperty(SERVICE_PATH); site_pair_set_path = props.getProperty(SITE_PAIR_SET_PATH); query_nodes_path = props.getProperty(QUERY_NODES_PATH); String iche = props.getProperty(CERTIFICATE_HOST_ERROR); boolean host_error = false; if (iche != null && !iche.isEmpty()) { host_error = Boolean.valueOf(iche); } ignore_certificate_host_error = host_error; HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { public boolean verify(String string, SSLSession ssls) { return ignore_certificate_host_error; } }); if (truststore_path != null && truststore_password != null && (new File(truststore_path)).exists()) { System.setProperty("javax.net.ssl.trustStore", truststore_path); System.setProperty("javax.net.ssl.trustStorePassword", truststore_password); } if (keystore_path != null && keystore_password != null && (new File(keystore_path)).exists()) { DefaultClientConfig config = new DefaultClientConfig(); //both jersey and HttpURLConnection can use this SSLContext ctx = null; try { ctx = SSLContext.getInstance("TLS"); KeyManagerFactory kmf = null; try { String def = "SunX509"; String storeType = "PKCS12"; def = KeyStore.getDefaultType(); kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); FileInputStream fin = new FileInputStream(keystore_path); // KeyStore ks = KeyStore.getInstance("PKCS12"); String extension = keystore_path.substring(keystore_path.lastIndexOf(".") + 1); if (extension != null && !extension.isEmpty() && extension.equalsIgnoreCase("JKS")) { storeType = "JKS"; } KeyStore ks = KeyStore.getInstance(storeType); char[] pwd = keystore_password.toCharArray(); ks.load(fin, pwd); kmf.init(ks, pwd); } catch (Exception ex) { LOG.error("AAIResource", ex); } ctx.init(kmf.getKeyManagers(), null, null); config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return ignore_certificate_host_error; } }, ctx)); CTX = ctx; LOG.debug("SSLContext created"); } catch (KeyManagementException | NoSuchAlgorithmException exc) { LOG.error("AAIResource", exc); } } LOG.info("AAIResource.ctor initialized."); try { Field methodsField = HttpURLConnection.class.getDeclaredField("methods"); methodsField.setAccessible(true); // get the methods field modifiers Field modifiersField = Field.class.getDeclaredField("modifiers"); // bypass the "private" modifier modifiersField.setAccessible(true); // remove the "final" modifier modifiersField.setInt(methodsField, methodsField.getModifiers() & ~Modifier.FINAL); /* valid HTTP methods */ String[] methods = { "GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE", "PATCH" }; // set the new methods - including patch methodsField.set(null, methods); } catch (SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException e) { e.printStackTrace(); } }
From source file:io.apiman.gateway.platforms.servlet.connectors.ssl.SSLSessionStrategyFactory.java
private static SSLContextBuilder loadTrustMaterial(SSLContextBuilder builder, final File file, final char[] tsp, final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException { Args.notNull(file, "Truststore file"); //$NON-NLS-1$ final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); final FileInputStream instream = new FileInputStream(file); try {// w ww. j a v a2 s .co m trustStore.load(instream, tsp); } finally { instream.close(); } return builder.loadTrustMaterial(trustStore, trustStrategy); }
From source file:org.geoserver.wps.remote.plugin.XMPPClient.java
@Override public void init() throws Exception { // Initializes the XMPP Client and starts the communication. It also // register GeoServer as "manager" to the service channels on the MUC // (Multi/* www .j a v a 2s . c om*/ // User Channel) Rooms LOGGER.info(String.format("Initializing connection to server %1$s port %2$d", server, port)); int packetReplyTimeout = DEFAULT_PACKET_REPLY_TIMEOUT; if (getConfiguration().get("xmpp_packet_reply_timeout") != null) { packetReplyTimeout = Integer.parseInt(getConfiguration().get("xmpp_packet_reply_timeout")); } SmackConfiguration.setDefaultPacketReplyTimeout(packetReplyTimeout); config = new ConnectionConfiguration(server, port); checkSecured(getConfiguration()); // Trust own CA and all self-signed certs SSLContext sslcontext = null; if (this.certificateFile != null && this.certificatePassword != null) { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(this.certificateFile); try { trustStore.load(instream, this.certificatePassword.toCharArray()); } finally { instream.close(); } sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build(); } if (sslcontext != null) { // config.setSASLAuthenticationEnabled(false); config.setSecurityMode(SecurityMode.enabled); config.setCustomSSLContext(sslcontext); } else { config.setSecurityMode(SecurityMode.disabled); } // Actually performs the connection to the XMPP Server for (int testConn = 0; testConn < 5; testConn++) { try { // Try first the TCP Endpoint connection = new XMPPTCPConnection(config); connection.connect(); break; } catch (NoResponseException e) { connection = null; if (testConn >= 5) { LOGGER.warning( "No XMPP TCP Endpoint available or could not get any response from the Server. Falling back to BOSH Endpoint."); } else { LOGGER.log(Level.WARNING, "Tentative #" + (testConn + 1) + " - Error while trying to connect to XMPP TCP Endpoint.", e); Thread.sleep(500); } } } if (connection == null || !connection.isConnected()) { for (int testConn = 0; testConn < 5; testConn++) { try { // Falling back to BOSH Endpoint BOSHConfiguration boshConfig = new BOSHConfiguration((sslcontext != null), server, port, null, getConfiguration().get("xmpp_domain")); if (sslcontext != null) { // boshConfig.setSASLAuthenticationEnabled(false); boshConfig.setSecurityMode(SecurityMode.enabled); boshConfig.setCustomSSLContext(sslcontext); } else { boshConfig.setSecurityMode(SecurityMode.disabled); } connection = new XMPPBOSHConnection(boshConfig); connection.connect(); break; } catch (NoResponseException e) { connection = null; if (testConn >= 5) { LOGGER.warning( "No XMPP BOSH Endpoint available or could not get any response from the Server. The XMPP Client won't be available."); } else { LOGGER.log(Level.WARNING, "Tentative #" + (testConn + 1) + " - Error while trying to connect to XMPP BOSH Endpoint.", e); Thread.sleep(500); } } } } LOGGER.info("Connected: " + connection.isConnected()); // Check if the connection to the XMPP server is successful; the login // and registration is not yet performed at this time if (connection.isConnected()) { chatManager = ChatManager.getInstanceFor(connection); discoStu = ServiceDiscoveryManager.getInstanceFor(connection); // Add features to our XMPP client discoProperties(); // Performs login with "admin" user credentials performLogin(getConfiguration().get("xmpp_manager_username"), getConfiguration().get("xmpp_manager_password")); // Start "ping" task in order to maintain alive the connection startPingTask(); // Send invitation to the registered endpoints sendInvitations(); // getEndpointsLoadAverages(); // checkPendingRequests(); } else { setEnabled(false); LOGGER.warning("Not connected! The XMPP client has been disabled."); } }
From source file:com.zzl.zl_app.cache.Utility.java
public static HttpClient getNewHttpClient(Context context) { try {/*from ww w . j a va 2 s.co 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); // Set the default socket timeout (SO_TIMEOUT) // in // milliseconds which is the timeout for waiting for data. HttpConnectionParams.setConnectionTimeout(params, Utility.SET_CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(params, Utility.SET_SOCKET_TIMEOUT); HttpClient client = new DefaultHttpClient(ccm, params); WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo info = wifiManager.getConnectionInfo(); if (!wifiManager.isWifiEnabled() || -1 == info.getNetworkId()) { // ??APN? Uri uri = Uri.parse("content://telephony/carriers/preferapn"); Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null); if (mCursor != null && mCursor.moveToFirst()) { // ??? String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy")); if (proxyStr != null && proxyStr.trim().length() > 0) { HttpHost proxy = new HttpHost(proxyStr, 80); client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy); } mCursor.close(); } } return client; } catch (Exception e) { return new DefaultHttpClient(); } }
From source file:com.liferay.sync.engine.lan.session.LanSession.java
private static SSLConnectionSocketFactory _getSSLSocketFactory() throws Exception { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null);/*from w w w .j a v a2 s . c o m*/ for (SyncAccount syncAccount : SyncAccountService.findAll()) { if (!syncAccount.isActive() || !syncAccount.isLanEnabled()) { continue; } try { PrivateKey privateKey = LanPEMParserUtil.parsePrivateKey(syncAccount.getLanKey()); if (privateKey == null) { _logger.error("SyncAccount {} missing valid private key", syncAccount.getSyncAccountId()); continue; } X509Certificate x509Certificate = LanPEMParserUtil .parseX509Certificate(syncAccount.getLanCertificate()); if (x509Certificate == null) { _logger.error("SyncAccount {} missing valid certificate", syncAccount.getSyncAccountId()); continue; } keyStore.setCertificateEntry(syncAccount.getLanServerUuid(), x509Certificate); keyStore.setKeyEntry(syncAccount.getLanServerUuid(), privateKey, "".toCharArray(), new Certificate[] { x509Certificate }); } catch (Exception e) { _logger.error(e.getMessage(), e); } } KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, "".toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); return new SNISSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier()); }
From source file:net.java.sip.communicator.impl.certificate.CertificateServiceImpl.java
public SSLContext getSSLContext(X509TrustManager trustManager) throws GeneralSecurityException { try {/*from w w w .ja v a 2s . com*/ KeyStore ks = KeyStore .getInstance(System.getProperty("javax.net.ssl.keyStoreType", KeyStore.getDefaultType())); KeyManagerFactory kmFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); String keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword"); if (System.getProperty("javax.net.ssl.keyStore") != null) { ks.load(new FileInputStream(System.getProperty("javax.net.ssl.keyStore")), null); } else { ks.load(null, null); } kmFactory.init(ks, keyStorePassword == null ? null : keyStorePassword.toCharArray()); return getSSLContext(kmFactory.getKeyManagers(), trustManager); } catch (Exception e) { throw new GeneralSecurityException("Cannot init SSLContext", e); } }
From source file:com.gs.tools.doc.extractor.core.util.HttpUtility.java
public static DefaultHttpClient getLoginHttpsClient(String userName, String password) { try {/*from w ww. j a va 2s . c o m*/ KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new DefaultSecureSocketFactory(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, 300000); HttpConnectionParams.setSocketBufferSize(params, 10485760); HttpConnectionParams.setSoTimeout(params, 300000); 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); DefaultHttpClient httpClient = new DefaultHttpClient(ccm, params); httpClient.getCredentialsProvider().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM), new UsernamePasswordCredentials(userName, password)); return httpClient; } catch (Exception e) { e.printStackTrace(); return new DefaultHttpClient(); } }