Thursday, September 29, 2011

Configuring SSL in tomcat

What is SSL?
SSL or Secure Socket Layer is a technology which allows web browsers and web servers to communicate over a secured connection. The data being sent is encrypted by one side, transmitted, then decrypted by the other side before any further processing. Essentially, it is a two way process, Browser encrypts its requests before sending them to the server and server decrypts them then server encrypts the response and the browser decrypts it.

There is one more thing we should understand about SSL is certificates used for Authentication. When the Browser places the first request to a web server over a secure connection, that server will respond to your web browser with two things, one is your page (for example ICICI Loginpage,CitiBank login page) and other is a set of credentials, in the form of a Certificate; This certificate gives information to the browser about the authenticity of the website.

Certificates and SSL
In order to implement SSL, a web server must have an associated certificate for each external IP address that accepts secure connections. Certificate acts as a identity proof for the website like your passport for you. This certificate is signed by the issuer (you can also create your self-signed certificates as well, but do not use them in production). Issuer is normally a well recognized authority like VeriSign, Thawte, Go Daddy, etc.

Why shouldn't you use Self-signed certificates?
Hackers normally utilize the weakness of your certificate to attack and the weakness is that it is self-signed. The attack might happen, something like this, when the client attempts to connect to the server the hacker hijacks the connection(means that now your requests will go to the hacker not the server). He then sends the client his own self-signed certificate(seeing which you feel happy and say, wow, now I can fill my credit card info without any prob.) which has the same name as the one present in the server's self-signed certificate. The hacker then connects to the real server himself. When the client sends data to the server the attacker reads it(might change it as well) and then sends it along to the real server. So, your credit card information might get leaked.
Let us start with tomcat:
  1. You need to create a keystore file to store the private key of the server using the following command.
    Windows:

    Unix:

    Same is shown below:
    The file will get created under the directory from which you are running the command, for example, as shown in image, the file will get created under following path: C:\Users\dharmvir.singh

    To specify a different location to store the keystore file(keystore in the last of the path), just modify the above command as shown below:
    Windows:

    same way you can do in unix.
    Sample is shown below:
    Password used in both the example screens shots is "changeit" as it is the default password for tomcat.
    The certificate can be obtained from authorities like Verisign and others.
  2. Uncomment the following section from $CATALINA_HOME/conf/server.xml:
    
    
    $Catalina_Home here represents path of your tomcat home folder
To test it I created a sample TestServer app (I have attached tomcat with that application to download). Here is how it will look like on accessing it on localhost.
Tips on SSL:
  1. SSL has encryption/decryption which is expensive so do not configure entire application on SSL. For example, Website home, adds, banners pages, sitemap page, about us page might not be put on SSL.
  2. using name-based virtual hosts on a secured connection can be problematic. This is a limitation of SSL protocol. So you can use only one certificate for one IP address.

Apache-Troubleshooting SSL in tomcat

tomcat with SSL enabled can be downloaded from here, It contains the TestServer App as well, so just download and start the server and test it.

Relevant References

Note from Author: Please leave appreciation comment, if you like the article or else please leave your questions, suggestions or feedback.
Thanks,
java-espresso

Wednesday, September 28, 2011

JAVA BASICS.. JAVA A DIFFERENT APPROACH TO START.. JAVA PLATFORM INDEPENDENT. HOW JAVA IS PORTABLE?


Must read for a good start of JAVA

All of us know that JAVA is portable i.e JAVA is platform independent.Let us try to figure out the reason how Java is platform independent. Java has used a slogan Write Once Run anywhere.

Explanation:
Some language generate .obj or .exe file after compiling. These generated file will not work in other Operating system. There was a need to have something which will not depend on operating system. Hence they came with new concept of JAVA VIRTUAL MACHINE(JVM). Running a java program was divided into 2 parts. First part makes .class file and in the second part this .class file will be run on JVM.
For the generation of .class file from .java file,compiler was written which will always generate the same .class file for any of the operating systems. Half of the work is over for getting platform independency.

.java ----Compile---->.class(Byte Code)---Interpreter(Platform Dependent)--->machineCode


For running the same .class file in different OS, they made a difference in JVM for different operating system. JVM depends on the hardware and OS architecture. It will take .class file as input and interpret it. So for the same .class file it will generate the same output. It is the difference in JVM which has made java a platform independent language.

Now in the next post we will learn basics of java taking memory into consideration.

Friday, September 23, 2011

web.xml servlet Understanding <url-pattern>/*</url-pattern>

Understanding the <url-pattern>/*</url-pattern>

Other Questions of similar pattern:
1) How to exclude from url-pattern in servlet mapping?
2) To exclude content from url-pattern

While developing web.xml in application, do take care of the <url-pattern>.
Try not to give a generic url-pattern ie., <url-pattern>/*</url-pattern>.The disadvantage of this URL Pattern is, any request coming to the server will fall in this URL PATTERN(except for those you have explicitly defined). Suppose browser is requesting a page which has images,css,etc then you will find page will load with the servlet response,while the images,css,js,etc are not getting loaded and it will be very difficult to find the reason for this type of behaviour.

The reason is as:-
Our browser requests in the following steps
Step1: The browser requests the page and gets back the response which contains all other path.
Step2: The browser again requests all the other path to the server and these path contains the images,css,etc

What happens in our problem is in step 2,the browser's request goes to the server and now the images,etc also falls in the <url-pattern >/*</url-pattern>,which redirects to a servlet and this is the problem. This is the reason why we don't get images and other files in our web page.

Let us solve this with the help of example:
web.xml

 TestUrlPattern
 
   ServletDefault
   com.test.ServletDefault
   
  
    ServletDefault
    /*
  
  
  abcd
  /abc.jsp
  
  
   abcd
    /abc.jsp
  


abc.jsp
<html>
<head>
<title>TestUrlPattern</title>
</head>
<body>
Sample text
<img src="Desert.jpg" >
</body>
</html>


Whenever a request comes as localhost:8080/TestApp/abc.jsp, the abc.jsp loads and images are not getting loaded. The images goes to the SevletDefault mapping. You can see this by printing any text in doGet or doPost method of ServletDefault class.
Reason is,all files other than abc.jsp will go to ServletDefault.

Solution for /* type pattern in web.xml

I found two approaches to solve this problem
Approach 1:

Make a common servlet which consumes all the files which have the pattern for images,css,javascript,etc
web.xml  (modified)

  TestUrlPattern
  
      CommonServlet
      com.test.CommonServlet
    
  
      Servlet
      com.test.Servlet
    
    
        Servlet
        /*
    
    
    abcd
    /abc.jsp
  
    
    
      abcd
        /abc.jsp
    
        
        CommonServlet
        /images/
    
    
        CommonServlet
        /stylesheet.css
    
    
        CommonServlet
        /javascript.js
      


Keep the images in the 'images' folder. For a new request to the servlet, you will find,all the images,css,js requests goes to CommonServlet. Write a CommonServlet which retuns back the file itself in the response.

CommonServlet.java

public class CommonServlet extends HttpServlet  {
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  ServletContext sc = getServletContext();
  String path=req.getRequestURI().substring(req.getContextPath().length()+1, req.getRequestURI().length());
     String filename = sc.getRealPath(path);

     // Get the MIME type of the image
     String mimeType = sc.getMimeType(filename);
     if (mimeType == null) {
         sc.log("Could not get MIME type of "+filename);
         resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
         return;
     }
     // Set content type
     resp.setContentType(mimeType);

     // Set content size
     File file = new File(filename);
     resp.setContentLength((int)file.length());

     // Open the file and output streams
     FileInputStream in = new FileInputStream(file);
     OutputStream out = resp.getOutputStream();

     // Copy the contents of the file to the output stream
     byte[] buf = new byte[1024];
     int count = 0;
     while ((count = in.read(buf)) >= 0) {
         out.write(buf, 0, count);
     }
     in.close();
     out.close();
 }
}

The above servlet write the contents of file in the response and our problem is solved.

Approach 2:

This approach sets the context in jboss server.xml file.
server.xml is found at Jboss_home\server\default\deploy\jboss-web.deployer path.
Open server.xml in edit mode
Add the context in server.xml.
Find text similar to the following code in server.xml
<Host name="localhost" autoDeploy="false" deployOnStartup="false" deployXML="false"configClass="org.jboss.web.tomcat.security.config.JBossContextConfig" >
Below the above code add the context as:



set docBase,path according to your path.This will solve your problem.

These were the two approaches which i found out for this problem. Please let me know if you know any more approach.

4.JAVA BASICS.. IS JAVA A PURE OBJECT ORIENTED LANGUAGE..PROBLEM SOLVING.


As you all know java is a pure Object Oriented language.
Is java Really a pure Object Oriented Language?

The answer is NO..Java is not a pure object oriented language.
1)The main reason for this is it does not always deal with objects.
int,char,float,etc are not in the form of objects and java uses them. So this is the main reason why java is not object oriented language.
2)The other reason is that java does not support Multiple inheritance in case of classes,but a pure object oriented language supports multiple inheritance.

Now let us see some of the basic thing in java which is to be noted. Those who already know java can skip this.

What is the default value of Byte?
Ans: NULL

Now a question may arise in your mind,that the default value of byte is false.Your question is correct.
If you observe clearly,then you will find that default value of Byte is asked not byte.And Byte is a class that means it will store reference. Remember in the first java basic, i told to see the data types start with lower case.

Point to be remembered: In java a class is always declared with first letter as Upper case letter(This is not a rule but it is a best practice so that you never make mistake).

Similarly you will find some more class which may confuse you like Boolean with boolean ,Float with float,Double with double. So don't get confuse with these classes.

 Now a question may arise in your mind that why they have made these confusing classes.What is the use of these classes.Your question is correct,following is the explanations for this.

Sometimes we need objects of these primitive data types,for this Java has made WRAPPER CLASSES for these primitive data types. All the primitive data types have Wrapper Class. Now by using these Wrapper classes,we can convert these data types to Objects and can use them.
Following are the wrapper classes of the primitive data types
1)int    --> Integer
2)byte   -->Byte
3)short   ---> Short
4)char    --->Character
5)boolean  --> Boolean
6)float    --->Float
7)double   --->Double
8)long     --->Long
9)void    ---> Void

Compilation of program:
The java compiler search for a particular signature in the main function.
The signature is
public static void main(String[] args)
This is the signature,that should exist in a program to run ,otherwise it will not run.

Example for the above concept
Class A
{
public static void main(String[] args)
{
     main('x');
     System.out.println("my string");
}
public static void main(char b)
{
     System.out.println(b);
}
}

Output: x
            my string

Reason: It will only treat the first main method as the main method as it is having proper signature and treats 2nd method like a normal java method.

Example2:Count how many objects are created and how many references exist:

Eg:
Customer a=new Customer();
Customer b=new Customer();
Customer c=a;
Customer d= b;
new Customer();

Ans: 3 Objects 4 references

In these types of questions just count the number of new keywords that will give you the number of objects.
and count the number of references by the class name count and in some examples please make the heap and object diagram which we made earlier and then there will be no mistakes.

In next we will learn the concept of static in java..So keep reading...

3.JAVA BASICS.. CLASS AND OBJECTS WITH APPROACH OF MEMORY

What is a class?
We can say class is a template of an object. Objects exists in memory. Class is just a way to define a structure of object.

Now we start with discussion of memory.
Four segments of memory
1)Data segment
2)Code segment
3)Stack segment
4)Heap segment

In C we have seen the use of code and data segment. But in java we will be dealing with Stack Segment and Heap Segment.

See the example below

When we write using new keyword, a new object is created and new Customer() returns the hashcode of the created object. The variable used to store the hash code value is called reference variable.It is called reference because it has the hash code value,which refers to an object.

In short we can say that obj(the variable used above) stores the hash code,where hash code is not the actual address(it is changed to hash code by some hash algorithm). Java does not deal with direct memory,it deals with hash code and the hash code  indirectly refers to a memory. This is the reason why java is called secure. Unlike C,it has no pointers or depointers which can take you to the actual memory address.

Suggestions: 
When ever dealing with output problems,always make a heap by making a square and see the code for how many objects are there. Count and make that many ovals inside the square and point these objects by an arrow of reference. I assure you by using this method,you will not make any mistakes. Example is below

Now an important note,to be always kept in mind and will solve all your problems.
         Local Variables   ------->  STACK
         Global Variables  ------->   HEAP
Keep the above note always in your mind and there will never be a chance of mistake.Here global refers to be a part of class definition.
Stack Variables do not have any default value
Heap variables have default value. If there is any variable in Stack and you try to use that variable without initialization then it will result in a compile time error.
All the objects which are created using new keyword,goes to heap memory,while the location of these references depends,whether they are local or global.
    Take a simple example::
  Sample sample=new Sample();
Here the object of class Sample will always be in heap memory,while the reference(sample here)  location depends on whether it is declared locally or global. We can say that if sample is inside a method then it will be in stack,and if it is inside a class(but outside methods) then it will be stored in heap memory.

Default values of all the variables(only Heap Variables)
int       ---> 0
byte     --->0
short    --->0
boolean -->false
long    ---->0
float     ---->0.0f
double  ---->0.0
char     ----->'\0'
Reference Variable   ---> NULL

NOTE: From above,keep in mind,all variables  keep 0 as the default value.. false(boolean) can be related with 0,NULL can be related with 0,'\0' can be related with 0. Keep in mind a default value of 0.

By seeing any class you can relate the variables with stack and heap.

We will do some examples and then proceed
Class Sample{
int a;                //   Global Variable =>heap              
void printVariable()
{
int b;               //     Local Variable => Stack                 
System.out.println(a);
System.out.println(b);                         ///Error
}
}

Why Error?
The reason is that b is a local variable. We are trying to use a local variable,which is not initialized,and stack variable don't have  default value so it gives error. 
Comparison with C language: In C also,global variables prints 0 while the local variable gives Garbage Value.
Java does not want to have these garbage values because that will make your code buggy,so Java compiler is checking for this at compile time only and thus ,doesn't allow the code to compile.

Example 2:
Class Sample{
Test obj;            //   suppose Test is another class
int a;
void printVariables()
{
System.out.println("value of a is:"+a);
System.out.println("value of reference:"+obj);
}
}
Ans: As we can see that both are global variables,means both use heap memory.
None of them is initialized,so default value is printed.
    value of a is: 0
    value of reference: NULL

Example 3:
class Sample{
void printArea()
{
 int a;
int b=1;
if(b==1)
{
a=10;
}
System.out.println(a);
}
Ans: Compile Time Error
Now the question that come in your mind, the local variable is initialized before using,then why it gives compile time error.
Reason: Even though you have initialized the variable,but at compile time, the compiler does not know in advance if it will enter the loop or not at run time. If suppose,at run time it does not enter the loop and the variable will not get initialized. To avoid these type of situations at run time,java is designed such a way,if a variable is not initialized and gets initialized in inner loops,it does not matter. So if any variable is initialized in inner loop but not in the loop where it is declared,and we use the variable in the declaration loop,the code will not compile.

2. JAVA BASICS..JAVA PRIMITIVE DATA TYPES.. A CORRECT WAY TO START JAVA


There are 8 primitive java data type

We will write the java data types in increasing order of their size (in bytes).

boolean<byte<short ,char <int,float<long,double
    (1)        (1)        (2)            (4)            (8)

 Please notice, all data type start with a lowercase letter.
We will derive the possible values of these data types,according to the size of data type.

byte: memory =1byte=8 bits
 1(signed bit)   1    1    1    1    1    1    1  
                                           7       6    5     4     3     2    1   0
Our computer store numbers in 2's complement format.

Calculating the max value.
Signed bit=0 for positive number.Below is the format shown


 0(signed bit)   1    1    1    1    1    1    1  
                                           7       6    5     4     3     2    1   0

max value :
 (0*27)+26+25+24+23+22+21+20
       => 127
       => 27-1

Min value:
Taking the signed bit as 1, i.e negative number. For getting lowest -ve we make all other bits to 0
Below is the format shown

 1(signed bit)   0    0    0    0    0    0    0  
                                           7       6    5     4     3     2    1   0

Calculated value is     (-27)
    => -128

The range of byte  as derived is: -27 to (27-1)      OR  -128 to 127

Analyse the above in powers of 2. You will find that for 8 bits it comes to power 7.

short:
  size=2 bytes= 16 bits

 1(signed bit)   1    1    1    1    1    1    1    1    1    1    1    1    1    1    1  
       15             14  13   12  11   10   9    8     7    6     5    4     3    2     1     0

max value:

 0(signed bit)   1    1    1    1    1    1    1    1    1    1    1    1    1    1    1  
      15             14  13   12  11   10   9    8     7    6     5    4     3    2     1     0

Calculated value:
      =>        20+21+22+.............+214 {Geometric progression formulla a(rn+1-1)/(r-1)}
here a=1,r=2,n=14
     => 1+21+22+......214
     => (215-1)

Min Value:
 1(signed bit)   0    0    0    0    0    0    0    0    0    0    0    0    0    0    0  
       15             14  13   12  11   10   9    8     7    6     5    4     3    2     1     0

calculated value:   -215

Range: -215 to (215-1)      OR -32768 to 32767

Here 2 bytes=16bits -----> Range in power of 15

char:
Don't consider the signed bit here as characters cannot be -ve.
Java follows unicode characters,and cannot be placed in 1 byte as 1 byte can contain a max of 255 chars.

max value:

 1   1    1    1    1    1    1    1    1    1    1    1    1    1    1    1  
           15   14  13   12   11  10   9    8     7    6     5    4     3    2     1     0
All 1's
   => 20 +21+......+215
   => (216-1)
   => 65535


Min Value:  all 0's
    => 0
Range: 0 to 65535

We can say,char supports a max of 65535 characters.

int:
 4 bytes=32 bits
See the above derivation for short,byte and you will be able to write the range of integers.
The range comes  -231 to (231-1)

long:
8 bytes=64 bits
Range:   -263  to (263-1)

From the above discussion,it is clear,we don't have to learn these ranges,just calculate the number of bits and you will be able to write the range directly without any calculation.

float(Calculation for float range)
It follows IEEE 754 standard.
According to which 1 bit is fixed for sign. 23 for Mantissa and 8 bits for Exponent


 1(signed bit){s}  <------23 bits(Mantissa)--------> {M}   <----8 bits(Exponent)--->{E}  

Formula for Calculation of Value is:
         =>  (-1)s * M* BE
where base B is fix by designer.

Mantissa is assumed to be in decimal i.e its value start from 1.{caculated value}
M=1.{calculated Mantissa value}

Assume,all mantissa bits to be 1:
Calculated value is:   2-1+2-2+.....+2-23  = 1-2-23=    0.999999880790071044921
Mantissa is: 1.999999880790071044921
Exponent is stored in excess 127 format. E is 8 bits. No signed bit in exponent,calculated range is 0 to 255.
Actual range is calculated by subtracting 127 from stored exponent value. Values 0,255 are fixed for special purpose. As M=1.{some value}, it can never be 0, and also the number cannot be 0. For this reason 0,255 were fixed for special purpose, which otherwise are not possible. Following are the special cases.
a) If M=0,E=0    => Number is 0
b) If  M=0, E=255   => Number is +ve Infinity
c) If M={any value} ,E=0 => Number is -ve Infinity
d) If M={any value}, E=255  => NaN(Not a Number)
Actual range of Exponent(subtracting 127 and not taking special case value): -126 to 127

Max Value(positive)= 1.999999880790071044921 * 2 127
=>3.40282346638528860e+38  (calculated  from calculator)

Min Value  : -ve of Max Value

Float range : (-1.999999880790071044921 * 2 127)    to 1.999999880790071044921 * 2 127
OR  -3.40282346638528860e+38    to     3.40282346638528860e+38

Minimum positive value= 1* M * 2 -126
 => 1.75494e-38 (M=1 for making it the smallest possible positive number,which means all the mantissa bits are 0)

The positive values range from 1.75494e-38 to 3.40282346638528860e+38
Range Magnitude Minimum(Denormalized) 
  { Here,they take min value as 2E(min)-no. of mantissa digits}
=1* 2-126-23
=>  2-149
=> 1.4012 e -45


We can say that min positive number is 1.4012 e -45.
Positive number range is 1.4012 e -45  to   3.40282346638528860e+38     -->(1)
Similarly maximum -ve number possible is (-1.4012 e -45)
Similarly,-ve number range is (-3.40282346638528860e+38) to (-1.4012 e -45)      --->(2)

The derivations (1) and (2) are the ranges which you will find in text books.This denotes the minimum possible positive number and also the minimum possible difference between 2 numbers. Similarly we can calculate the maximum possible difference by calculating the difference between the largest possible number and the 2nd highest possible number.

double:
8bytes=64 bits
Mantissa - 52 bits
Signed -1 bit
Exponent- 11 bits

Same as the above method,we can calculate the positive and negative range for double.
I have not calculated,i am writing the book range
 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative).
But the method is similar.
Please calculate once.


TYPE CONVERSION
Now think type conversion in simple terms.
If we try to save information from more number of bits space to a smaller number of bits space. 
Is this possible?? Ask the question to yourself.
Not satisfied.
Try to save 111111111111111 in 8 bits. It is obvious that some bits will be lost.
Think the other way around try to save 8 bits in 16 bits. It is easily possible without loss of information.

To avoid this problem the java designers thought,the loss of information should not happen. They fixed ,you cannot convert from higher to lower but lower to higher is allowed.
But in explicit it is possible to convert from higher to lower,which means that you agree for loss of information.

Below you find the lowest to highest (one way)
byte<short,char<int<long<float<double.

You will find that  long(8 bytes) and float(4 bytes).
Now you will ask how is it possible.
See the highest value possible for long which is (263-1) while the highest possible value for float which is 1.999999880790071044921 * 2 127 
which is much more than max possible value of long. There will be loss of precision but the value can be stored in that.
This is how the type conversion works.

EXAMPLES
Now we will see few examples and try to learn the type casting.
=> In java,default decimal values are treated as double.

1)int a=10.1;

The above code will give Compile time error.. Why??
RHS is of type double and LHS is of type int. So we are trying to save big in a small one.Is it possible?
No Bigger data type to  smaller data type is not possible.

2) float b=7.2

The above code will give Compile time error.. Why??
RHS is double and LHS is float. Bigger data type to  smaller data type is not possible.

3) byte b=10,c=20;
byte d=b+c;

The above code will give Compile time error.. Why??
The reason behind this is that the arithmetic calculations are treated as integers in java.
So b+c is an integer and this integer value we are saving in byte which is not possible
so correct way is byte d=(byte)(b+c)


Eclipse connection through proxy server for update

Most of the companies have proxy server in between internet and your computer.For update we need connect to internet but the proxy server requires authentication for that. And we are not able to connect to internet through Eclipse.

Solution to the problem.

Step 1)If you know the proxy server name and port number then go to step 2. If you don't know the proxy settings then open internet Explorer.Go to tools->Internet Options->Connections(Tab)->LAN settingsYou will see something as follows




Out of three check boxes may be only one is checked.
Find the check box which is checked
a) If the first check box is checked then there is no proxy required
b) If the second is checked copy the URL for "pac" file and open in a browser and download it and then open it. There may be many servers with ports defined in the file. You can choose any one. I chose the last one with IP address and port number. This is how you will get proxy server and port number
c) If the third is checked then you can directly take Address as proxy Server and port as port number.
In above image for example you can see the proxy server as sample/gate.net and port as 100

In this  step you get proxy server and port number.

Step 2: Open the Eclipse 
a) Go to Window->Preferences
b) Go to General tab -> Network Connections
 After this you may find one of the following screens depending on the version of Eclipse
Screen 1
Screen 2

i)Screen 1:  From the Active provider drop down Select "manual" then you will find 3 Check boxes as shown in screen 1 automatically gets checked. Now Double click on any of the checked Check Boxes a new small window will open where you will be prompted to enter Host, port, Username and password. 
In the host Text Field enter the proxy server name which we got in step 1 and also enter the port number.
In the username and password enter the user name and password you got from your company(it may be same as your desktop password). Repeat this for all three check boxes and click apply and then Ok.
So now you are done with proxy setting in eclipse.

ii) Screen 2: Click on Radio Button Manual proxy Configuration. You can directly see to enter the Http proxy,SSL proxy,SOCKS proxy. So enter here the proxy server and port number. Below you will find to enter User Name and password. Enter the desired user name and password and you are finish with the work.Click Apply and Ok

Now you can directly update the Eclipse with your proxy server also.
Please feel free to tell if there is anything wrong in this blog or any update is needed.

Wednesday, September 21, 2011

DES algorithm Code in Java

Introduction of DES
The Data Encryption Standard (DES) is a symmetric-key algorithm that uses a 56-bit key.Symmetric-key encryption means it uses same key to cipher and decipher the message. DES was developed in IBM under the name of LUCIFER. DES is now considered to be insecure for many applications(especially Govt., defense). For applications demanding more security of the content, Triple-DES can be used.

Coding DES in Java
Code listing below contains the Cryptography class which has both encryption and decryption method.
import java.io.IOException;
import java.security.InvalidKeyException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * @author dharmvir.singh 
 * The class demonstrates the DES algorithm by using java
 * crypto API
 */
