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:mitm.common.security.ca.handlers.ejbca.ws.EjbcaWSClient.java
public static void main(String args[]) throws Exception { BasicConfigurator.configure();/*from w w w . ja v a 2 s . c o m*/ JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); factory.setServiceClass(EjbcaWS.class); factory.setAddress("https://192.168.178.113:8443/ejbca/ejbcaws/ejbcaws"); factory.setServiceName(SERVICE_NAME); EjbcaWS client = (EjbcaWS) factory.create(); Client proxy = ClientProxy.getClient(client); HTTPConduit conduit = (HTTPConduit) proxy.getConduit(); TLSClientParameters tlsClientParameters = new TLSClientParameters(); KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); java.security.KeyStore keyStore = java.security.KeyStore.getInstance("PKCS12"); InputStream keyInput = new FileInputStream("/home/martijn/temp/superadmin.p12"); String password = "ejbca"; keyStore.load(keyInput, password.toCharArray()); keyInput.close(); keyManagerFactory.init(keyStore, password.toCharArray()); KeyManager[] keyManagers = keyManagerFactory.getKeyManagers(); tlsClientParameters.setDisableCNCheck(true); tlsClientParameters.setKeyManagers(keyManagers); X509TrustManager trustAll = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }; TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(new KeyStoreLoader().loadKeyStore(new File("/home/martijn/temp/truststore.jks"), "changeit".toCharArray())); tlsClientParameters.setTrustManagers(new TrustManager[] { trustAll }); //tlsClientParameters.setTrustManagers(trustManagerFactory.getTrustManagers()); conduit.setTlsClientParameters(tlsClientParameters); System.out.println(client.getEjbcaVersion()); UserDataVOWS userData = new UserDataVOWS(); userData.setEmail("test@example.com"); userData.setUsername("test@example.com"); //userData.setPassword("test@example.com"); userData.setSubjectDN("CN=test@example.com"); userData.setSubjectAltName("rfc822Name=test@example.com"); userData.setEndEntityProfileName("test"); userData.setCaName("AdminCA1"); userData.setCertificateProfileName("ENDUSER"); userData.setStatus(EJBCAConst.STATUS_NEW); userData.setTokenType(EJBCAConst.TOKEN_TYPE_USERGENERATED); try { //client.editUser(userData); SecurityFactory securityFactory = SecurityFactoryFactory.getSecurityFactory(); SecureRandom randomSource = securityFactory.createSecureRandom(); KeyPairGenerator keyPairGenerator = securityFactory.createKeyPairGenerator("RSA"); keyPairGenerator.initialize(2048, randomSource); KeyPair keyPair = keyPairGenerator.generateKeyPair(); X500PrincipalBuilder builder = new X500PrincipalBuilder(); builder.setCommonName("john doe"); builder.setEmail("test@example.com"); PKCS10CertificationRequestBuilder requestBuilder = new PKCS10CertificationRequestBuilder( X500PrincipalUtils.toX500Name(builder.buildPrincipal()), SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded())); PKCS10CertificationRequest pkcs10 = requestBuilder .build(getContentSigner("SHA1WithRSA", keyPair.getPrivate())); String base64PKCS10 = Base64Utils.encode(pkcs10.getEncoded()); CertificateResponse certificateResponse = client.certificateRequest(userData, base64PKCS10, EJBCAConst.CERT_REQ_TYPE_PKCS10, null, EJBCAConst.RESPONSETYPE_CERTIFICATE); if (certificateResponse != null && certificateResponse.getData() != null) { /* * The result is a base64 encoded certificate */ Collection<X509Certificate> certificates = CertificateUtils.readX509Certificates( new ByteArrayInputStream(Base64.decode(certificateResponse.getData()))); if (CollectionUtils.isNotEmpty(certificates)) { for (X509Certificate certificate : certificates) { System.out.println(certificate); } } else { System.out.println("No certificates found"); } } else { System.out.println("certificateResponse is empty"); } } catch (Exception e) { e.printStackTrace(); } }
From source file:net.sf.jsignpdf.InstallCert.java
/** * The main - whole logic of Install Cert Tool. * // ww w . j av a2s . c o m * @param args * @throws Exception */ public static void main(String[] args) { String host; int port; char[] passphrase; System.out.println("InstallCert - Install CA certificate to Java Keystore"); System.out.println("====================================================="); final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { if ((args.length == 1) || (args.length == 2)) { String[] c = args[0].split(":"); host = c[0]; port = (c.length == 1) ? 443 : Integer.parseInt(c[1]); String p = (args.length == 1) ? "changeit" : args[1]; passphrase = p.toCharArray(); } else { String tmpStr; do { System.out.print("Enter hostname or IP address: "); tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null); } while (tmpStr == null); host = tmpStr; System.out.print("Enter port number [443]: "); tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null); port = tmpStr == null ? 443 : Integer.parseInt(tmpStr); System.out.print("Enter keystore password [changeit]: "); tmpStr = reader.readLine(); String p = "".equals(tmpStr) ? "changeit" : tmpStr; passphrase = p.toCharArray(); } char SEP = File.separatorChar; final File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security"); final File file = new File(dir, "cacerts"); System.out.println("Loading KeyStore " + file + "..."); InputStream in = new FileInputStream(file); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(in, passphrase); in.close(); SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; SavingTrustManager tm = new SavingTrustManager(defaultTrustManager); context.init(null, new TrustManager[] { tm }, null); SSLSocketFactory factory = context.getSocketFactory(); System.out.println("Opening connection to " + host + ":" + port + "..."); SSLSocket socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(10000); try { System.out.println("Starting SSL handshake..."); socket.startHandshake(); socket.close(); System.out.println(); System.out.println("No errors, certificate is already trusted"); } catch (SSLException e) { System.out.println(); System.out.println("Certificate is not yet trusted."); // e.printStackTrace(System.out); } X509Certificate[] chain = tm.chain; if (chain == null) { System.out.println("Could not obtain server certificate chain"); return; } System.out.println(); System.out.println("Server sent " + chain.length + " certificate(s):"); System.out.println(); MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest md5 = MessageDigest.getInstance("MD5"); for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN()); System.out.println(" Issuer " + cert.getIssuerDN()); sha1.update(cert.getEncoded()); System.out.println(" sha1 " + toHexString(sha1.digest())); md5.update(cert.getEncoded()); System.out.println(" md5 " + toHexString(md5.digest())); System.out.println(); } System.out.print("Enter certificate to add to trusted keystore or 'q' to quit [1]: "); String line = reader.readLine().trim(); int k = -1; try { k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1; } catch (NumberFormatException e) { } if (k < 0 || k >= chain.length) { System.out.println("KeyStore not changed"); } else { try { System.out.println("Creating keystore backup"); final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); final File backupFile = new File(dir, CACERTS_KEYSTORE + "." + dateFormat.format(new java.util.Date())); final FileInputStream fis = new FileInputStream(file); final FileOutputStream fos = new FileOutputStream(backupFile); IOUtils.copy(fis, fos); fis.close(); fos.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println("Installing certificate..."); X509Certificate cert = chain[k]; String alias = host + "-" + (k + 1); ks.setCertificateEntry(alias, cert); OutputStream out = new FileOutputStream(file); ks.store(out, passphrase); out.close(); System.out.println(); System.out.println(cert); System.out.println(); System.out.println("Added certificate to keystore '" + file + "' using alias '" + alias + "'"); } } catch (Exception e) { System.out.println(); System.out.println("----------------------------------------------"); System.out.println("Problem occured during installing certificate:"); e.printStackTrace(); System.out.println("----------------------------------------------"); } System.out.println("Press Enter to finish..."); try { reader.readLine(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.vmware.photon.controller.core.Main.java
public static void main(String[] args) throws Throwable { try {//from w ww . jav a2 s. c o m LoggingFactory.bootstrap(); logger.info("args: " + Arrays.toString(args)); ArgumentParser parser = ArgumentParsers.newArgumentParser("PhotonControllerCore").defaultHelp(true) .description("Photon Controller Core"); parser.addArgument("config-file").help("photon controller configuration file"); parser.addArgument("--manual").type(Boolean.class).setDefault(false) .help("If true, create default deployment."); Namespace namespace = parser.parseArgsOrFail(args); PhotonControllerConfig photonControllerConfig = getPhotonControllerConfig(namespace); DeployerConfig deployerConfig = photonControllerConfig.getDeployerConfig(); new LoggingFactory(photonControllerConfig.getLogging(), "photon-controller-core").configure(); SSLContext sslContext; if (deployerConfig.getDeployerContext().isAuthEnabled()) { sslContext = SSLContext.getInstance(KeyStoreUtils.THRIFT_PROTOCOL); TrustManagerFactory tmf = null; tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); KeyStore keyStore = KeyStore.getInstance("JKS"); InputStream in = FileUtils .openInputStream(new File(deployerConfig.getDeployerContext().getKeyStorePath())); keyStore.load(in, deployerConfig.getDeployerContext().getKeyStorePassword().toCharArray()); tmf.init(keyStore); sslContext.init(null, tmf.getTrustManagers(), null); } else { KeyStoreUtils.generateKeys("/thrift/"); sslContext = KeyStoreUtils.acceptAllCerts(KeyStoreUtils.THRIFT_PROTOCOL); } ThriftModule thriftModule = new ThriftModule(sslContext); PhotonControllerXenonHost xenonHost = startXenonHost(photonControllerConfig, thriftModule, deployerConfig, sslContext); if ((Boolean) namespace.get("manual")) { DefaultDeployment.createDefaultDeployment(photonControllerConfig.getXenonConfig().getPeerNodes(), deployerConfig, xenonHost); } // Creating a temp configuration file for apife with modification to some named sections in photon-controller-config // so that it can match the Configuration class of dropwizard. File apiFeTempConfig = File.createTempFile("apiFeTempConfig", ".tmp"); File source = new File(args[0]); FileInputStream fis = new FileInputStream(source); BufferedReader in = new BufferedReader(new InputStreamReader(fis)); FileWriter fstream = new FileWriter(apiFeTempConfig, true); BufferedWriter out = new BufferedWriter(fstream); String aLine = null; while ((aLine = in.readLine()) != null) { if (aLine.equals("apife:")) { aLine = aLine.replace("apife:", "server:"); } out.write(aLine); out.newLine(); } in.close(); out.close(); // This approach can be simplified once the apife container is gone, but for the time being // it expects the first arg to be the string "server". String[] apiFeArgs = new String[2]; apiFeArgs[0] = "server"; apiFeArgs[1] = apiFeTempConfig.getAbsolutePath(); ApiFeService.setupApiFeConfigurationForServerCommand(apiFeArgs); ApiFeService.addServiceHost(xenonHost); ApiFeService.setSSLContext(sslContext); ApiFeService apiFeService = new ApiFeService(); apiFeService.run(apiFeArgs); apiFeTempConfig.deleteOnExit(); LocalApiClient localApiClient = apiFeService.getInjector().getInstance(LocalApiClient.class); xenonHost.setApiClient(localApiClient); // in the non-auth enabled scenario we need to be able to accept any self-signed certificate if (!deployerConfig.getDeployerContext().isAuthEnabled()) { KeyStoreUtils.acceptAllCerts(KeyStoreUtils.THRIFT_PROTOCOL); } Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { logger.info("Shutting down"); xenonHost.stop(); logger.info("Done"); LoggingFactory.detachAndStop(); } }); } catch (Exception e) { logger.error("Failed to start photon controller ", e); throw e; } }
From source file:Main.java
public static TrustManager[] getTrustManagers(KeyStore keyStore) throws KeyStoreException, NoSuchAlgorithmException, NoSuchProviderException { String trustManAlg = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(trustManAlg /* , PROVIDER_NAME */); tmf.init(keyStore);/*w w w . ja va2 s . c o m*/ return tmf.getTrustManagers(); }
From source file:Main.java
/** * Creates an SSLSocketFactory which contains {@code certChainFile} as its only root certificate. *//*w w w . j a va2 s . c o m*/ public static SSLSocketFactory newSslSocketFactoryForCa(InputStream certChain) throws Exception { KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null, null); CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate) cf.generateCertificate(new BufferedInputStream(certChain)); X500Principal principal = cert.getSubjectX500Principal(); ks.setCertificateEntry(principal.getName("RFC2253"), cert); // ks.setCertificateEntry("ca", cert); // Set up trust manager factory to use our key store. TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(ks); SSLContext context = SSLContext.getInstance("TLS"); context.init(null, trustManagerFactory.getTrustManagers(), null); return context.getSocketFactory(); }
From source file:Main.java
public static SSLSocketFactory setCertificates(InputStream... certificates) { try {/* ww w .ja va2s . c o m*/ CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null); int index = 0; for (InputStream certificate : certificates) { String certificateAlias = Integer.toString(index++); keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate)); try { if (certificate != null) certificate.close(); } catch (IOException e) { } } SSLContext sslContext = SSLContext.getInstance("TLS"); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom()); socketFactory = sslContext.getSocketFactory(); } catch (Exception e) { e.printStackTrace(); } return socketFactory; }
From source file:Main.java
private static TrustManager[] prepareTrustManager(InputStream... certificates) { if (certificates == null || certificates.length <= 0) return null; try {/*from w w w . j a v a 2s .c o m*/ CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null); int index = 0; for (InputStream certificate : certificates) { String certificateAlias = Integer.toString(index++); keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate)); try { if (certificate != null) certificate.close(); } catch (IOException e) { } } TrustManagerFactory trustManagerFactory = null; trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); return trustManagers; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:Main.java
private static TrustManager[] prepareTrustManager(InputStream... certificates) { if (certificates == null || certificates.length <= 0) return null; try {// w w w . java2s . com CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null); int index = 0; for (InputStream certificate : certificates) { String certificateAlias = Integer.toString(index++); keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate)); try { if (certificate != null) certificate.close(); } catch (IOException e) { e.printStackTrace(); } } TrustManagerFactory trustManagerFactory = null; trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); return trustManagers; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:com.allstate.client.ssl.SSLUtils.java
public static X509TrustManager getTrustManager(KeyStore trustStore) throws NoSuchAlgorithmException, KeyStoreException { TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); return (X509TrustManager) trustManagerFactory.getTrustManagers()[0]; }
From source file:Main.java
private static SSLContext sslContextForTrustedCertificates(InputStream in) { try {// ww w .ja va2 s.com CertificateFactory e = CertificateFactory.getInstance("X.509"); Collection certificates = e.generateCertificates(in); if (certificates.isEmpty()) { throw new IllegalArgumentException("expected non-empty set of trusted certificates"); } else { char[] password = "password".toCharArray(); KeyStore keyStore = newEmptyKeyStore(password); int index = 0; Iterator keyManagerFactory = certificates.iterator(); while (keyManagerFactory.hasNext()) { Certificate trustManagerFactory = (Certificate) keyManagerFactory.next(); String sslContext = Integer.toString(index++); keyStore.setCertificateEntry(sslContext, trustManagerFactory); } KeyManagerFactory var10 = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); var10.init(keyStore, password); TrustManagerFactory var11 = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); var11.init(keyStore); SSLContext var12 = SSLContext.getInstance("TLS"); var12.init(var10.getKeyManagers(), var11.getTrustManagers(), new SecureRandom()); return var12; } } catch (Exception var9) { var9.printStackTrace(); } return null; }