List of usage examples for javax.net.ssl KeyManagerFactory getKeyManagers
public final KeyManager[] getKeyManagers()
From source file:com.predic8.membrane.core.transport.ssl.SSLContext.java
public SSLContext(SSLParser sslParser, ResolverMap resourceResolver, String baseLocation) { this.sslParser = sslParser; try {//from ww w.ja v a 2s . c o m String algorihm = KeyManagerFactory.getDefaultAlgorithm(); if (sslParser.getAlgorithm() != null) algorihm = sslParser.getAlgorithm(); KeyManagerFactory kmf = null; String keyStoreType = "JKS"; if (sslParser.getKeyStore() != null) { if (sslParser.getKeyStore().getKeyAlias() != null) throw new InvalidParameterException("keyAlias is not yet supported."); char[] keyPass = "changeit".toCharArray(); if (sslParser.getKeyStore().getKeyPassword() != null) keyPass = sslParser.getKeyStore().getKeyPassword().toCharArray(); if (sslParser.getKeyStore().getType() != null) keyStoreType = sslParser.getKeyStore().getType(); KeyStore ks = openKeyStore(sslParser.getKeyStore(), "JKS", keyPass, resourceResolver, baseLocation); kmf = KeyManagerFactory.getInstance(algorihm); kmf.init(ks, keyPass); Enumeration<String> aliases = ks.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (ks.isKeyEntry(alias)) { // first key is used by the KeyManagerFactory Certificate c = ks.getCertificate(alias); if (c instanceof X509Certificate) { X509Certificate x = (X509Certificate) c; dnsNames = new ArrayList<String>(); Collection<List<?>> subjectAlternativeNames = x.getSubjectAlternativeNames(); if (subjectAlternativeNames != null) for (List<?> l : subjectAlternativeNames) { if (l.get(0) instanceof Integer && ((Integer) l.get(0) == 2)) dnsNames.add(l.get(1).toString()); } } break; } } } TrustManagerFactory tmf = null; if (sslParser.getTrustStore() != null) { String trustAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); if (sslParser.getTrustStore().getAlgorithm() != null) trustAlgorithm = sslParser.getTrustStore().getAlgorithm(); KeyStore ks = openKeyStore(sslParser.getTrustStore(), keyStoreType, null, resourceResolver, baseLocation); tmf = TrustManagerFactory.getInstance(trustAlgorithm); tmf.init(ks); } TrustManager[] tms = tmf != null ? tmf.getTrustManagers() : null /* trust anyone: new TrustManager[] { new NullTrustManager() } */; if (sslParser.isIgnoreTimestampCheckFailure()) tms = new TrustManager[] { new TrustManagerWrapper(tms, true) }; if (sslParser.getProtocol() != null) sslc = javax.net.ssl.SSLContext.getInstance(sslParser.getProtocol()); else sslc = javax.net.ssl.SSLContext.getInstance("TLS"); sslc.init(kmf != null ? kmf.getKeyManagers() : null, tms, null); if (sslParser.getCiphers() != null) { ciphers = sslParser.getCiphers().split(","); Set<String> supportedCiphers = Sets.newHashSet(sslc.getSocketFactory().getSupportedCipherSuites()); for (String cipher : ciphers) { if (!supportedCiphers.contains(cipher)) throw new InvalidParameterException("Unknown cipher " + cipher); if (cipher.contains("_RC4_")) log.warn("Cipher " + cipher + " uses RC4, which is deprecated."); } } else { // use all default ciphers except those using RC4 String supportedCiphers[] = sslc.getSocketFactory().getDefaultCipherSuites(); ArrayList<String> ciphers = new ArrayList<String>(supportedCiphers.length); for (String cipher : supportedCiphers) if (!cipher.contains("_RC4_")) ciphers.add(cipher); sortCiphers(ciphers); this.ciphers = ciphers.toArray(new String[ciphers.size()]); } if (setUseCipherSuitesOrderMethod == null) log.warn( "Cannot set the cipher suite order before Java 8. This prevents Forward Secrecy with some SSL clients."); if (sslParser.getProtocols() != null) { protocols = sslParser.getProtocols().split(","); } else { protocols = null; } if (sslParser.getClientAuth() == null) { needClientAuth = false; wantClientAuth = false; } else if (sslParser.getClientAuth().equals("need")) { needClientAuth = true; wantClientAuth = true; } else if (sslParser.getClientAuth().equals("want")) { needClientAuth = false; wantClientAuth = true; } else { throw new RuntimeException("Invalid value '" + sslParser.getClientAuth() + "' in clientAuth: expected 'want', 'need' or not set."); } } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.beepcore.beep.profile.tls.jsse.TLSProfileJSSE.java
/** * init sets the criteria for which an SSL connection is made when * a TLS channel is started for a profile. It should only be * called once. For the properties, the initiator is defined as * the peer who starts the channel for the TLS profile, the * listener is the peer that receives the the channel start * request, irregardless of which actually started the session.<p> * * @param config <code>ProfileConfiguration</code> object that * contains key value pairs to initialize the TLS layer. None of * these are mandatory, but if you wish communication to be * anonymous with no authentication, (i.e., the listener to not * send back a certificate), you must set "Listener Anonymous" to * "true" and "Initiator Authentication Required" to "false". * The meaningful properties that can be set are these:<p> * <table>//from w w w .j a v a 2s.com * <tr> * <td>Listener Anonymous</td><td>(true|false) must be set to false if the * listener will not authenticate itself</td> * </tr><tr> * <td>Initiator Authentication Required</td><td>(true|false) set if the * initiator should send a certificate and the listener expects a * certificate.</td> * </tr><tr> * <td>Cipher Suite</td><td><i>not yet implemented.</i>the algorithms that * can be used for encryption, authentication, and key exchange.</td> * </tr><tr> * <td>Key Algorithm</td><td>key management algorithm. See * {@link com.sun.net.ssl.KeyManagerFactory#getInstance}</td> * </tr><tr> * <td>Key Provider</td><td>provider of the key management * algorithm. Defaults to * <code>com.sun.net.ssl.internal.ssl.Provider</code> See * {@link com.sun.net.ssl.KeyManagerFactory#getInstance}</td> * </tr><tr> * <td>Trust Algorithm</td><td>algorithm to be used by the trust * manager. See * {@link com.sun.net.ssl.TrustManagerFactory#getInstance}</td> * </tr><tr> * <td>Trust Provider</td><td>provider of the trust manager. Defaults to * <code>com.sun.net.ssl.internal.ssl.Provider</code>. See * {@link com.sun.net.ssl.TrustManagerFactory#getInstance}</td> * </tr><tr> * <td>Key Store Passphrase</td><td>pass phrase used to encrypt the key * store. See {@link java.security.KeyStore#load}</td> * </tr><tr> * <td>Key Store Data Type</td><td>data type of the key store passed in. * "file" is currently the only value accepted, meaning Key Store * is the name of a file containing keys. See * {@link java.security.KeyStore#load}</td> * </tr><tr> * <td>Key Store</td><td>value of the key store, dependent on the type in * Key Store Data Type. See {@link java.security.KeyStore#load}</td> * </tr><tr> * <td>Key Store Format</td><td>format of the keys within the key store. * Default is "JKS". See {@link java.security.KeyStore#getInstance}</td> * </tr><tr> * <td>Key Store Provider</td><td>provider for the key stores. See * {@link java.security.KeyStore#getInstance}</td> * </tr><tr> * <td>Trust Store Passphrase</td><td>pass phrase used to encrypt the trust * store. See {@link java.security.KeyStore#load}</td> * </tr><tr> * <td>Trust Store Data Type</td><td>data type of the certificates in the * trust store. "file" is currently th only value accepted, * meaning the trust store is a file on the local disk. See * {@link java.security.KeyStore#load}</td> * </tr><tr> * <td>Trust Store</td><td>value of the trust store, dependent on the type * in Trust * Store Data Type See {@link java.security.KeyStore#load}</td> * </tr><tr> * <td>Trust Store Format</td><td>format of the certificates within the * trust store. * Default is "JKS". See {@link java.security.KeyStore#getInstance}</td> * </tr><tr> * <td>Trust Store Provider</td><td>provider for the trust stores. See * {@link java.security.KeyStore#getInstance}</td> * </tr><tr> * <td>Allowed SSL Protocols</td><td>Comma separated list of algorithms * that may be used for SSL/TLS negotiations. By default, this will be * whatever the {@link SSLSocket} implementation supports. * @see SSLSocket#getSupportedProtocols() * @see SSLSocket#setEnabledProtocols(String[]) * </tr><tr> * </table> * @throws BEEPException For any error in the profile configuration, a * negative response in the form of a BEEP error will be sent back to the * requesting peer. The session will continue to be open and usable, at * least from the standpoint of this peer. * * @see com.sun.net.ssl.KeyManagerFactory * @see com.sun.net.ssl.TrustManagerFactory * @see java.security.KeyStore * @see com.sun.net.ssl.SSLContext */ public StartChannelListener init(String uri, ProfileConfiguration config) throws BEEPException { KeyManagerFactory kmf = null; KeyManager[] km = null; KeyStore ks = null; TrustManagerFactory tmf = null; TrustManager[] tm = null; KeyStore ts = null; SSLContext ctx; this.sslProtocols = null; // set the URI of this instance of the profile this.uri = uri; try { // create an SSL context object ctx = SSLContext.getInstance("TLS"); } catch (java.security.NoSuchAlgorithmException e) { throw new BEEPException("TLS Algorithm Not Found. Probable " + "cause is the JSSE provider has not " + "been added to the java.security file."); } try { String protocols = config.getProperty(PROPERTY_SSL_PROTOCOLS); if (protocols != null) { this.sslProtocols = protocols.split(","); } // initialize the key managers, trust managers, and keyAlgorithm = config.getProperty(PROPERTY_KEY_MANAGER_ALGORITHM); keyProvider = config.getProperty(PROPERTY_KEY_MANAGER_PROVIDER); trustAlgorithm = config.getProperty(PROPERTY_TRUST_MANAGER_ALGORITHM); trustProvider = config.getProperty(PROPERTY_TRUST_MANAGER_PROVIDER); keyPassphrase = config.getProperty(PROPERTY_KEYSTORE_PASSPHRASE); keyStoreType = config.getProperty(PROPERTY_KEYSTORE_TYPE); keyStoreName = config.getProperty(PROPERTY_KEYSTORE_NAME); keyStoreFormat = config.getProperty(PROPERTY_KEYSTORE_FORMAT, "JKS"); keyStoreProvider = config.getProperty(PROPERTY_KEYSTORE_PROVIDER); trustPassphrase = config.getProperty(PROPERTY_TRUSTSTORE_PASSPHRASE); trustStoreType = config.getProperty(PROPERTY_TRUSTSTORE_TYPE); trustStoreName = config.getProperty(PROPERTY_TRUSTSTORE_NAME); trustStoreFormat = config.getProperty(PROPERTY_TRUSTSTORE_FORMAT, "JKS"); trustStoreProvider = config.getProperty(PROPERTY_TRUSTSTORE_PROVIDER); // determine if the client must authenticate or if the server can // needClientAuth = new Boolean(config.getProperty(PROPERTY_CLIENT_AUTHENTICATION, "false")) .booleanValue(); serverAnonymous = new Boolean(config.getProperty(PROPERTY_SERVER_ANONYMOUS, "true")).booleanValue(); if (keyAlgorithm != null) { if (keyProvider != null) { kmf = KeyManagerFactory.getInstance(keyAlgorithm, keyProvider); } else { kmf = KeyManagerFactory.getInstance(keyAlgorithm); } // add support for a default type of key manager factory? if (keyStoreProvider != null) { ks = KeyStore.getInstance(keyStoreFormat, keyStoreProvider); } else { ks = KeyStore.getInstance(keyStoreFormat); } if (keyStoreType.equals("file")) { ks.load(new FileInputStream(keyStoreName), keyPassphrase.toCharArray()); } else { throw new BEEPException(ERR_ILLEGAL_KEY_STORE); } // initialize the key factory manager kmf.init(ks, keyPassphrase.toCharArray()); km = kmf.getKeyManagers(); } else { km = null; } if (trustAlgorithm != null) { if (trustProvider != null) { tmf = TrustManagerFactory.getInstance(trustAlgorithm, trustProvider); } else { tmf = TrustManagerFactory.getInstance(trustAlgorithm); } // add support for a default type of trust manager factory? if (trustStoreProvider != null) { ts = KeyStore.getInstance(trustStoreFormat, trustStoreProvider); } else { ts = KeyStore.getInstance(trustStoreFormat); } if (trustStoreType.equals("file")) { ts.load(new FileInputStream(trustStoreName), trustPassphrase.toCharArray()); } else { throw new BEEPException(ERR_ILLEGAL_TRUST_STORE); } // initialize the trust factory manager tmf.init(ts); tm = tmf.getTrustManagers(); } else { tm = null; } // create a socket factory from the key factories and // trust factories created for the algorithms and stores // specfied. No option is given to change the secure // random number generator ctx.init(km, tm, null); socketFactory = ctx.getSocketFactory(); return this; } catch (Exception e) { log.error(e); throw new BEEPException(e); } }
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;/*w ww.ja v a2 s . c o 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(); } }