public class Cryptography {
 private static final String CRYPTOGRAPHY_ALGO_DES = "DES";
 private static Cipher cipher = null;
 private static DESKeySpec keySpec = null;
 private static SecretKeyFactory keyFactory = null;
 
 public static String encrypt(String inputString, String commonKey)
   throws InvalidKeyException, IllegalBlockSizeException,
   BadPaddingException {
  String encryptedValue = null;
  SecretKey key = getSecretKey(commonKey);
  cipher.init(Cipher.ENCRYPT_MODE, key);
  byte[] inputBytes = inputString.getBytes();
  byte[] outputBytes = cipher.doFinal(inputBytes);
  encryptedValue = new BASE64Encoder().encode(outputBytes);
  return encryptedValue;
 }
 public static String decrypt(String encryptedString, String commonKey)
   throws InvalidKeyException, IllegalBlockSizeException,
   BadPaddingException, IOException {
  String decryptedValue = "";
// When Base64Encoded strings are passed in URLs, '+' character gets converted to space and so we need to reconvert the space to '+' and since encoded string cannot have space in it so we are completely safe.
  encryptedString = encryptedString.replace(' ', '+');
  SecretKey key = getSecretKey(commonKey);
  cipher.init(Cipher.DECRYPT_MODE, key);
  byte[] recoveredBytes = cipher.doFinal(new BASE64Decoder()
    .decodeBuffer(encryptedString));
  decryptedValue = new String(recoveredBytes);
  return decryptedValue;
 }
 private static SecretKey getSecretKey(String secretPassword) {
  SecretKey key = null;
  try {
   cipher = Cipher.getInstance(CRYPTOGRAPHY_ALGO_DES);
   keySpec = new DESKeySpec(secretPassword.getBytes("UTF8"));
   keyFactory = SecretKeyFactory.getInstance(CRYPTOGRAPHY_ALGO_DES);
   key = keyFactory.generateSecret(keySpec);
  } catch (Exception e) {
   e.printStackTrace();
   System.out.println("Error in generating the secret Key");
  }
  return key;
 }
}

