JSSE server/client SSL connection Example

Posted on November 11, 2012. Filed under: java/j2EE |


http://www.maximporges.com/2009/11/18/configuring-tomcat-ssl-clientserver-authentication/

http://docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html

  • Step 1 Create self-signed server and client certificates with keytool.
  • Step 2 create server java code.
  • Step 3 create client java code.
SSLDemo #mkdir ssldemo
SSLDemo #cd ssldemo/
SSLDemo #echo "Generate the Client and Server Keystores" > /dev/null
SSLDemo #keytool -genkeypair -alias plainserverkeys -keyalg RSA -dname "CN=Plain Server,OU=kl2217,O=kl2217org,L=Boston,ST=MA,C=US" -keypass password -keystore plainserver.jks -storepass password
SSLDemo #keytool -genkeypair -alias plainclientkeys -keyalg RSA -dname "CN=Plain Client,OU=kl2217,O=kl2217org,L=Boston,ST=MA,C=US" -keypass password -keystore plainclient.jks -storepass password
SSLDemo #echo "Export the server public certificate and create a seperate keystore">/dev/null
SSLDemo #keytool -exportcert -alias plainserverkeys -file serverpub.cer -keystore plainserver.jks -storepass password
Certificate stored in file <serverpub.cer>
SSLDemo #keytool -importcert -keystore serverpub.jks -alias serverpub -file serverpub.cer -storepass password
Owner: CN=Plain Server, OU=kl2217, O=kl2217org, L=Boston, ST=MA, C=US
Issuer: CN=Plain Server, OU=kl2217, O=kl2217org, L=Boston, ST=MA, C=US
Serial number: 509fdd3e
Valid from: Sun Nov 11 12:15:42 EST 2012 until: Sat Feb 09 12:15:42 EST 2013
Certificate fingerprints:
 MD5: 22:28:1C:8C:EE:19:10:E6:E4:A3:A3:F8:24:D0:E3:11
 SHA1: 22:C7:1B:18:0D:8D:0A:6D:31:BD:CF:90:09:E9:6A:42:AA:4B:14:2A
 Signature algorithm name: SHA1withRSA
 Version: 3
Trust this certificate? [no]: yes
Certificate was added to keystore
SSLDemo #echo "Export the client public certificate and create a seperate keystore">/dev/null
SSLDemo #keytool -exportcert -alias plainclientkeys -file clientpub.cer -keystore plainclient.jks -storepass password
Certificate stored in file <clientpub.cer>
SSLDemo #keytool -importcert -keystore clientpub.jks -alias clientpub -file clientpub.cer -storepass password
Owner: CN=Plain Client, OU=kl2217, O=kl2217org, L=Boston, ST=MA, C=US
Issuer: CN=Plain Client, OU=kl2217, O=kl2217org, L=Boston, ST=MA, C=US
Serial number: 509fdd8c
Valid from: Sun Nov 11 12:17:00 EST 2012 until: Sat Feb 09 12:17:00 EST 2013
Certificate fingerprints:
 MD5: 6A:4B:AC:16:6B:5B:4E:A4:F2:9B:4C:83:A9:6D:31:4D
 SHA1: 71:EA:11:0E:87:DB:E1:ED:66:68:C3:D4:D9:78:83:48:C9:C0:15:69
 Signature algorithm name: SHA1withRSA
 Version: 3
Trust this certificate? [no]: yes
Certificate was added to keystore</pre>
SSLDemo #ls
clientpub.cer clientpub.jks plainclient.jks plainserver.jks serverpub.cer serverpub.jks
SSLDemo #vi PlainServer.java
SSLDemo #vi PlainClient.java
SSLDemo #cat PlainServer.java
import java.io.*;
import java.security.*;
import javax.net.ssl.*;

