Example usage for javax.net.ssl TrustManagerFactory init

List of usage examples for javax.net.ssl TrustManagerFactory init

Introduction

In this page you can find the example usage for javax.net.ssl TrustManagerFactory init.

Prototype

public final void init(ManagerFactoryParameters spec) throws InvalidAlgorithmParameterException 

Source Link

Document

Initializes this factory with a source of provider-specific trust material.

Usage

From source file:mitm.common.security.ca.handlers.ejbca.ws.EjbcaWSClient.java

public static void main(String args[]) throws Exception {
    BasicConfigurator.configure();/* w  ww .  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.
 * /*  w w 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  .  ja  v a  2 s.com*/
        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);
    return tmf.getTrustManagers();
}

From source file:Main.java

/**
 * Generate a SSLSocketFactory wich checks the certificate given
 * @param context Context to use// www. j a  v  a  2  s.c o m
 * @param rResource int with url of the resource to read the certificate
 * @parma password String to use with certificate
 * @return SSLSocketFactory generated to validate this certificate
 */
public static SSLSocketFactory newSslSocketFactory(Context context, int rResource, String password)
        throws CertificateException, NoSuchProviderException, KeyStoreException, NoSuchAlgorithmException,
        IOException, UnrecoverableKeyException, KeyManagementException {

    // Get an instance of the Bouncy Castle KeyStore format
    KeyStore trusted = KeyStore.getInstance("BKS");
    // Get the raw resource, which contains the keystore with
    // your trusted certificates (root and any intermediate certs)
    InputStream is = context.getApplicationContext().getResources().openRawResource(rResource);

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
    X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(is);
    String alias = "alias";//cert.getSubjectX500Principal().getName();

    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null);
    trustStore.setCertificateEntry(alias, cert);
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
    kmf.init(trustStore, null);
    KeyManager[] keyManagers = kmf.getKeyManagers();

    TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
    tmf.init(trustStore);
    TrustManager[] trustManagers = tmf.getTrustManagers();

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagers, trustManagers, null);
    return sslContext.getSocketFactory();

}

From source file:Main.java

public static SocketFactory getSocketFactoryWithCustomCA(InputStream stream) throws CertificateException,
        KeyStoreException, IOException, NoSuchAlgorithmException, KeyManagementException {

    // Load CAs from an InputStream
    // (could be from a resource or ByteArrayInputStream or ...)
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    InputStream caInput = new BufferedInputStream(stream);
    Certificate ca;//from  www .  j av a  2 s  .com
    try {
        ca = cf.generateCertificate(caInput);
        System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
    } finally {
        try {
            caInput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", ca);

    // Create a TrustManager that trusts the CAs in our KeyStore
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);

    // Create an SSLContext that uses our TrustManager
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, tmf.getTrustManagers(), null);

    return context.getSocketFactory();
}

From source file:Main.java

/**
 * Creates an SSLSocketFactory which contains {@code certChainFile} as its only root certificate.
 *//*from  ww w .  j a  v  a2 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:org.rhq.enterprise.server.plugins.rhnhosted.RHNSSLSocketFactory.java

/**
 *
 * @param sslCerts these certs will be used to validate the ssl connection
 * @return/*from  w w  w .j  a  v a2  s .  c om*/
 * @throws IOException
 * @throws GeneralSecurityException
 */
static public SSLSocketFactory getSSLSocketFactory(List<X509Certificate> sslCerts)
        throws IOException, GeneralSecurityException {
    SSLContext sc = null;
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(null); //Important, this intializes the keystore
    int counter = 0;
    for (X509Certificate cert : sslCerts) {
        ks.setCertificateEntry("rhn-key-" + counter, cert);
        counter++;
    }
    sc = SSLContext.getInstance("SSL");
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);
    sc.init(null, tmf.getTrustManagers(), new java.security.SecureRandom());
    return sc.getSocketFactory();
}

From source file:org.elasticsearch.client.RestClientBuilderIntegTests.java

private static SSLContext getSslContext() throws Exception {
    SSLContext sslContext = SSLContext.getInstance("TLS");
    try (InputStream in = RestClientBuilderIntegTests.class.getResourceAsStream("/testks.jks")) {
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(in, "password".toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(keyStore, "password".toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(keyStore);
        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    }// w ww  .j  a  v a 2 s  .c  o  m
    return sslContext;
}

From source file:spade.client.CommandLine.java

private static void setupClientSSLContext() throws Exception {
    SecureRandom secureRandom = new SecureRandom();
    secureRandom.nextInt();//w  w  w.j a  va2s . c o m

    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(serverKeyStorePublic);
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(clientKeyStorePrivate, "private".toCharArray());

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), secureRandom);
    sslSocketFactory = sslContext.getSocketFactory();
}