Download
Code can be downloaded from here
Download contains:
  1. Cryptography.java: Contains the encrption and decryption method
  2. TestCrypto.java

Related Articles
Implementing MD5 in java

Relevant References
DES explained
Wiki Links:
DES, Symmetric-key algorithm, Triple-DES

Wednesday, September 14, 2011

MD5 encryption in Java

What is MD5?
MD5(Message-Digest algorithm 5)is hashing function which results in 128 bit(16 byte) hash value. It came as a replacement of MD4 which was considered insecure then. MD5 is one way encryption technique means once I have encrypted some text using MD5 I cannot get the clear text from the hash value again. But now it is proved that even MD5 is vulnerable.

Where can we use MD5?
MD5 can primarily be used for encryption and for checking file integrity. But again remember it is possible to have two big different files having same hash value.
Usage examples:
  1. Data Encryption:You can use it to encrypt your passwords something like getMD5Hash(password+date+time of registration)= 'hashed value'. Here we have concatenated actual passwords with date and time of registration to ensure that every time a unique hash value gets generated.
  2. File integrity: Suppose you want to make a file comparing utility. So if you will go straight away and compare the files it will not efficient. So first we can compare size, then HASH VALUE OF BOTH FILES(by using MD5 hashing) and if both are same then probably you can compare the actual text in the files.