public class PlainServer {
 public static void main(String [] args) {
 SSLServerSocket serverSock = null;
 SSLSocket socket = null;
 PrintWriter out = null;
 try {
 //load server private key
 KeyStore serverKeys = KeyStore.getInstance("JKS");
 serverKeys.load(new FileInputStream("plainserver.jks"),"password".toCharArray());
 KeyManagerFactory serverKeyManager = KeyManagerFactory.getInstance("SunX509");
 //System.out.println(KeyManagerFactory.getDefaultAlgorithm());
 //System.out.println(serverKeyManager.getProvider());
 serverKeyManager.init(serverKeys,"password".toCharArray());
 //load client public key
 KeyStore clientPub = KeyStore.getInstance("JKS");
 clientPub.load(new FileInputStream("clientpub.jks"),"password".toCharArray());
 TrustManagerFactory trustManager = TrustManagerFactory.getInstance("SunX509");
 trustManager.init(clientPub);
 //use keys to create SSLSoket
 SSLContext ssl = SSLContext.getInstance("TLS");
 ssl.init(serverKeyManager.getKeyManagers(), trustManager.getTrustManagers(), SecureRandom.getInstance("SHA1PRNG"));
 serverSock = (SSLServerSocket)ssl.getServerSocketFactory().createServerSocket(8889);
 serverSock.setNeedClientAuth(true);
 socket = (SSLSocket)serverSock.accept();
 //send data
 out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
 out.println("data from PlainServer");
 out.flush();
 } catch (Exception e) {
 e.printStackTrace();
 } finally {
 if(out!=null) out.close();
 try {
 if(serverSock!=null) serverSock.close();
 if(socket!=null) socket.close();
 } catch (IOException e) {
 e.printStackTrace();
 }
 }
 }
}

SSLDemo #cat PlainClient.java
import java.io.*;
import java.security.*;
import javax.net.ssl.*;

public class PlainClient {
 public static void main(String [] args) {
 SSLSocket socket = null;
 BufferedReader in = null;
 try {
 //load client private key
 KeyStore clientKeys = KeyStore.getInstance("JKS");
 clientKeys.load(new FileInputStream("plainclient.jks"),"password".toCharArray());
 KeyManagerFactory clientKeyManager = KeyManagerFactory.getInstance("SunX509");
 clientKeyManager.init(clientKeys,"password".toCharArray());
 //load server public key
 KeyStore serverPub = KeyStore.getInstance("JKS");
 serverPub.load(new FileInputStream("serverpub.jks"),"password".toCharArray());
 TrustManagerFactory trustManager = TrustManagerFactory.getInstance("SunX509");
 trustManager.init(serverPub);
 //use keys to create SSLSoket
 SSLContext ssl = SSLContext.getInstance("TLS");
 ssl.init(clientKeyManager.getKeyManagers(), trustManager.getTrustManagers(), SecureRandom.getInstance("SHA1PRNG"));
 socket = (SSLSocket)ssl.getSocketFactory().createSocket("localhost", 8889);
 socket.startHandshake();
 //receive data
 in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
 String data;
 while((data = in.readLine())!=null) {
 System.out.println(data);
 }
 } catch (Exception e) {
 e.printStackTrace();
 } finally {
 try {
 if(in!=null) in.close();
 if(socket!=null) socket.close();
 if(socket!=null) socket.close();
 } catch (IOException e) {
 e.printStackTrace();
 }
 }
 }
}

SSLDemo #
SSLDemo #javac PlainServer.java PlainClient.java
SSLDemo #java PlainServer &
[1] 5749
SSLDemo #java PlainClient
data from PlainServer
[1]+ Done java PlainServer
SSLDemo #

 

Advertisements

Make a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

4 Responses to “JSSE server/client SSL connection Example”

RSS Feed for IT Certifications Comments RSS Feed

This example is very usefull!!! Thanks!!!

hi,
I’ve tested your code and it’s allright. I have a question : I want to deploy java client app (pure jars) with a server public key to enable https communication between them : which file should be boudle with client’s jars to enable this secured communication ?
thanks !
Phil

Thanks for this great tutorial! This example saved my day…

Very good example thank you


Where's The Comment Form?

Liked it here?
Why not try sites on the blogroll...

%d bloggers like this: