Monday 14 October 2013

How to generate CSR






CSR means Certificate Signing Request. CSR will be generated before giving it to CA authority.
To generate a CSR, you will need to create a key pair for your server. These two items are a digital certificate key pair and cannot be separated. If you lose your public/private key file or your password and generate a new one, your SSL Certificate will no longer match and you will need to replace the certificate.
Step 1: Create a Keystore and Private Key
Please use a recent version of the JDK for best security practices
Download from here.
You have to download jsse for high strength algorithms.

  1. Create a certificate keystore and private key by executing the following command:

    keytool -genkey -alias <your_alias_name> -keyalg RSA -keystore <your_keystore_filename> -keysize 2048
    For example:

  2. Enter and re-enter a keystore password.  Tomcat uses a default password of changeit.  Hit Enter if you want to keep the default
    password. If you use a different password, you will need to specify a custom password in the server.xml configuration file.
     
  3. This command will prompt for the following X.509 attributes of the certificate:




    • First and last name (Common Name (CN)): Enter the domain of your website (i.e. www.myside.org) in the "first- and lastname" field.. It looks like "www.company.com" or "company.com".
    • Organizational Unit (OU): This field is optional; but can be used to help identify certificates registered to an organization. The Organizational Unit (OU) field is the name of the department or organization unit making the request.
    • Organization (O): If your company or department has an &, @, or any other symbol using the shift key in its name, you must spell out the symbol or omit it to enroll.  Example: XY & Z Corporation would be XYZ Corporation  
    • Locality or City (L): The Locality field is the city or town name, for example: Mountain View. 
    • State or Province (S): Spell out the state completely; do not abbreviate the state or province name, for example: California 
    • Country Name (C): Use the two-letter code without punctuation for country, for example: US or CA
      NOTE: Symantec certificates can only be used on Web servers using the Common Name specified during enrollment.
      For example, a certificate for the domain "domain.com" will receive a warning if accessing a site named www.domain.com
      or "secure.domain.com", because "www.domain.com" and "secure.domain.com" are different from "domain.com".
       
  1. When prompted for the password for the private key alias, press Enter.  This will set the private key password to the same password used for the keystore from the previous step.
    Make note of the private key and the keystore password.  If lost they cannot be retrieved.



    For further information, please refer to the Tomcat Web site.
Step 2: Generate a CSR
  1. Run the following command to generate the CSR:

    keytool -certreq -keyalg RSA -alias <your_alias_name> -file certreq.csr -keystore <your_keystore_filename>
    For example:



    NOTE: CSRs generated using the MD5 digest (signature) algorithm are no longer allowed.
    CSRs must be generated using SHA-1 or SHA-256/384/512
    Outdated versions of Java SDK may use the MD5 signature hash under RSA. It is recommended to upgrade to a more recent version of the Java SDK.

    Alternatively, try to specify SHA-1 using the following command:

    keytool -certreq -keyalg RSA -alias <your_alias_name> -file certreq.csr -keystore <your_keystore_filename> -sigalg SHA1withRSAFor example:



     
  2. Verify your CSR
     
  3. Create a copy of the keystore file. Having a back-up file of the keystore at this point can help resolve installation issues that can occur when importing the certificate into the original keystore file.
     
  4. To copy and paste the file certreq.csr into the enrollment form, open the file in a text editor that does not add extra characters (Notepad or Vi are recommended).

    Make sure to include the "BEGIN CERTIFICATE REQUEST" and "END CERTIFICATE REQUEST" header and footer.

    The text file should look like this:

    -----BEGIN CERTIFICATE REQUEST-----

    [encoded data]

    -----END CERTIFICATE REQUEST----- 

Friday 11 October 2013

Socket Server with SSL

Socket Server with SSL
import java.io.FileInputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocketFactory;

public class SocketServerTest{
  public static void main(String args[]) throws Exception {
   
    
    char[] storepass = "testpass".toCharArray();
    char[] keypass = "testpass".toCharArray();
    String storename = "ServerKeystore";

    SSLContext context = SSLContext.getInstance("TLS");
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    FileInputStream fin = new FileInputStream(storename);
    KeyStore  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(9999);
    while (true) 
   {
      Socket s = ss.accept();
      PrintStream out = new PrintStream(s.getOutputStream());
      out.print("Server Data Pushed to Client");
      out.flush();
      out.close();
      s.close();
    }

  }
}
Ref:
http://docs.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#WhySSL

