14 May 2013

How To Create A SSL ServerSocket On Android

On Android to create a Successful SSL Server Socket First you need to create a keystore using "keytool" that comes with jdk. We need to run this tool with the option of  "storetype BKS". BKS stands for Bouncy Castle. Androids default keystore type is BKS. But the jdk that comes from oracle site does not have this security provider. So first we need to download the jar which has this provider files. This can be downloaded from  http://repo2.maven.org/maven2/org/bouncycastle/bcprov-ext-jdk15on/1.46/bcprov-ext-jdk15on-1.46.jar 

After downloading this jar file place this jar file in "jre/lib/ext". After placing the jar file you need to modify the  "java.security" file under "jre/lib/security" folder. Open the "java.security" file and add the following entry without quotes "security.provider.7=org.bouncycastle.jce.provider.BouncyCastleProvider". 

After all this now we need to generate a keystore using keytool. To generate the keystore run the following command without quotes. 
"keytool -genkey -keystore ServerKeystore -storetype BKS -provider org.bouncycastle.jce.provider.BouncyCastleProvider".


If you run the above command then it generates an error saying that "java.security.InvalidKeyException:illegal Key Size".  To avoid this, download "jce policy files" from oracle site. For suppose if you are using jdk6 then you can download the "jcp policy files" from http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html 

After downloading this zip file extract the contents into a directory and copy the "local_policy.jar" and "US_export_policy.jar" from the extracted directory and paste them in "jre/lib/security" folder(these files already may exist but you need to replace them). 

After all this open the command prompt and run the keytool as stated above. This generates the keystore which can be used in Android. Copy this keystore file into one of your project directory. 

After all the above the following is the code to successfully create a SSLServerSocket.

try{                
      String keyStoreType = KeyStore.getDefaultType();
      KeyStore keyStore = KeyStore.getInstance(keyStoreType);
      keyStore.load(Dummy.class.getResourceAsStream("ServerKeystore"), "12345".toCharArray());                

      String keyalg=KeyManagerFactory.getDefaultAlgorithm();
      KeyManagerFactory kmf=KeyManagerFactory.getInstance(keyalg);
      kmf.init(keyStore, "dhar9654".toCharArray());

      SSLContext context = SSLContext.getInstance("TLS");
      context.init(MainActivity.kmf.getKeyManagers(), null, null);          
      SSLServerSocket ss=(SSLServerSocket)context.getServerSocketFactory().createServerSocket(Constants.CHAT_SERVER_PORT);

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

Hope this helps.  I have struggled a lot to find this. So thought to document. 

No comments: