List of usage examples for javax.net.ssl TrustManagerFactory getInstance
public static final TrustManagerFactory getInstance(String algorithm) throws NoSuchAlgorithmException
TrustManagerFactory
object that acts as a factory for trust managers. From source file:com.dbay.apns4j.tools.ApnsTools.java
public final static SocketFactory createSocketFactory(InputStream keyStore, String password, String keystoreType, String algorithm, String protocol) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException, KeyManagementException, CertificateExpiredException { char[] pwdChars = password.toCharArray(); KeyStore ks = KeyStore.getInstance(keystoreType); ks.load(keyStore, pwdChars);//from w w w . j av a 2 s.c om // ?? Enumeration<String> enums = ks.aliases(); String alias = ""; if (enums.hasMoreElements()) { alias = enums.nextElement(); } if (StringUtils.isNotEmpty(alias)) { X509Certificate certificate = (X509Certificate) ks.getCertificate(alias); if (null != certificate) { String type = certificate.getType(); int ver = certificate.getVersion(); String name = certificate.getSubjectDN().getName(); String serialNumber = certificate.getSerialNumber().toString(16); String issuerDN = certificate.getIssuerDN().getName(); String sigAlgName = certificate.getSigAlgName(); String publicAlgorithm = certificate.getPublicKey().getAlgorithm(); Date before = certificate.getNotBefore(); Date after = certificate.getNotAfter(); String beforeStr = DateFormatUtils.format(before, "yyyy-MM-dd HH:mm:ss"); String afterStr = DateFormatUtils.format(after, "yyyy-MM-dd HH:mm:ss"); // ?? long expire = DateUtil.getNumberOfDaysBetween(new Date(), after); if (expire <= 0) { if (LOG.isErrorEnabled()) { LOG.error( "?[{}], [{}], ?[{}], ??[{}], ?[{}], ??[{}], [{}], [{}][{}], ?[{}]", name, type, ver, serialNumber, issuerDN, sigAlgName, publicAlgorithm, beforeStr, afterStr, Math.abs(expire)); } throw new CertificateExpiredException("??[" + Math.abs(expire) + "]"); } if (LOG.isInfoEnabled()) { LOG.info( "?[{}], [{}], ?[{}], ??[{}], ?[{}], ??[{}], [{}], [{}][{}], ?[{}]?", name, type, ver, serialNumber, issuerDN, sigAlgName, publicAlgorithm, beforeStr, afterStr, expire); } } } KeyManagerFactory kf = KeyManagerFactory.getInstance(algorithm); kf.init(ks, pwdChars); TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm); tmf.init((KeyStore) null); SSLContext context = SSLContext.getInstance(protocol); context.init(kf.getKeyManagers(), tmf.getTrustManagers(), null); return context.getSocketFactory(); }
From source file:com.thejoshwa.ultrasonic.androidapp.service.ssl.SSLSocketFactory.java
private static SSLContext createSSLContext(String algorithm, final KeyStore keystore, final String keystorePassword, final KeyStore truststore, final SecureRandom random, final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException { if (algorithm == null) { algorithm = TLS;/*from ww w .j av a2 s.c o m*/ } KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keystore, keystorePassword != null ? keystorePassword.toCharArray() : null); KeyManager[] keymanagers = kmfactory.getKeyManagers(); TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmfactory.init(keystore); TrustManager[] trustmanagers = tmfactory.getTrustManagers(); if (trustmanagers != null && trustStrategy != null) { for (int i = 0; i < trustmanagers.length; i++) { TrustManager tm = trustmanagers[i]; if (tm instanceof X509TrustManager) { trustmanagers[i] = new TrustManagerDecorator((X509TrustManager) tm, trustStrategy); } } } SSLContext sslcontext = SSLContext.getInstance(algorithm); sslcontext.init(keymanagers, trustmanagers, random); return sslcontext; }
From source file:org.opendaylight.aaa.cert.impl.CertificateManagerService.java
@Override public SSLContext getServerContext() { String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm"); if (algorithm == null) { algorithm = "SunX509"; }//from ww w.j a v a2 s.co m SSLContext serverContext = null; try { KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm); kmf.init(aaaCertProvider.getODLKeyStore(), aaaCertProvider.getOdlKeyStoreInfo().getStorePassword().toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm); tmf.init(aaaCertProvider.getTrustKeyStore()); serverContext = SSLContext.getInstance(KeyStoreConstant.TLS_PROTOCOL); serverContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); } catch (final NoSuchAlgorithmException | UnrecoverableKeyException | KeyStoreException | KeyManagementException e) { LOG.error("Error while creating SSLContext ", e); } return serverContext; }
From source file:org.apache.synapse.transport.nhttp.config.ServerConnFactoryBuilder.java
protected SSLContextDetails createSSLContext(final OMElement keyStoreEl, final OMElement trustStoreEl, final OMElement cientAuthEl, final OMElement httpsProtocolsEl, final RevocationVerificationManager verificationManager, final String sslProtocol) throws AxisFault { KeyManager[] keymanagers = null; TrustManager[] trustManagers = null; if (keyStoreEl != null) { String location = getValueOfElementWithLocalName(keyStoreEl, "Location"); String type = getValueOfElementWithLocalName(keyStoreEl, "Type"); String storePassword = getValueOfElementWithLocalName(keyStoreEl, "Password"); String keyPassword = getValueOfElementWithLocalName(keyStoreEl, "KeyPassword"); FileInputStream fis = null; try {//from w w w . jav a 2s . c o m KeyStore keyStore = KeyStore.getInstance(type); fis = new FileInputStream(location); if (log.isInfoEnabled()) { log.debug(name + " Loading Identity Keystore from : " + location); } keyStore.load(fis, storePassword.toCharArray()); KeyManagerFactory kmfactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keyStore, keyPassword.toCharArray()); keymanagers = kmfactory.getKeyManagers(); if (log.isInfoEnabled() && keymanagers != null) { for (KeyManager keymanager : keymanagers) { if (keymanager instanceof X509KeyManager) { X509KeyManager x509keymanager = (X509KeyManager) keymanager; Enumeration<String> en = keyStore.aliases(); while (en.hasMoreElements()) { String s = en.nextElement(); X509Certificate[] certs = x509keymanager.getCertificateChain(s); if (certs == null) continue; for (X509Certificate cert : certs) { log.debug(name + " Subject DN: " + cert.getSubjectDN()); log.debug(name + " Issuer DN: " + cert.getIssuerDN()); } } } } } } catch (GeneralSecurityException gse) { log.error(name + " Error loading Key store : " + location, gse); throw new AxisFault("Error loading Key store : " + location, gse); } catch (IOException ioe) { log.error(name + " Error opening Key store : " + location, ioe); throw new AxisFault("Error opening Key store : " + location, ioe); } finally { if (fis != null) { try { fis.close(); } catch (IOException ignore) { } } } } if (trustStoreEl != null) { String location = getValueOfElementWithLocalName(trustStoreEl, "Location"); String type = getValueOfElementWithLocalName(trustStoreEl, "Type"); String storePassword = getValueOfElementWithLocalName(trustStoreEl, "Password"); FileInputStream fis = null; try { KeyStore trustStore = KeyStore.getInstance(type); fis = new FileInputStream(location); if (log.isInfoEnabled()) { log.debug(name + " Loading Trust Keystore from : " + location); } trustStore.load(fis, storePassword.toCharArray()); TrustManagerFactory trustManagerfactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerfactory.init(trustStore); trustManagers = trustManagerfactory.getTrustManagers(); } catch (GeneralSecurityException gse) { log.error(name + " Error loading Key store : " + location, gse); throw new AxisFault("Error loading Key store : " + location, gse); } catch (IOException ioe) { log.error(name + " Error opening Key store : " + location, ioe); throw new AxisFault("Error opening Key store : " + location, ioe); } finally { if (fis != null) { try { fis.close(); } catch (IOException ignore) { } } } } final String s = cientAuthEl != null ? cientAuthEl.getText() : null; final SSLClientAuth clientAuth; if ("optional".equalsIgnoreCase(s)) { clientAuth = SSLClientAuth.OPTIONAL; } else if ("require".equalsIgnoreCase(s)) { clientAuth = SSLClientAuth.REQUIRED; } else { clientAuth = null; } String[] httpsProtocols = null; final String configuredHttpsProtocols = httpsProtocolsEl != null ? httpsProtocolsEl.getText() : null; if (configuredHttpsProtocols != null && configuredHttpsProtocols.trim().length() != 0) { String[] configuredValues = configuredHttpsProtocols.trim().split(","); List<String> protocolList = new ArrayList<String>(configuredValues.length); for (String protocol : configuredValues) { if (!protocol.trim().isEmpty()) { protocolList.add(protocol.trim()); } } httpsProtocols = protocolList.toArray(new String[protocolList.size()]); } try { final String sslProtocolValue = sslProtocol != null ? sslProtocol : "TLS"; SSLContext sslContext = SSLContext.getInstance(sslProtocolValue); sslContext.init(keymanagers, trustManagers, null); ServerSSLSetupHandler sslSetupHandler = (clientAuth != null || httpsProtocols != null) ? new ServerSSLSetupHandler(clientAuth, httpsProtocols, verificationManager) : null; return new SSLContextDetails(sslContext, sslSetupHandler); } catch (GeneralSecurityException gse) { log.error(name + " Unable to create SSL context with the given configuration", gse); throw new AxisFault("Unable to create SSL context with the given configuration", gse); } }
From source file:org.apache.felix.karaf.jaas.config.impl.ResourceKeystoreInstance.java
public TrustManager[] getTrustManager(String algorithm) throws KeyStoreException, NoSuchAlgorithmException, KeystoreIsLocked { if (isKeystoreLocked()) { throw new KeystoreIsLocked("Keystore '" + name + "' is locked."); }/* w w w. j av a2s .c o m*/ if (!loadKeystoreData()) { return null; } TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(algorithm); trustFactory.init(keystore); return trustFactory.getTrustManagers(); }
From source file:eu.eubrazilcc.lvl.core.http.client.TrustedHttpsClient.java
private static final void importCertificate(final String url, final KeyStore trustStore) throws Exception { final URL url2 = new URL(url); final SSLContext sslContext = SSLContext.getInstance("TLS"); final TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); final X509TrustManager defaultTrustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0]; final SavingTrustManager trustManager = new SavingTrustManager(defaultTrustManager); sslContext.init(null, new TrustManager[] { trustManager }, null); final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); final SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(url2.getHost(), url2.getPort() > 0 ? url2.getPort() : 443); socket.setSoTimeout(10000);/* ww w.j a v a 2s. co m*/ try { socket.startHandshake(); socket.close(); } catch (SSLException e) { } final X509Certificate[] chain = trustManager.chain; if (chain == null) { LOGGER.error("Could not obtain server certificate chain from: " + url); return; } final MessageDigest sha1 = MessageDigest.getInstance("SHA1"); final MessageDigest md5 = MessageDigest.getInstance("MD5"); for (int i = 0; i < chain.length; i++) { final X509Certificate cert = chain[i]; final String alias = url2.getHost() + "-" + (i + 1); if (!trustStore.containsAlias(alias)) { sha1.update(cert.getEncoded()); md5.update(cert.getEncoded()); LOGGER.trace("Importing certificate to trusted keystore >> " + "Subject: " + cert.getSubjectDN() + ", Issuer: " + cert.getIssuerDN() + ", SHA1: " + printHexBinary(sha1.digest()) + ", MD5: " + printHexBinary(md5.digest()) + ", Alias: " + alias); trustStore.setCertificateEntry(alias, cert); } } }
From source file:com.clustercontrol.plugin.impl.WebServicePlugin.java
/** * ???WebService?Agent????????//from www . j a va 2 s . c o m * @param addressPrefix ? http://x.x.x.x:xxxx? ? * @param addressBody ??? addressPrefix ?? * @param endpointInstance * @param threadPool ? */ protected void publish(String addressPrefix, String addressBody, Object endpointInstance, ThreadPoolExecutor threadPool) { try { final URL urlPrefix = new URL(addressPrefix); final String fulladdress = addressPrefix + addressBody; HttpsServer httpsServer = null; // ? HTTPS???????HttpsService???endpoit.publish????? // URL??????????HttpsService?????Hashmap???????HashMap? // HTTPSServer??????????? if ("https".equals(urlPrefix.getProtocol())) { httpsServer = httpsServerMap.get(addressPrefix); if (httpsServer == null) { // HTTPS Server??HTTPS????????????????????? String protocol = HinemosPropertyUtil.getHinemosPropertyStr("ws.https.protocol", "TLS"); String keystorePath = HinemosPropertyUtil.getHinemosPropertyStr("ws.https.keystore.path", HinemosPropertyDefault .getString(HinemosPropertyDefault.StringKey.WS_HTTPS_KEYSTORE_PATH)); String keystorePassword = HinemosPropertyUtil .getHinemosPropertyStr("ws.https.keystore.password", "hinemos"); String keystoreType = HinemosPropertyUtil.getHinemosPropertyStr("ws.https.keystore.type", "PKCS12"); log.info("Starting HTTPS Server..."); log.info("SSLContext: " + protocol + ", KeyStore: " + keystoreType); SSLContext ssl = SSLContext.getInstance(protocol); KeyManagerFactory keyFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); KeyStore store = KeyStore.getInstance(keystoreType); try (InputStream in = new FileInputStream(keystorePath)) { store.load(in, keystorePassword.toCharArray()); } keyFactory.init(store, keystorePassword.toCharArray()); TrustManagerFactory trustFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustFactory.init(store); ssl.init(keyFactory.getKeyManagers(), trustFactory.getTrustManagers(), new SecureRandom()); HttpsConfigurator configurator = new HttpsConfigurator(ssl); // ??HTTPSSever???Hashmap?? httpsServer = HttpsServer .create(new InetSocketAddress(urlPrefix.getHost(), urlPrefix.getPort()), 0); httpsServer.setHttpsConfigurator(configurator); httpsServerMap.put(addressPrefix, httpsServer); } } // ?????endpoint?? log.info("publish " + fulladdress); final Endpoint endpoint = Endpoint.create(endpointInstance); endpoint.setExecutor(threadPool); if (httpsServer != null) { endpoint.publish(httpsServer.createContext(addressBody)); } else { endpoint.publish(fulladdress); } endpointList.add(endpoint); } catch (NoSuchAlgorithmException | UnrecoverableKeyException | KeyStoreException | KeyManagementException | IOException | CertificateException | RuntimeException e) { log.warn("failed to publish : " + e.getClass().getSimpleName() + ", " + e.getMessage(), e); } finally { } }
From source file:org.elasticsearch.xpack.security.transport.ssl.SslIntegrationTests.java
public void testThatHttpUsingSSLv3IsRejected() throws Exception { SSLContext sslContext = SSLContext.getInstance("SSL"); TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); factory.init((KeyStore) null); sslContext.init(null, factory.getTrustManagers(), new SecureRandom()); SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, new String[] { "SSLv3" }, null, NoopHostnameVerifier.INSTANCE); try (CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sf).build()) { CloseableHttpResponse result = SocketAccess .doPrivileged(() -> client.execute(new HttpGet(getNodeUrl()))); fail("Expected a connection error due to SSLv3 not being supported by default"); } catch (Exception e) { assertThat(e, is(instanceOf(SSLHandshakeException.class))); }/*from w ww.ja v a 2 s. c om*/ }
From source file:com.adito.server.jetty.CustomJsseListener.java
protected SSLServerSocketFactory createFactory() throws Exception { if (KeyStoreManager.getInstance(KeyStoreManager.DEFAULT_KEY_STORE).isKeyStoreEmpty()) { throw new Exception( "The keystore does not contain any certificates. Please run the installation wizard (--install)."); }/*from ww w . j a v a 2s. co m*/ KeyStore ks = KeyStoreManager.getInstance(KeyStoreManager.DEFAULT_KEY_STORE).getKeyStore(); String pw = ContextHolder.getContext().getConfig() .retrieveProperty(new ContextKey("webServer.keystore.sslCertificate.password")); KeyManager[] kma = new KeyManager[] { new CustomKeyManager(pw) }; TrustManager[] tma = null; if (trustManager == null) { TrustManagerFactory tm = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tm.init(ks); tma = tm.getTrustManagers(); } else { // LDP - Add the existing trust managers so that outgoing certificates are still trusted. TrustManagerFactory tm = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tm.init(ks); tma = new TrustManager[tm.getTrustManagers().length + 1]; for (int i = 0; i < tm.getTrustManagers().length; i++) { tma[i] = tm.getTrustManagers()[i]; } tma[tma.length - 1] = trustManager; } SSLContext sslc = SSLContext.getInstance("SSL"); sslc.init(kma, tma, SecureRandom.getInstance("SHA1PRNG")); SSLServerSocketFactory ssfc = sslc.getServerSocketFactory(); if (log.isInfoEnabled()) log.info("SSLServerSocketFactory=" + ssfc); initialised = true; return ssfc; }
From source file:com.sslexplorer.server.jetty.CustomJsseListener.java
protected SSLServerSocketFactory createFactory() throws Exception { if (KeyStoreManager.getInstance(KeyStoreManager.DEFAULT_KEY_STORE).isKeyStoreEmpty()) { throw new Exception( "The keystore does not contain any certificates. Please run the installation wizard (--install)."); }//from w ww . ja v a 2s .c om KeyStore ks = KeyStoreManager.getInstance(KeyStoreManager.DEFAULT_KEY_STORE).getKeyStore(); String pw = ContextHolder.getContext().getConfig() .retrieveProperty(new ContextKey("webServer.keystore.sslCertificate.password")); KeyManager[] kma = new KeyManager[] { new CustomKeyManager(pw) }; TrustManager[] tma = null; if (trustManager == null) { TrustManagerFactory tm = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tm.init(ks); tma = tm.getTrustManagers(); } else { // LDP - Add the existing trust managers so that outgoing certificates are still trusted. TrustManagerFactory tm = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tm.init(ks); tma = new TrustManager[tm.getTrustManagers().length + 1]; for (int i = 0; i < tm.getTrustManagers().length - 1; i++) { tma[i] = tm.getTrustManagers()[i]; } tma[tma.length - 1] = trustManager; } SSLContext sslc = SSLContext.getInstance("SSL"); sslc.init(kma, tma, SecureRandom.getInstance("SHA1PRNG")); SSLServerSocketFactory ssfc = sslc.getServerSocketFactory(); if (log.isInfoEnabled()) log.info("SSLServerSocketFactory=" + ssfc); initialised = true; return ssfc; }