Wednesday 9 October 2013

SSL in java , Java scoket, SSL Socket, Adding SSL to java socket



How to add SSL to Socket in Java

// For trust Store adding to client Side
System.setProperty("javax.net.ssl.trustStore", requestTO.getKeystore());
System.setProperty("javax.net.ssl.trustStorePassword", requestTO.getStorepass());


SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
sssocket = (SSLSocket) sslsocketfactory.createSocket(requestTO.getIpaddress(), new Integer(requestTO.getPort()));
sssocket.startHandshake();
sssocket.setSoTimeout(timeout);
out = new PrintWriter(sssocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(sssocket.getInputStream()));



// For adding on Server Side usngf Apache MINA
/*
* STEP 1: Create a FILE OBJECT
*/
//FILE_PATH = path of Keystore

FilePermission.checkReadFilePermission(FILE_PATH, "JKS");
File clientJKS = new File(FILE_PATH);
/*
* STEP2: Upload file in KeyStoreFactory
*/
final KeyStoreFactory keyStoreFactory = new KeyStoreFactory();
keyStoreFactory.setDataFile(clientJKS);
keyStoreFactory.setPassword(PASSWORD);

/*
* STEP3:GET JKS OBJECT and upload into SSLCONTEXT_FACTORY
*/
final KeyStore keyStore = keyStoreFactory.newInstance();
final SslContextFactory contextFactory = new SslContextFactory();
contextFactory.setKeyManagerFactoryKeyStore(keyStore);
contextFactory.setKeyManagerFactoryKeyStorePassword(PASSWORD);

/*
* STEP 4:RETURN SSLCONTEXT
*/
return contextFactory.newInstance();



If you want to add the SSL Debug mode then
-Djavax.net.debug=ssl:record as vm argument

References:

http://www.javanna.net/2011/07/common-ssl-issues-in-java/

http://docs.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#WhySSL





javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure


========================================================
javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

Issue with the Server Keystore. Server keystore is not generated properly.
We have to follow the process of this link
http://javaresolutions.blogspot.com/2013/10/csr-creation-ca-certiifcate-import-ssl.html

CSR creation, CA certiifcate import, SSL Certificate Import


Steps to Create SSL Certificate:

1. We need to generate the keystore using
keytool -genkey -alias mydomain -keyalg RSA -keystore keystore.jks -keysize 2048

2. Generate the CSR out of this keystore and also export privatekey from the same.
keytool -certreq -alias mydomain -keystore keystore.jks -file mydomain.csr


3. Get the .crt file from Well known CA like VeriSign, Thawte,GoDaddy..etc.
4. Using CA.crt and privatekey from original keystore , we have to generate .pfx or .p12 file using ,
openssl pkcs12 -export -out cert-and-key.p12 -inkey privateKey.key -in CAcertificate.crt

5. Convert your existing CA certificate and private key into a PKCS12 file, and then use the keytool functionality to merge one keystore with another one. Java 6 can treat a PKCS12 file as a keystore, so putting this together, you get this:
keytool -importkeystore -deststorepass changeit -destkeypass changeit -destkeystore final-keystore.jks -srckeystore cert-and-key.p12 -srcstoretype PKCS12 -srcstorepass cert-and-key-password -alias 1
   The alias of 1 is required to choose the certificate in the source PKCS12 file, keytool isn't clever enough to figure out which certificate you want in a store containing one certificate.
 
6.   final-keystore.jks is the final keystore we have to keep in classpath to work.
 

Reference:
http://cunning.sharp.fm/2008/06/importing_private_keys_into_a.html
https://www.sslshopper.com/article-most-common-java-keytool-keystore-commands.html

Saturday 28 September 2013

Android XML Parsing


I have a requirement to read the XML content in Android project.
So googling for long time and people are talking about the JAXB versionof android and XML to POJO utilities etc...but I found that Android itself has own API to read XML content, which is beautiful.

I came across this API which I will give you the example here .
It also has the better implementations of SAX parsers inside the android .

you can go through this :
http://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html
which is from ANDROID SDK exmaples itself.

I don't know when will this be removed or updated from the site or for quick reference I am pasting here.

================

import java.io.IOException;
 import java.io.StringReader;

 import org.xmlpull.v1.XmlPullParser;
 import org.xmlpull.v1.XmlPullParserException;
 import org.xmlpull.v1.XmlPullParserFactory;

 public class SimpleXmlPullApp
 {

     public static void main (String args[])
         throws XmlPullParserException, IOException
     {
         XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
         factory.setNamespaceAware(true);
         XmlPullParser xpp = factory.newPullParser();

         xpp.setInput( new StringReader ( "<foo>Hello World!</foo>" ) );
         int eventType = xpp.getEventType();
         while (eventType != XmlPullParser.END_DOCUMENT) {
          if(eventType == XmlPullParser.START_DOCUMENT) {
              System.out.println("Start document");
          } else if(eventType == XmlPullParser.START_TAG) {
              System.out.println("Start tag "+xpp.getName());
          } else if(eventType == XmlPullParser.END_TAG) {
              System.out.println("End tag "+xpp.getName());
          } else if(eventType == XmlPullParser.TEXT) {
              System.out.println("Text "+xpp.getText());
          }
          eventType = xpp.next();
         }
         System.out.println("End document");
     }
 }
 
The above example will generate the following output:
 Start document
 Start tag foo
 Text Hello World!
 End tag foo
 End document
 

Sunday 19 May 2013

don't know how to handle message of type ' b'. are you missing a protocol encoder



Please write IoBuffer in the Protocol Decoder
in Apache Mina Framework.

If you try to send String/ or any other object it will throw some thing like,
don't know how to handle message of type ' b'. are you missing a protocol encoder

ProtocolEncoderOutput

java.lang.IllegalArgumentException: buf is empty. Forgot to call flip()?


It has two chances possible for this error:
1. Forget to call flip() after put/write into Buffer.
2. If you used wrap() , then no need to call flip().Because wrap() will set position to Zero. it is ready for read from Buffer.



Here are the better articles I suggest:

ByteBuffer
ByteBuffer Tutorial

Please post me here I will help you on this.

Caused by: java.io.IOException: java.io.IOException: error=2, No such file or directory


This will come while executing the cmd/shell from java

might be the problem will be more like
command you are trying to execute will be a problem.

So please put more concentration on arguments you ar passing to application.

I also suggest this Article on this


I also faced same issues like above,
My mistake is
java -jar "Jaraname.jar" classname arg1 arg2

Totally here 3 args, even arg classname is not required for me...which is also trying to pass as an argument and creates the problem.

Jar is Runnable jar file with Manifest generated by eclipse in my case.

Windows / Linux both are same no need to take extra caring for os dependent.

One of the Best Article was from Javaworld.

Please post me for any solutions like this. I will help you with little Charge
:-)



how to make executor as daemon thread




You need to use a new ThreadFactory that creates daemon threads. See this answer here


import these classes:


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;



Add this Class


static class DaemonThreadFactory implements ThreadFactory {
   public Thread newThread(Runnable r) {
       Thread thread = new Thread(r);
       thread.setDaemon(true);
       return thread;
   }
}


Use like this:

private static DaemonThreadFactory dtf = new DaemonThreadFactory();
private static ExecutorService service= Executors.newFixedThreadPool(5, dtf);


If you need any example on this please leave a comment i will reply.



--------------------------------


you can also use Anonumous class like this:

ExecutorService pool = Executors.newSingleThreadExecutor(new ThreadFactory() {
   @Override
   public Thread newThread(Runnable runnable) {
      Thread thread = Executors.defaultThreadFactory().newThread(runnable);
      thread.setDaemon(true);
      return thread;
   }
});



Tuesday 14 May 2013

First Shell Script to Run Java Applications in Solaris


#!/bin/bash
JAVA_HOME=/usr/jdk/jdk1.7.0_07/bin
PATH=$JAVA_HOME/bin:$PATH
export PATH JAVA_HOME


java -classpath .:./config:./lib/1.jar:./lib/2.jar:com.test.run.ClassName

Query that returns list of all Stored Procedures in an MS SQL database


select * from information_schema.routines
where routine_type = 'PROCEDURE'

Friday 10 May 2013

Thursday 9 May 2013

Solaris 11, How to check Java version in Solaris

First time I am using Solaris and i don't even know anything in solaris 11.
Solaris 11 commands
admin@solaris:/$ java -version
java version "1.7.0_07"
Java(TM) SE Runtime Environment (build 1.7.0_07-b10)
Java HotSpot(TM) Client VM (build 23.3-b01, mixed mode)

By default Solaris have jdk latest version.

Wednesday 30 January 2013

Locks & Conditions in Java 5 or 6


We have the some ways to communicate in between threads.
All of usknow that  "wait" and "notify", which is a traditional method of communicating.

With the introduction of Locks and Condition , we have better performance and control .

It was already proved  that Locks and Conditions are more throughput than Synchronized blocks.

Here I will try to explain the simple producer - consumer problem without  Locks and Condition.




package org.ohms.threads.locks;

import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 
 * Producer Consumer Problem...Solved with Locks
 * 
 * @author
 *
 */
public class PCproblemWithLocks {

 private static int storedBox=-1;;

 public static void main(String[] args) throws InterruptedException {
  
  int totalProduction=1000;
  Lock lock=new ReentrantLock();
  Condition condition= lock.newCondition();
  
  
  Buffer buffer= new Buffer();
  Thread producer= new Thread(new Producer(totalProduction, buffer,lock,condition));
  Thread consumer= new Thread(new Consumer(totalProduction, buffer,lock,condition));
  
  System.out.println("=====================================");
  
  producer.start();
  consumer.start();
  
  producer.join();
  consumer.join();
  
  System.out.println("Completed .....");
 }
 
 
 
 /**
  * used to store the values or a common 
  * object where two threads used.
  * 
  * @author
  *
  */
 static class Buffer {

  void put(int newValue) 
  {
   storedBox = newValue;
  }

  int get() 
  {
   return storedBox;
  }
  
   void clear() {
    storedBox=-1;
  }
  
 }

 /**
  * Used to store the Value
  * in the StoredBox(int variable defined above) 
  * 
  * @author
  *
  */
 static class Producer implements Runnable 
 {
  
  private int counter;
  private Buffer buffer;
  private Lock lock;
  private Condition condition;
  
  public Producer(int count,Buffer buffer,Lock lock,Condition condition) 
  {
   this.counter=count;
   this.buffer=buffer;
   this.lock=lock;
   this.condition=condition;
   System.out.println("Producer Started placing the Values");
  }

  @Override
  public void run() 
  {
   try {
   this.lock.lock();
   System.out.println(" Producer Lock Acquired ");
    for (int i = 0; i < this.counter; i++) 
    {

     if(this.buffer.get()!=-1)
     {
      //System.out.println("Waiting to put>>>>>>");
      condition.await();
      System.out.println(" Producer Lock Acquired ");
     }
     
     int randomValue=i;//new Random().nextInt(100);
     this.buffer.put(randomValue);
     System.out.println("Produced -->"+randomValue);
     condition.signalAll();
     System.out.println(" Producer Lock Released ");
     
    }
   } catch (InterruptedException e) {
    e.printStackTrace();
   }finally{
    this.lock.unlock();
   }
   
  }

 }

 /**
  * used to retrieve/read the stored value
  * in the StoredValue Box
  * 
  * @author Kumar
  *
  */
 static class Consumer implements Runnable {

  private int counter;
  private Buffer buffer;
  private Lock lock;
  private Condition condition;
  
  public Consumer(int count,Buffer buffer,Lock lock,Condition condition) {
   this.counter=count;
   this.buffer=buffer;
   this.lock=lock;
   this.condition=condition;
   System.out.println("Consumer started Reading the Values ");
  }

  @Override
  public void run() 
  {
   this.lock.lock();
    System.out.println(" Consumer Lock Acquired ");
   try {
   for (int i = 0; i < this.counter; i++) 
   {
    if(this.buffer.get()==-1)
    {
     //System.out.println("Waiting to get <<<<<<<<<<");
     condition.await();
     System.out.println(" Consumer Lock Acquired ");
    }
    
    System.out.println("Consumed -->"+this.buffer.get());
    this.buffer.clear();
    condition.signalAll();
    System.out.println(" Consumer Lock Released ");
   }

   } catch (InterruptedException e) {
    e.printStackTrace();
   }finally{
    this.lock.unlock();
   }
   
  }

 }

}



 run the above program to know the usage of the Locks and condition in java .