Example usage for javax.net.ssl SSLContext init

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

Introduction

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

Prototype

public final void init(KeyManager[] km, TrustManager[] tm, SecureRandom random) throws KeyManagementException 

Source Link

Document

Initializes 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;
        }/* w  ww  . j  ava2  s  . c  om*/

        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;
        }// www .  j a 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:MainClass.java

public static void main(String[] args) throws Exception {
    char[] passphrase = "password".toCharArray();
    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(new FileInputStream(".keystore"), passphrase);
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(keystore, passphrase);//from  w  ww  .  j a va2  s . co  m
    SSLContext context = SSLContext.getInstance("TLS");
    KeyManager[] keyManagers = kmf.getKeyManagers();

    context.init(keyManagers, null, null);

    SSLServerSocketFactory ssf = context.getServerSocketFactory();
    ServerSocket ss = ssf.createServerSocket(PORT);

    Socket s = ss.accept();

    BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

    String line = null;
    while (((line = in.readLine()) != null)) {
        System.out.println(line);
    }
    in.close();
    s.close();
}

From source file:org.switchyard.quickstarts.demo.policy.security.basic.propagate.WorkServiceMain.java

public static void main(String... args) throws Exception {
    Set<String> policies = new HashSet<String>();
    for (String arg : args) {
        arg = Strings.trimToNull(arg);/*from w  w  w  . j  a v a  2 s. c o m*/
        if (arg != null) {
            if (arg.equals(CONFIDENTIALITY) || arg.equals(CLIENT_AUTHENTICATION) || arg.equals(HELP)) {
                policies.add(arg);
            } else {
                LOGGER.error(MAVEN_USAGE);
                throw new Exception(MAVEN_USAGE);
            }
        }
    }
    if (policies.contains(HELP)) {
        LOGGER.info(MAVEN_USAGE);
    } else {
        final String scheme;
        final int port;
        if (policies.contains(CONFIDENTIALITY)) {
            scheme = "https";
            port = 8443;
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, null, null);
            SSLSocketFactory sf = new SSLSocketFactory(sslcontext, SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
            Scheme https = new Scheme(scheme, port, sf);
            SchemeRegistry sr = new SchemeRegistry();
            sr.register(https);
        } else {
            scheme = "http";
            port = 8080;
        }
        String[] userPass = policies.contains(CLIENT_AUTHENTICATION) ? new String[] { "kermit", "the-frog-1" }
                : null;
        invokeWorkService(scheme, port, userPass);
    }
}

From source file:org.switchyard.quickstarts.demo.policy.security.wss.signencrypt.WorkServiceMain.java

public static void main(String... args) throws Exception {
    Set<String> policies = new HashSet<String>();
    for (String arg : args) {
        arg = Strings.trimToNull(arg);/*from  w  w w. ja v a  2  s .  com*/
        if (arg != null) {
            if (arg.equals(CONFIDENTIALITY) || arg.equals(SIGNENCRYPT) || arg.equals(HELP)) {
                policies.add(arg);
            } else {
                LOGGER.error(MAVEN_USAGE);
                throw new Exception(MAVEN_USAGE);
            }
        }
    }
    if (policies.contains(HELP)) {
        LOGGER.info(MAVEN_USAGE);
    } else {
        final String scheme;
        final int port;
        if (policies.contains(CONFIDENTIALITY)) {
            scheme = "https";
            port = getPort(8443);
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, null, null);
            SSLSocketFactory sf = new SSLSocketFactory(sslcontext, SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
            Scheme https = new Scheme(scheme, port, sf);
            SchemeRegistry sr = new SchemeRegistry();
            sr.register(https);
        } else {
            scheme = "http";
            port = getPort(8080);
        }
        boolean signencrypt = policies.contains(SIGNENCRYPT);
        invokeWorkService(scheme, port, getContext(), signencrypt);
    }
}

From source file:org.switchyard.quickstarts.demo.security.propagation.jms.WorkServiceMain.java

public static void main(String... args) throws Exception {
    Set<String> policies = new HashSet<String>();
    for (String arg : args) {
        arg = Strings.trimToNull(arg);//from w ww .j  a  va  2  s. co  m
        if (arg != null) {
            if (arg.equals(CONFIDENTIALITY) || arg.equals(CLIENT_AUTHENTICATION) || arg.equals(HELP)) {
                policies.add(arg);
            } else {
                LOGGER.error(MAVEN_USAGE);
                throw new Exception(MAVEN_USAGE);
            }
        }
    }
    if (policies.contains(HELP)) {
        LOGGER.info(MAVEN_USAGE);
    } else {
        final String scheme;
        final int port;
        if (policies.contains(CONFIDENTIALITY)) {
            scheme = "https";
            port = getPort(8443);
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, null, null);
            SSLSocketFactory sf = new SSLSocketFactory(sslcontext, SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
            Scheme https = new Scheme(scheme, port, sf);
            SchemeRegistry sr = new SchemeRegistry();
            sr.register(https);
        } else {
            scheme = "http";
            port = getPort(8080);
        }
        String[] userPass = policies.contains(CLIENT_AUTHENTICATION) ? new String[] { "kermit", "the-frog-1" }
                : null;
        invokeWorkService(scheme, port, getContext(), userPass);
    }
}

From source file:org.acme.insurance.policyquote.test.WorkServiceMain.java

