Example usage for javax.net.ssl SSLContext getSocketFactory

List of usage examples for javax.net.ssl SSLContext getSocketFactory

Introduction

In this page you can find the example usage for javax.net.ssl SSLContext getSocketFactory.

Prototype

public final SSLSocketFactory getSocketFactory() 

Source Link

Document

Returns a SocketFactory object for this context.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }/*from w ww.  jav a2  s  .  c o  m*/

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };

    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    URL url = new URL("https://hostname/index.html");
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }/*ww  w  .  ja v  a  2  s.c o  m*/

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };

    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    URL url = new URL("https://hostname/index.html");
}

From source file:com.cloudbees.tftwoway.Client.java

public static void main(String[] args) throws Exception {
    URL url = new URL(SERVER_ADDRESS);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

    SSLContext sslContext = createSSLContext();
    connection.setSSLSocketFactory(sslContext.getSocketFactory());

    connection.connect();//from w  ww.  j  av a2 s .c o m

    int responseCode = connection.getResponseCode();
    String response = IOUtils.toString(connection.getInputStream(), connection.getContentEncoding());
    System.out.println(responseCode);
    System.out.println(response);
}

From source file:com.yahoo.athenz.example.http.tls.client.HttpTLSClient.java

public static void main(String[] args) {

    // parse our command line to retrieve required input

    CommandLine cmd = parseCommandLine(args);

    final String url = cmd.getOptionValue("url");
    final String keyPath = cmd.getOptionValue("key");
    final String certPath = cmd.getOptionValue("cert");
    final String trustStorePath = cmd.getOptionValue("trustStorePath");
    final String trustStorePassword = cmd.getOptionValue("trustStorePassword");

    // we are going to setup our service private key and
    // certificate into a ssl context that we can use with
    // our http client

    try {/*from ww w  . j av a  2 s  .co m*/
        KeyRefresher keyRefresher = Utils.generateKeyRefresher(trustStorePath, trustStorePassword, certPath,
                keyPath);
        SSLContext sslContext = Utils.buildSSLContext(keyRefresher.getKeyManagerProxy(),
                keyRefresher.getTrustManagerProxy());

        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        HttpsURLConnection con = (HttpsURLConnection) new URL(url).openConnection();
        con.setReadTimeout(15000);
        con.setDoOutput(true);
        con.connect();

        try (BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            System.out.println("Data output: " + sb.toString());
        }

    } catch (Exception ex) {
        System.out.println("Exception: " + ex.getMessage());
        ex.printStackTrace();
        System.exit(1);
    }
}

From source file:com.tc.simple.apn.quicktests.Test.java

/**
 * @param args/*from  ww w  .ja v  a2 s . co m*/
 */

