Example usage for javax.net.ssl KeyManagerFactory getInstance

List of usage examples for javax.net.ssl KeyManagerFactory getInstance

Introduction

In this page you can find the example usage for javax.net.ssl KeyManagerFactory getInstance.

Prototype

public static final KeyManagerFactory getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a KeyManagerFactory object that acts as a factory for key managers.

Usage

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  w w.  ja  va2s .  c o  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:MainClass.java

public static void main(String args[]) throws Exception {
    SSLContext context;/*from  w  ww .  ja  v a  2 s .c  o  m*/
    KeyManagerFactory kmf;
    KeyStore ks;
    char[] storepass = "newpass".toCharArray();
    char[] keypass = "wshr.ut".toCharArray();
    String storename = "newstore";

    context = SSLContext.getInstance("TLS");
    kmf = KeyManagerFactory.getInstance("SunX509");
    FileInputStream fin = new FileInputStream(storename);
    ks = KeyStore.getInstance("JKS");
    ks.load(fin, storepass);

    kmf.init(ks, keypass);
    context.init(kmf.getKeyManagers(), null, null);
    SSLServerSocketFactory ssf = context.getServerSocketFactory();

    ServerSocket ss = ssf.createServerSocket(5432);
    while (true) {
        Socket s = ss.accept();
        PrintStream out = new PrintStream(s.getOutputStream());
        out.println("Hi");
        out.close();
        s.close();
    }

}

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

/**
 * @param args/*from ww w .  jav a2  s  .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();/*  w ww.  j a  va2 s  . c o  m*/

    // 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:com.bfd.job.testClient.t04.ElementalHttpServer.java

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

    // 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();

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

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

    SSLServerSocketFactory sf = null;
    if (port == 8443) {
        // Initialize SSL context
        ClassLoader cl = ElementalHttpServer.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:mitm.common.security.ca.handlers.ejbca.ws.EjbcaWSClient.java

public static void main(String args[]) throws Exception {
    BasicConfigurator.configure();/*from w ww . j  a  va2s .com*/

    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:httpserver.ElementalHttpServer.java

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

    // Clay code, adding arguments to simulate command line execution
    args = new String[2];
    args[0] = "C://Users/Clay/Documents";
    args[1] = "80";

    if (args.length < 1) {
        System.err.println("Please specify document root directory");
        System.exit(1);/*from   w  ww  . ja va  2 s  .  com*/
    }
    // Document root directory
    String docRoot = args[0];

    // Setting up port, if port was specified, then use that one
    int port = 8080;
    if (args.length >= 2) {
        port = Integer.parseInt(args[1]);
    }

    // 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();

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

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

    SSLServerSocketFactory sf = null;
    if (port == 8443) {
        // Initialize SSL context
        ClassLoader cl = ElementalHttpServer.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:za.co.taung.httpdotserver.main.HttpDotServer.java

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

    LOG.info("Initialise server");

    // The parameter is the Port to listen on. Default is 8080. 
    int port = 8080;
    if (args.length >= 1) {
        port = Integer.parseInt(args[0]);
    }/*ww  w . j  av a 2  s  . c  o  m*/

    // Set up the HTTP protocol processor.
    HttpProcessor httpProcessor = HttpProcessorBuilder.create().add(new ResponseDate())
            .add(new ResponseServer("HttpDotServer/1.1")).add(new ResponseContent())
            .add(new ResponseConnControl()).build();

    // Set up request handler. This is the method that generates SVG. 
    UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();
    reqistry.register("*", new Dot2SVGHandler());

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

    // Set up SSL if listening on 8443 for https.
    SSLServerSocketFactory serverSocketFactory = null;
    if (port == 8443) {
        // Get the location of the keystore secrets.
        ClassLoader cl = HttpDotServer.class.getClassLoader();
        URL url = cl.getResource("my.keystore");
        if (url == null) {
            LOG.error("Keystore not found");
            System.exit(1);
        }
        // Load the secret into a keystore and manage the key material.
        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();
        // Prepare the socket factory for use by the RequestListenerThread.
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(keymanagers, null, null);
        serverSocketFactory = sslcontext.getServerSocketFactory();
    }

    LOG.debug("Start the RequestListenerThread");
    Thread thread = new RequestListenerThread(port, httpService, serverSocketFactory);
    thread.setDaemon(false);
    thread.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);/* w  w w .j a v  a  2  s. co  m*/
    }
    // 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");
}

From source file:yucatan.communication.server.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);/*ww w.j a  va2s .  c  o  m*/
    }
    // Document root directory
    File docRoot = new File(args[0]);
    int port = 8080;
    if (args.length >= 2) {
        port = Integer.parseInt(args[1]);
    }
    // HTTP parameters for the server
    HttpParams params = new SyncBasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpTest/1.1");
    // Create HTTP protocol processing chain
    HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
            // Use standard server-side protocol interceptors
            new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() });
    // Create request handler registry
    HttpAsyncRequestHandlerRegistry reqistry = new HttpAsyncRequestHandlerRegistry();
    // Register the default handler for all URIs
    reqistry.register("*", new HttpFileHandler(docRoot));
    // Create server-side HTTP protocol handler
    HttpAsyncService protocolHandler = new HttpAsyncService(httpproc, new DefaultConnectionReuseStrategy(),
            reqistry, params) {

        @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, params);
    } else {
        connFactory = new DefaultNHttpServerConnectionFactory(params);
    }
    // Create server-side I/O event dispatch
    IOEventDispatch ioEventDispatch = new DefaultHttpServerIODispatch(protocolHandler, connFactory);
    // Create server-side I/O reactor
    ListeningIOReactor ioReactor = new DefaultListeningIOReactor();
    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");
}