Implementing MD5 in Java:
MD5 is already implemented in java. So we just need to reuse the method and do some pre and post processing. MD5 hashing technique always produces a fixed length encrypted string having 128 bits or 16 bytes and so you will always get a hexadecimal string of length 16.
Code listing is given below:
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;

/**
 * @author dharmvir.singh
 * @Description: This class generated the hash code of few strings
 * 
 */
public class TestMD5 {
 public static void main(String[] args) {
  String[] inputStrings = { "Open Source", "Apache project",
    "java espresso" };
  System.out.println("String\t\t\tHash Value\t\tHash val length");
  System.out.println("======\t\t\t==========\t\t===============");
  for (int i = 0; i < inputStrings.length; i++) {
   System.out.println(inputStrings[i] + "\t\t"
     + getMD5HashVal(inputStrings[i]));
  }
 }

 public static String getMD5HashVal(String strToBeEncrypted) {
  String encryptedString = null;
  byte[] bytesToBeEncrypted;
  try {
   // convert string to bytes using a encoding scheme
   bytesToBeEncrypted = strToBeEncrypted.getBytes("UTF-8");
   MessageDigest md = MessageDigest.getInstance("MD5");
   byte[] theDigest = md.digest(bytesToBeEncrypted);
                        // convert each byte to a hexadecimal digit
   Formatter formatter = new Formatter();
   for (byte b : theDigest) {
    formatter.format("%02x", b);
   }
   encryptedString = formatter.toString().toLowerCase();

  } catch (UnsupportedEncodingException e) {
   e.printStackTrace();
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  }
  return encryptedString;
 }
}
The code is self explanatory and I tested it already. For production purposes, avoid using MD5 as encryption technique for banking domain and (security concerned) domains.
Related Articles
Implementing DES in Java

Relevant References JBuilder Professional: Pure Java Visual Development With Integrated Database Tools

Tuesday, September 13, 2011

org.tigris.subversion.javahl.ClientException: RA layer request failed

Title of the article is basically an error which you might receive when you are trying to connect to a SVN repository over internet (that means repository is outside your corporate LAN firewall) using subversion plugin (inside Eclipse).
Below is the screen-shot of the same:

Now how to resolve it. Here we go:
  1. Close the eclipse if it is running.
  2. Open the following file:
    Windows Vista/7: C:\Users\<user-profile-name>\AppData\Roaming\Subversion\server
    Windows XP: C:\Documents and Settings\<user-profile-name>\Application Data\Subversion\server
  3. Go to the Entry shown below:
    [global]
    # http-proxy-exceptions = *.exception.com, www.internal-site.org
    #http-proxy-host = somehost.example.com
    #http-proxy-port = 80
    # http-proxy-username = defaultusername
    # http-proxy-password = defaultpassword
    
  4. Uncomment the http-proxy-host and http-proxy-port line and provide your proxy server path and port no. Do not leave any spaces before the http-proxy-host.So it should look like this:
    http-proxy-host = substitute with your proxy server path
    http-proxy-port = substitute your proxy server port
    

  5. Start the eclipse again.
  6. That should resolve the problem for you. If this article resolves your problem. Please leave a comment otherwise add comment to let me know, your issue.

After seeing so many comments, I decided that I will try the same thing for NetBeans and guess what it was easier than eclipse also.
Following are the steps to access the SVN behind the firewall:
  1. Click on Team > select subversion > select checkout...
    Click on the image to open it in new window to see it properly.
  2. On the next window fill the repository URL, username and password as shown:
  3. After that click on Proxy Configuration.. button and select Manual Proxy settings and fill the proxy server host and port and click on ok as shown:
  4. Note: If your company uses a .pac file for proxy settings then open that file and find out the proper proxy server address and port number. In NetBeans do not select the option of using system proxy settings
At times we make mistake in entering the URL itself so here is a sample SVN url
https://onlinerepository.com/svn/myproject