Requirement : Create JKS keystore and truststore out of certificate and private key files given in pem format.

Try to open the certificate and key files and it contains ASCII text that starts with —–BEGIN CERTIFICATE—–, then it is in PEM format.

Using keytool in java, when a keystore is created it already has the private key in it. Keytool does not allow us to import a private key into a keystore. Thus we need to use OpenSSL for this but OpenSSL creates the keystore in pkcs12 format. So we use jetty to convert our pkcs12 into jks format.

OpenSSL for Windows is available from http://www.slproweb.com/products/Win32OpenSSL.html.

Keystore to be created : keystore.pkcs12, Certificate File : test.cert.pem, PrivateKey File : test.key.pem.
openssl pkcs12 -export -out keystore.pkcs12 -in test.cert.pem -inkey test.key.pem
Enter the appropriate password. Now using jetty we can convert the pkcs12 keystore into jks keystore (keystore.jks).
java -cp c:\jetty\lib\jetty-6.1.1.jar org.mortbay.jetty.security.PKCS12Import keystore.pkcs12 keystore.jks

Now to create truststore file.
keytool -import -alias test -file test.cert.pem -keystore truststore

where truststore is the new TrustStore in jks format. You can import as many other certificates as you need to trust into the truststore. Give the password and type y when asked trust the certificate.


Started a java app and here comes jvm_bind issue. Use

netstat -a

in command prompt to discover the ports in use and the process ids. Then kill our process to free that port.



 In plain words secure sockets using javax.net.ssl package.

We need secure socket to connect to an ip and port with security. Thus Secure Socket is like a door which we need to go inside apartment whose address is its ip and door number is the port. Now how to we open the door. We need keys.

Certificates are keys which is verified and signed by some authority(Certifying Authority – CA) as good keys.

Now we have more than one key. So we use a keystore. Its like key-rings holding all your keys in one place. KeyStore Class can be used to represent a certificate in java. You upload your keystore made by java keytool into this object.

KeyManagerFactory class does the job of managing your key ring. Give that to your SSLContextClass and from that you can get the SSLSocketFactory. Using SSLSocketFactory we finally get our SSLSocket.

That much code in place the problem of how to trust others keys which they(servers) send to verify themselves while communicating comes up. We will put those keys in another keystore and call it our trust store. Again put the trust store in a KeyStore object and put it a TrustManagerFactory and give it to the context.

Of-course the question how to get keystore and truststore with certificates is still there. Click this link for that.

The folowing method creates a secure socket with client authentication.

public SSLSocket createSecureSocket(String keyStore, String keyStorePwd, String trustStore,
String trustStorePwd) throws IOException {
// create 2 JKS keystores for keystore and truststore
KeyStore clientKeyStore = null;
KeyStore clientTrustStore = null;
try {
clientKeyStore = KeyStore.getInstance( “JKS”);
clientTrustStore = KeyStore.getInstance( “JKS”) ;
} catch (KeyStoreException e) {
e.printStackTrace();
}
//convert keystore pwd into char array and load the client keystore made with keytool into
//one keystore object.
char[] keyStorePwdArray = keyStorePwd.toCharArray();
try {
clientKeyStore.load(new FileInputStream(keyStore), keyStorePwdArray);
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
} catch (CertificateException e1) {
e1.printStackTrace();
}
//convert truststore pwd into char array and load the client truststore made with keytool into
//other keystore object.
char[] trustStorePwdArray = trustStorePwd.toCharArray();
try {
clientTrustStore.load(new FileInputStream(trustStore), trustStorePwdArray);
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
} catch (CertificateException e1) {
e1.printStackTrace();
}
// create the key manager and trust manager factories.
KeyManagerFactory kmf = null;
TrustManagerFactory tmf = null;
try {
kmf = KeyManagerFactory.getInstance( “SunX509″ );
tmf = TrustManagerFactory.getInstance(“SunX509″);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
//load client keystore and pwd to key manager factory.
try {
kmf.init(clientKeyStore, keyStorePwdArray);
} catch (KeyStoreException e1) {
e1.printStackTrace();
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
} catch (UnrecoverableKeyException e1) {
e1.printStackTrace();
}
// load client truststore into trust manager factory.
try {
tmf.init(clientTrustStore);
} catch (KeyStoreException e) {
e.printStackTrace();
}
// create sslcontext object and load both the facotries into it.
SSLContext ctx=null;
try {
ctx = SSLContext.getInstance( “TLS” );
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
try {
ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
} catch (KeyManagementException e) {
e.printStackTrace();
}
// Get our socket factory from context and then get the socket.
SSLSocketFactory factory = ctx.getSocketFactory();
SSLSocket socket = (SSLSocket)factory.createSocket();
return socket;
}

Now we need to open a connection.
socket.connect(new InetSocketAddress(“localhost”, 9999),10000000);
or
SSLSocketFactory sf = sslContext.getSocketFactory();
Socket socket = sf.createSocket(host, port);

To create a server socket use the same method but use servers keystore and truststore.
Get the context object ctx.
SSLServerSocketFactory ssf = ctx.getServerSocketFactory();
ServerSocket ss = ssf.createServerSocket( 6660 );

Note : If you are really bothered by the numerous try catch statements just put the code in one try block and write catch statements at the end. I write really good 
system.out.printlns in catch blocks during the first attempt just to know where I am going wrong. Later I combine them.


When urgently you need some keystores and truststores to test out some security related java code this is a useful bat file to have. Copy the code below and create a bat file. run it and you got your stuff.

keytool -genkey -alias serverkeys -keyalg RSA -keystore server.k
eystore -storepass 123456 -keypass 123456 -dname “CN=localhost, OU=MYOU, O=MYORG, L=MYCITY, ST=M
YSTATE, C=MY”


keytool -export -alias serverkeys -keystore server.keystore -stor
epass 123456 -file server.cer


keytool -genkey -alias clientkeys -keyalg RSA -keystore client.k
eystore -storepass 123456 -keypass 123456 -dname “CN=localhost, OU=MYOU, O=MYORG, L=MYCITY, S=MY
STATE, C=MY”


keytool -export -alias clientkeys -keystore client.keystore -stor
epass 123456 -file client.cer


keytool -import -v -keystore client.truststore -storepass 123456
-file server.cer


keytool -import -v -keystore server.truststore -storepass 123456
-file client.cer

It generates a keystore called server.keystore with password 123456. Then it creates server certificate server.cer.

Then it  generates a keystore called client.keystore with password 123456. Creates a client certificate named client.cer

Next it imports server certificate into client truststore and client certificate into server truststore.

These are self signed certificates. Good for internal use. You can use open ssl
and create certificates. But this bat file is short and sweet for immediate use.
When you paste it you do have to be careful about keywords not getting split up like wordpress does.


This is a video podcast by Paul Duvall and Levent Gurses, discussing Levent’s presentation at the Better Software Conference. JDepend4Eclipse, Checkstyle, Coverlipse, PMD, and Metrics eclipse plugins are discussed.

All  these plugins are for software metrics which will help in code quality.

Checkstyle is a plugin which I have used and found useful. We can
give a xml file based rule (coding std) to the plugin and while writing
code it will highlight the checkstyle errors. This avoided a lot of headaches
when compared to times the code went into the automated build process
and then all your checkstyle errors were highlighted before the world.

JDepend4Eclipse – traverses Java class file directories and generates design metrics for each Java package.

Coverlipse – djunit is another plugin which does the same job of showing your unit test coverage.

PMD – Helps with code duplication.

Metrics – Measures complexity.

The video pod cast I was talking about before

An article and tutorial about the five plugins by ibm developer works :- Automation for the people by Paul Duvall

To download the free plugins use the links below.

http://pmd.sourceforge.net/eclipse/

http://andrei.gmxhome.de/jdepend4eclipse/index.html 

http://coverlipse.sourceforge.net/index.php

http://metrics.sourceforge.net/

http://eclipse-cs.sourceforge.net/