public static void main(String[] args) {
    SSLSocket socket = null;

    try {
        String host = "gateway.sandbox.push.apple.com";
        int port = 2195;

        String token = "de7f197546e41a76684f8e2d89f397ed165298d7772f4bd9b0f39c674b185b0f";
        System.out.println(token.toCharArray().length);

        //String token = "8cebc7c08f79fa62f0994eb4298387ff930857ff8d14a50de431559cf476b223";

        KeyStore keyStore = KeyStore.getInstance("PKCS12");

        keyStore.load(Test.class.getResourceAsStream("egram-dev-apn.p12"), "xxxxxxxxx".toCharArray());
        KeyManagerFactory keyMgrFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyMgrFactory.init(keyStore, "xxxxxxxxx".toCharArray());

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyMgrFactory.getKeyManagers(), null, null);
        SSLSocketFactory socketFactory = sslContext.getSocketFactory();

        socket = (SSLSocket) socketFactory.createSocket(host, port);
        String[] cipherSuites = socket.getSupportedCipherSuites();
        socket.setEnabledCipherSuites(cipherSuites);
        socket.startHandshake();

        char[] t = token.toCharArray();
        byte[] b = Hex.decodeHex(t);

        OutputStream outputstream = socket.getOutputStream();

        String payload = "{\"aps\":{\"alert\":\"yabadabadooo\"}}";

        int expiry = (int) ((System.currentTimeMillis() / 1000L) + 7200);

        ByteArrayOutputStream bout = new ByteArrayOutputStream();

        DataOutputStream dos = new DataOutputStream(bout);

        //command
        dos.writeByte(1);

        //id
        dos.writeInt(900);

        //expiry
        dos.writeInt(expiry);

        //token length.
        dos.writeShort(b.length);

        //token
        dos.write(b);

        //payload length
        dos.writeShort(payload.length());

        //payload.
        dos.write(payload.getBytes());

        byte[] byteMe = bout.toByteArray();

        socket.getOutputStream().write(byteMe);

        socket.setSoTimeout(900);
        InputStream in = socket.getInputStream();

        System.out.println(APNErrors.getError(in.read()));

        in.close();

        outputstream.close();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            socket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

From source file:at.peppol.smp.client.console.SMPClient.java

public static void main(final String[] args) throws Exception {
    if (false) {//from   ww w.  ja  v a 2s.  co  m
        // Enable this section in development mode, if you want to trust all HTTPS
        // certificates
        final SSLContext aSSLContext = SSLContext.getInstance("SSL");
        aSSLContext.init(null, new TrustManager[] { new DoNothingTrustManager() },
                VerySecureRandom.getInstance());
        HttpsURLConnection.setDefaultSSLSocketFactory(aSSLContext.getSocketFactory());
    }

    final SMPClientOptions aOptions = new SMPClientOptions();
    final CommandLine cmd = new PosixParser().parse(aOptions, args);

    ECommand eAction = null;
    boolean bGoodCmd = true;
    String cert = null;

    if (!cmd.hasOption("h")) {
        s_aLogger.error("No Host specified use -h to specify Host");
        bGoodCmd = false;
    }

    if (!cmd.hasOption("u")) {
        s_aLogger.error("No Username specified use -u to specify username");
        bGoodCmd = false;
    }

    if (!cmd.hasOption("p")) {
        s_aLogger.error("No Password specified use -p to specify password");
        bGoodCmd = false;
    }

    if (!cmd.hasOption("c")) {
        s_aLogger.error("No Action specified please use -c parameter to specify command("
                + ECommand.getAllAsString() + ")");
        bGoodCmd = false;
    } else {
        final String sCommand = cmd.getOptionValue("c");
        eAction = ECommand.getFromNameOrNull(sCommand);
        if (eAction == null) {
            s_aLogger.error("Illegal Action specified:" + sCommand + " allowed commands("
                    + ECommand.getAllAsString() + ")");
            bGoodCmd = false;
        } else
            switch (eAction) {
            case ADDGROUP:
                if (!cmd.hasOption("b")) {
                    s_aLogger.error(
                            "No Business/Participant ID specified use -b to specify Business/Participant ID");
                    bGoodCmd = false;
                }
                break;
            case DELGROUP:
                if (!cmd.hasOption("b")) {
                    s_aLogger.error(
                            "No Business/Participant ID specified use -b to specify Business/Participant ID");
                    bGoodCmd = false;
                }
                break;
            case ADD:
                if (!cmd.hasOption("a")) {
                    s_aLogger.error("No Accesspoint URL defined use -a to Specifify AP-URL");
                    bGoodCmd = false;
                }
                if (!cmd.hasOption("b")) {
                    s_aLogger.error(
                            "No Business/Participant ID specified use -b to specify Business/Participant ID");
                    bGoodCmd = false;
                }
                if (!cmd.hasOption("d")) {
                    s_aLogger.error("No DocumentType ID specified use -d to specify Document Type ID");
                    bGoodCmd = false;
                }
                if (!cmd.hasOption("r")) {
                    s_aLogger.error("No Process ID specified use -r to specify Process ID");
                    bGoodCmd = false;
                }
                if (!cmd.hasOption("e")) {
                    s_aLogger.error("No Certificate PEM file specified use -e to specify Certificate PEM file");
                    bGoodCmd = false;
                } else {
                    cert = SimpleFileIO.readFileAsString(new File(cmd.getOptionValue('e')),
                            CCharset.CHARSET_ISO_8859_1);
                }
                break;
            case DEL:
                if (!cmd.hasOption("b")) {
                    s_aLogger.error(
                            "No Business/Participant ID specified use -b to specify Business/Participant ID");
                    bGoodCmd = false;
                }
                if (!cmd.hasOption("d")) {
                    s_aLogger.error("No Document Type ID specified use -d to specify Document Type ID");
                    bGoodCmd = false;
                }
            }
    }

    if (!bGoodCmd) {
        final NonBlockingStringWriter aSW = new NonBlockingStringWriter();
        new HelpFormatter().printHelp(new PrintWriter(aSW), HelpFormatter.DEFAULT_WIDTH,
                CGStringHelper.getClassLocalName(SMPClient.class), null, aOptions,
                HelpFormatter.DEFAULT_LEFT_PAD, HelpFormatter.DEFAULT_DESC_PAD, null);
        s_aLogger.info(aSW.getAsString());
        System.exit(-3);
    }

    final SMPClient client = new SMPClient(new URI(cmd.getOptionValue('h')), cmd.getOptionValue('u'),
            cmd.getOptionValue('p'), cmd.getOptionValue('b'), cmd.getOptionValue('d'), cmd.getOptionValue('r'),
            cmd.getOptionValue('a'), cert);

    switch (eAction) {
    case ADDGROUP:
        client._createServiceGroup();
        break;
    case DELGROUP:
        client._deleteServiceGroup();
        break;
    case ADD:
        client._addDocument();
        break;
    case DEL:
        client._deleteDocument();
        break;
    case LIST:
        client._listDocuments();
        break;
    default:
        throw new IllegalStateException();
    }
}

From source file:net.sf.jsignpdf.InstallCert.java

/**
 * The main - whole logic of Install Cert Tool.
 * /*from  w ww.  j a  v  a 2 s  .com*/
 * @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:net.fenyo.gnetwatch.CommandLine.java

/**
 * General entry point.//w  ww . j a va 2s. co  m
 * @param args command line arguments.
 * @return void.
 * @throws IOException io exception.
 * @throws FileNotFoundException file not found.
 */
public static void main(final String[] args)
        throws IOException, FileNotFoundException, InterruptedException, AlgorithmException {
    Config config = null;
    Synchro synchro = null;
    Background background = null;
    GUI gui = null;
    Main main = null;
    SNMPManager snmp_manager = null;
    CaptureManager capture_mgr = null;

    if (args.length > 0) {
        if (args.length == 4 && args[0].equals("import") && args[1].equals("source")) {
            importGenericSrc(args);
            return;
        }
        log.error("invalid arguments");
        System.exit(1);
    }

    // Get configuration properties
    config = new Config();

    // Set debug level
    // debug level 1: simulate hundreds of ping per second to check the DB and hibernate abilities to handle lots of events
    config.setDebugLevel(0);

    // Read general logging rules
    GenericTools.initLogEngine(config);
    log.info(config.getString("log_engine_initialized"));
    log.info(config.getString("begin"));

    /*
    final MessageBox dialog = new MessageBox(new Shell(new org.eclipse.swt.widgets.Display()),
        SWT.ICON_QUESTION | SWT.YES | SWT.NO);
    // traduire
    dialog.setText("GNetWatch startup");
    dialog.setMessage("Database Selection:\ndo you want to erase the current database content ?");
    dialog.open();
    */

    // Initialize Object-Relational mapping
    synchro = new Synchro(config);

    // Do not check SSL certificates
    SSLContext ssl_context = null;
    try {
        ssl_context = SSLContext.getInstance("SSL");
        ssl_context.init(null, new TrustManager[] { new NoCheckTrustManager() }, new SecureRandom());
    } catch (final NoSuchAlgorithmException ex) {
        log.error("Exception", ex);
    } catch (final KeyManagementException ex) {
        log.error("Exception", ex);
    }
    HttpsURLConnection.setDefaultSSLSocketFactory(ssl_context.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        public final boolean verify(String hostname, SSLSession session) {
            return true;
        }
    });

    // Initialize background processes management
    background = new Background(config);
    background.createBackgroundThread();

    // Initialize packet capture on every interface
    capture_mgr = new CaptureManager(config);

    // Initialize main processes management
    main = new Main(config, capture_mgr);

    // Build SNMP Manager
    snmp_manager = new SNMPManager();

    // Build GUI
    gui = new GUI(config, background, main, snmp_manager, synchro);
    main.setGUI(gui);
    capture_mgr.setGUI(gui);
    gui.waitForCreation();

    // Initial configuration
    gui.createFromXML(gui.getConfig().getProperty("initialobjects"));

    // Move the GUI to the top of the drawing order
    gui.showGUI();

    // merge events at startup
    background.informQueue("merge-1", gui);

    // Wait for the GUI to terminate
    gui.join();
    // The GUI is now closed
    log.info(config.getString("end"));

    // Stop every application thread
    config.setEnd();
    gui.end();
    background.end();
    capture_mgr.unRegisterAllListeners();

    // stop synchronizing
    synchro.end();
}

From source file:org.opennms.protocols.vmware.VmwareConfigBuilder.java

public static void main(String[] args) throws ParseException {
    String hostname = null;//from   w w  w  .j  av a 2 s. com
    String username = null;
    String password = null;
    String rrdRepository = null;

    final Options options = new Options();

    options.addOption("rrdRepository", true,
            "set rrdRepository path for generated config files, default: '/opt/opennms/share/rrd/snmp/'");

    final CommandLineParser parser = new PosixParser();
    final CommandLine cmd = parser.parse(options, args);

    @SuppressWarnings("unchecked")
    List<String> arguments = (List<String>) cmd.getArgList();

    if (arguments.size() < 3) {
        usage(options, cmd);
        System.exit(1);
    }

    hostname = arguments.remove(0);
    username = arguments.remove(0);
    password = arguments.remove(0);

    if (cmd.hasOption("rrdRepository")) {
        rrdRepository = cmd.getOptionValue("rrdRepository");
    } else {
        rrdRepository = "/opt/opennms/share/rrd/snmp/";
    }

    TrustManager[] trustAllCerts = new TrustManager[1];

    trustAllCerts[0] = new TrustAllManager();

    SSLContext sc = null;
    try {
        sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    HostnameVerifier hv = new HostnameVerifier() {
        @Override
        public boolean verify(String urlHostName, SSLSession session) {
            return true;
        }
    };

    HttpsURLConnection.setDefaultHostnameVerifier(hv);

    VmwareConfigBuilder vmwareConfigBuilder;

    vmwareConfigBuilder = new VmwareConfigBuilder(hostname, username, password);

    try {
        vmwareConfigBuilder.generateData(rrdRepository);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.eclipse.aether.transport.http.SslSocketFactory.java

private static SSLSocketFactory getSocketFactory(SSLContext context) {
    return (context != null) ? context.getSocketFactory() : (SSLSocketFactory) SSLSocketFactory.getDefault();
}