Search code examples
javasecuritysslx509certificateserversocket

SSL server socket and handshake with known certificate


I am new to SSl server sockets. All I am tying to do is to read data over SSL. My application listens on port 8000. Please give me few steps on how I can do this. When I have a certificate (on my disc), how can I establish the SSL server socket and read from client ?

Here are my steps

1) reading server.crt from file and making X509Certificate (has public certificate and private key) 2) Getting instance of JKS keystore

3) Get instance of context

4) create server socket over the port (8000)

InputStream in = new DataInputStream(new FileInputStream(new File("server.crt")));
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, null);

CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(in);
in.close();

ks.setCertificateEntry("dts", cert);

char[] newpass = "password".toCharArray();
String name = "mykeystore.ks";
FileOutputStream output = new FileOutputStream(name);
ks.store(output, newpass);

KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, "password".toCharArray());




try{

    System.setProperty("javax.net.ssl.keyStore","mykeystore.ks");
    System.setProperty("javax.net.ssl.keyStorePassword","password");
    System.setProperty("javax.net.debug","all");



    SSLContext context = SSLContext.getInstance("TLSv1.2");
    context.init(kmf.getKeyManagers(), null, null);
    SSLServerSocketFactory sslServerSocketfactory = context.getServerSocketFactory();
    SSLServerSocket sslServerSocket = (SSLServerSocket)sslServerSocketfactory.createServerSocket(8000);
    SSLSocket sslSocket = (SSLSocket)sslServerSocket.accept();  


    InputStream dataIN = sslSocket.getInputStream();

    byte[] hello = new byte[20];

    dataIN.read(hello);
    System.out.println(new String(hello));

    dataIN.close();

} catch (IOException e){
    e.printStackTrace();
}

Solution

  • I got the answer for my question, I did research on how to setup my own keystore with self signed certificate. This way helped me.

    ping me for a detailed solutions.