public static void main(String... args) throws Exception {
    serverHostname = System.getProperty("serverHostname", serverHostname);

    Set<String> policies = new HashSet<String>();
    for (String arg : args) {
        arg = Strings.trimToNull(arg);//from   w  w w.  j  ava2s . c o  m
        if (arg != null) {
            if (arg.equals(CONFIDENTIALITY) || arg.equals(CLIENT_AUTHENTICATION) || arg.equals(HELP)) {
                policies.add(arg);
            } else {
                LOGGER.error(MAVEN_USAGE);
                throw new Exception(MAVEN_USAGE);
            }
        }
    }
    if (policies.contains(HELP)) {
        LOGGER.info(MAVEN_USAGE);
    } else {
        final String scheme;
        final int port;
        if (policies.contains(CONFIDENTIALITY)) {
            LOGGER.info("Invoking service via SSL...");
            scheme = "https";
            port = 443;
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, null, null);
            SSLSocketFactory sf = new SSLSocketFactory(sslcontext, SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
            Scheme https = new Scheme(scheme, port, sf);
            SchemeRegistry sr = new SchemeRegistry();
            sr.register(https);
        } else {
            scheme = "http";
            port = 8080;
        }
        Element assertion = policies.contains(CLIENT_AUTHENTICATION) ? getAssertion() : null;
        invokeWorkService(scheme, port, assertion);
    }
}

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

/**
 * @param args/*  w  ww.  j  a  va 2s .  c  o 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:com.adhi.webserver.WebServer.java

public static void main(String[] args) throws Exception {

    int port = 9999;

    // Set up the HTTP protocol processor
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate())
            .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl())
            .build();/*from   w w  w.  java 2 s  . com*/

    // Set up request handlers
    UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();
    reqistry.register("*", new MessageCommandHandler());

    // Set up the HTTP service
    HttpService httpService = new HttpService(httpproc, reqistry);

    SSLServerSocketFactory sf = null;
    if (port == 8443) {
        // Initialize SSL context
        ClassLoader cl = WebServer.class.getClassLoader();
        URL url = cl.getResource("my.keystore");
        if (url == null) {
            System.out.println("Keystore not found");
            System.exit(1);
        }
        KeyStore keystore = KeyStore.getInstance("jks");
        keystore.load(url.openStream(), "secret".toCharArray());
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmfactory.init(keystore, "secret".toCharArray());
        KeyManager[] keymanagers = kmfactory.getKeyManagers();
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(keymanagers, null, null);
        sf = sslcontext.getServerSocketFactory();
    }

    Thread t = new RequestListenerThread(port, httpService, sf);
    t.setDaemon(false);
    t.start();
}

From source file:proxy.NHttpServer.java

public static void main(String[] args) throws Exception {
    if (args.length < 1) {
        System.err.println("Please specify document root directory");
        System.exit(1);//from   w ww .java 2  s  .  com
    }
    // Document root directory
    File docRoot = new File(args[0]);
    int port = 8080;
    if (args.length >= 2) {
        port = Integer.parseInt(args[1]);
    }

    // Create HTTP protocol processing chain
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate())
            .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl())
            .build();
    // Create request handler registry
    UriHttpAsyncRequestHandlerMapper reqistry = new UriHttpAsyncRequestHandlerMapper();
    // Register the default handler for all URIs
    reqistry.register("*", new HttpFileHandler(docRoot));
    // Create server-side HTTP protocol handler
    HttpAsyncService protocolHandler = new HttpAsyncService(httpproc, reqistry) {

        @Override
        public void connected(final NHttpServerConnection conn) {
            System.out.println(conn + ": connection open");
            super.connected(conn);
        }

        @Override
        public void closed(final NHttpServerConnection conn) {
            System.out.println(conn + ": connection closed");
            super.closed(conn);
        }

    };
    // Create HTTP connection factory
    NHttpConnectionFactory<DefaultNHttpServerConnection> connFactory;
    if (port == 8443) {
        // Initialize SSL context
        ClassLoader cl = NHttpServer.class.getClassLoader();
        URL url = cl.getResource("my.keystore");
        if (url == null) {
            System.out.println("Keystore not found");
            System.exit(1);
        }
        KeyStore keystore = KeyStore.getInstance("jks");
        keystore.load(url.openStream(), "secret".toCharArray());
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmfactory.init(keystore, "secret".toCharArray());
        KeyManager[] keymanagers = kmfactory.getKeyManagers();
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(keymanagers, null, null);
        connFactory = new SSLNHttpServerConnectionFactory(sslcontext, null, ConnectionConfig.DEFAULT);
    } else {
        connFactory = new DefaultNHttpServerConnectionFactory(ConnectionConfig.DEFAULT);
    }
    // Create server-side I/O event dispatch
    IOEventDispatch ioEventDispatch = new DefaultHttpServerIODispatch(protocolHandler, connFactory);
    // Set I/O reactor defaults
    IOReactorConfig config = IOReactorConfig.custom().setIoThreadCount(1).setSoTimeout(3000)
            .setConnectTimeout(3000).build();
    // Create server-side I/O reactor
    ListeningIOReactor ioReactor = new DefaultListeningIOReactor(config);
    try {
        // Listen of the given port
        ioReactor.listen(new InetSocketAddress(port));
        // Ready to go!
        ioReactor.execute(ioEventDispatch);
    } catch (InterruptedIOException ex) {
        System.err.println("Interrupted");
    } catch (IOException e) {
        System.err.println("I/O error: " + e.getMessage());
    }
    System.out.println("Shutdown");
}