Sunday, 16 November 2014

Generating MD5 hash in Java

Background

Heard of MD5 hashing algorithm ?  MD5 stands for Message Digest algorithm 5 which is a cryptographic algorithm invented by Ronald Rivest in 1991 for calculating hash values. So MD5 is a widely used hashing algorithm in many companies and firms. (MD5 Wiki)

How did I get here you ask ? 

I was trying to understand how passwords are stored in database. For example you create a website where users can login you will need to store user credentials - username and password for instance. Now how would you store the password ? Plain text ? Don't guess... answer is NO! It is a major security flaw. Anyone can get the passwords once they get into the file system you are using to store the passwords. Then store in encrypted ? Better idea then storing as raw text but again not recommended. Once someone knows the encryption method you have used all your sensitive data is gone. Infact developers developing the product should not know what passwords users have. And answer to all of it is hash the password string and store it which is exactly why we are looking at MD5 algorithm in this post. Well... natural question to follow is how is password verified when user logs in again? Again the hash of user entered password is generated and compared against the save hash value.

Infact you can use MD5 checksum to verify integrity of your files after transferring it over the network. In linux you can use md5sum command to calculate the checksum value. 

  • Hash is 128 bit or 16 byte or 32 hex characters.



If checksum is same after transferring your file over the network then your files is transferred correctly. If it's not the same that mean your file is corrupted.

To the Code

 Java code to generate MD5 hash is as follows - 

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class MD5HashDemo {
    
    public static void main(String args[]) throws IOException 
    {
        
        String password = "password";
        try {
            System.out.println("MD5 hash generated : " + getMD5Hash(password));
        } catch (NoSuchAlgorithmException e) {
            System.out.println("Could not generate MD5 hash for password");
            e.printStackTrace();
        }
        
    }
    
    public static String getMD5Hash(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException
    {
        
        byte[] passwordBytes = password.getBytes("UTF-8");
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] md5Bytes = md.digest(passwordBytes);
        
        StringBuffer hexStringBuffer = new StringBuffer();
        for (int i=0;i<md5Bytes.length;i++) {
            String hexString=Integer.toHexString(md5Bytes[i] & 0xff);
                if(hexString.length()==1) 
                {
                hexStringBuffer.append('0');
                }
            hexStringBuffer.append(hexString);
        }
        
        return hexStringBuffer.toString();
    }

}


Output : 
MD5 hash generated : 5f4dcc3b5aa765d61d8327deb882cf99

Above is just plain raw method to generate MD5 hash but we need not code from scratch. We have libraries that help us do that. You can use commons-codec library which apache provides. Then you can get the hash by simply executing -

org.apache.commons.codec.digest.DigestUtils.md5Hex(password);

Even Spring framework provides such a method.

Note :  See how I have used "UTF-8" encoding in getBytes() method? It is a good idea to do so unless you are using a specific encoding throughout your application. If not provided system encoding is picked up by default which may vary from system to system.


Lets now come to million dollar question....

Is it possible to decrypt md5 hashes?

Answer is No! If we could then why bother for hashing we could go for good encryption only. So we cannot get the original string from the hash unless you use Rainbow tables do some kind of brute forcing technique to guess.  But even using that it is almost impossible to get the original string back.

Also if you use Salt to generate the hash then even above techniques won't work. Using salt gives different hashes every time for same String input. But note using salt will not work in case of passwords for obvious reasons (you will not be able to compare it then)



Related Links

Saturday, 15 November 2014

Creating a simple JSON parser for parsing various similar response types.

Background

Many a times it so happens that a particular service or APIs return a set of similar resources. So how do we handle it in a client that uses these APIs or services. One way is that you check the incoming response against all the exhaustive possible list of responses . One would match and you will have your result. But that's very bad programming. So many if-else statements. Plus so much computing time wastage. Surely not a way to go for production code. In this post I will show how can write a simple parser that parses such requests.


Assumption and Understanding of task

Before we go to the code let me explain the problem which we are going to solve with the parser. Assume there is a Service or an API that returns an Animal. For example you want a pet you may ask for Dog or a Cat. If you want to participate in horse racing you may ask for a Horse or a Hen for poultry etc. Point is we have to build a client that can parse the incoming requests. So if someone asks for a Dog we should parse the response for a Dog and prove it is indeed a Dog.

For simplicity of code and understanding I am just going to work with Class Dog and Class Cat. To differentiate between them I am adding bark() method in Dog class and drink() method in Cat class.
Also we have a super class called Animal. Both Dog and Cat class extend Animal Class. We will leverage the concept of polymorphism

Also I am assuming that the response we get has a basic structure 

{
     "type":type of animal
}

It may have additional attributes depending on the type of animal. For Cat and Dog I have added another attribute called isPet. What will be more important is the type which is common to all the responses.

To the Code

As usual I am using Eclipse with Ivy dependency manager. We need GSON library to handle json data. My Ivy file looks like -



<ivy-module version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd">
    <info
        organisation="OpenSourceForGeeks"
        module="JsonParser"
        status="integration">
    </info>
    
    <dependencies>
        <dependency org="com.google.code.gson" name="gson" rev="2.2.4"/>
    </dependencies>
</ivy-module>

Next lets create our model classes. We will have three model classes - Animal, Dog and Cat. Overall my project structure looks like follows -



Animal.java

package opensourceForGeeks.models;

public class Animal {
    
    private String type;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

}

Dog.java

package opensourceForGeeks.models;

public class Dog extends Animal {
    
    boolean isPet;
    
    public boolean isPet() {
        return isPet;
    }

    public void setPet(boolean isPet) {
        this.isPet = isPet;
    }

    public void bark()
    {
        System.out.println("Dog is barking...");
    }

}

Cat.java

package opensourceForGeeks.models;

public class Cat extends Animal {
    
    boolean isPet;
    
    public boolean isPet() {
        return isPet;
    }

    public void setPet(boolean isPet) {
        this.isPet = isPet;
    }

    public void drink()
    {
        System.out.println("Cat is drinking milk...");
    }
    
    
}

Next lets write our actual parser logic - JsonParser.java

package opensourceForGeeks.parser;

import java.util.HashMap;
import java.util.Map;

import com.google.gson.Gson;

import opensourceForGeeks.models.Animal;
import opensourceForGeeks.models.Cat;
import opensourceForGeeks.models.Dog;

public class JsonParser {
    
    private static final Map<String, Class> ANIMAL_MAPPING = new HashMap<String, Class>();
    private static final Gson gson = new Gson();
    
    static
    {
        ANIMAL_MAPPING.put("dog", Dog.class);
        ANIMAL_MAPPING.put("cat", Cat.class);
    }
    
    public Animal parseAnimal(String jsonString)
    {
        try
        {
            Animal animal = gson.fromJson(jsonString, Animal.class);
            return gson.fromJson(jsonString, ANIMAL_MAPPING.get(animal.getType()));
        }
        catch (Exception ex)
        {
            System.out.println("Exception occured while parsing Animal json string");
            return null;
        }
        
    }

}

and finally lets test it - JSONParserTest.java

package opensourceForGeeks.test;

import opensourceForGeeks.models.Cat;
import opensourceForGeeks.models.Dog;

public class JSONParserTest {
    
     private static final String DOG_JSON = "{\"type\": dog,\"isPet\": true}";
     private static final String CAT_JSON = "{\"type\": cat,\"isPet\": true}";
    
    public static void main(String args[])
    {
        opensourceForGeeks.parser.JsonParser parser = new opensourceForGeeks.parser.JsonParser();
        ((Dog) parser.parseAnimal(DOG_JSON)).bark();
        ((Cat) parser.parseAnimal(CAT_JSON)).drink();
    }

}


and the output is as expected - 

Dog is barking...
Cat is drinking milk...

Understanding the logic

What we have done in our JsonParser class is as follows -

  • We first create a map of type(exhaustive list of possible types of Animals) and their model classes.
  • All type of Animals extend Class Animal which has the type that will be common to all the JSON responses.
  • So we first convert the json string into Animal object which in turn provides us the information about what type of Animal it is.
  • Then we use this information to get the model class used to describe that type of Animal and again parse the json String to covert it into that specific type of Animal and finally return it.
  • Yes we have used polymorphism here to make our task easier!




Thursday, 13 November 2014

Difference between Association, Aggregation and Composition in UML, Java and Object Oriented Programming

Background

In Object oriented programming a program is essentially multiple objects interacting with each other. Each interacting object have a relation. This relationship can be categorized as -
  • Association, 
  • Aggregation and 
  • Composition
Note these are not mutually exclusive (We will come to that in a while). But given a relationship between a Class or it's object their interactions can be described with above categories. Also to represent these relationships there are UML diagrams (Wiki) . For example we may have Class diagram or Use case diagram or a timeline diagram. Above classifications are also used in these UML diagrams.


Difference between Association, Aggregation and Composition


When we think of Object oriented nature we always think of Objects, class (objects blueprints) and the relationship between them. Objects are related and interact with each other via methods. In other words object of one class may use services/methods provided by object of another class. This kind of relationship is termed as association.

For example you are related to your parent. In other words you are associated with  associated with your parent. This type of generic relationship is called association.




Aggregation and Composition are subsets of association meaning they are specific cases of association.


  • In both aggregation and composition object of one class "owns" object of another class.
  • But there is a subtle difference. In Composition the object of class that is owned by the object of it's owning class cannot live on it's own(Also called "death relationship"). It will always live as a part of it's owning object where as in Aggregation the dependent object is standalone and can exist even if the object of owning class is dead.
  • So in composition if owning object is garbage collected the owned object will also be which is not the case in aggregation.



Confused? Lets take examples to understand Composition and Aggregation

  • Composition Example :Consider example of a Heart and an Human. This type of relation ship between Human and Heart class is called Composition. Object of Heart class cannot exist without object of Human class and object of Heart has no significance without Human class. To put in simple words Humanclass solely "owns" the Heart class.



  • Aggregation Example :Now consider class Car and class Wheel. Car needs a Wheel object to function. Meaning Car object own Wheel object but we cannot say Wheel object has no significance without Car Object. It can very well be used in a Bike, Truck or different Cars Object.




Summing it up


To sum it up association is a very generic term used to represent when on class used the functionalities provided by another class. We say it's composition if one parent class object owns another child class object and that child class object cannot meaningfully exist without the parent class object. If it can then it is called Aggregation.




Note : For Association you can either use an arrow depicted above or a simple line. In Argo UML (Wiki) tool which I use we can choose from either. For example above association diagram for Parent-Child can be


Related Links

Sunday, 9 November 2014

Strategy Design pattern in Java

Background

In my previous post on Introduction to Design Patterns  we saw there are various types of Design patterns. They are mainly categorized into three types - 
  1. Creational
  2. Structural
  3. Behavioral
 In this post we will lean about Strategy Design pattern. This design pattern comes under behavioral type. This design patterns lets you  
  • define family of algorithms or class behaviors that can change at runtime depending on the context involved. To put it in other words 
  • it lets you choose your strategy from a list of predefined ones depending on what would suit your current runtime context.

Class Diagram




 Above class diagram represents the program that I will be using to demonstrate Strategy pattern. Points to note here -

  1. Both concrete type of Strategies i.e AdditionStrategy and SubtractionStrategy implement the interface Strategy that has a common method performOperation() that each implementing class implement.
  2. Also note the composition relationship between Strategy class and Calculator class. It simply means Calculator class owns Strategy class and that Strategy class cannot exist meaningfully without Calculator class.

To the Code

Lets first write own interface class - 

 Strategy.java

/**
 * 
 * @author athakur
 *
 */
public interface Strategy {
    
    public int performOperation(int a, int b);

}


Now lets write our concrete classes that implement above class -

AdditionStrategy.java


/**
 * 
 * @author athakur
 *
 */
public class AdditionStrategy implements Strategy {

    @Override
    public int performOperation(int a, int b) {
        // TODO Auto-generated method stub
        return a+b;
    }

}

SubtractionStrategy.java

/**
 * 
 * @author athakur
 *
 */
public class SubtractionStrategy implements Strategy {

    @Override
    public int performOperation(int a, int b) {
        // TODO Auto-generated method stub
        return a-b;
    }

}

and finally our Calculator class - Calculator.java


/**
 * 
 * @author athakur
 *
 */
public class Calculator {
    
    Strategy strategy;

    public Strategy getStrategy() {
        return strategy;
    }

    public void setStrategy(Strategy strategy) {
        this.strategy = strategy;
    }
    
    public int calculate(int a, int b) {
        return strategy.performOperation(a, b);
    }

}

Now lets test our code. Create a class Test.java

/**

 * 

 * @author athakur

 *

 */

public class Test {

    public static void main(String args[]) {

        Calculator calc = new Calculator();

        calc.setStrategy(new AdditionStrategy());

        System.out.println("Additition : " + calc.calculate(5, 2));

        calc.setStrategy(new SubtractionStrategy());

        System.out.println("Subtraction : " + calc.calculate(5, 2));

    }

}

and the output will be as expected - 

Additition : 7
Subtraction : 3

Understanding the pattern via code

 See how we could change the operation using a particular strategy depending on the requirement. Calculator here is own context. When we needed addition we use the Addition Strategy and when we needed Subtraction we used the Subtraction strategy. Note how the context or the Calculator remains the same but the strategy used changes. We are simply using different strategies depending on the requirement at runtime. This type of design is called Strategy pattern.

To sum up -

In Strategy pattern, objects representing various strategies are created and a context object behavior changes depending on these strategies at runtime.

Related Links

Sunday, 26 October 2014

Things to do after installing Ubuntu 14.04 LTS


  1. Setting -> Appearances ->  Behavior -> Enable Workspaces

  2. Settings -> Security & Privacy ->Search -> Include online results : Set this to off if you don't want online results like the Amazon results in your Unity Dashboard. You can remove it altogether with

    • sudo apt-get remove unity-lens-shopping

  3. Install "nautilus-open-terminal" and "nautilus-terminal" plugins for nautilus file manager so that it would be easier to open terminal directly from specific directories and embed terminal directly in explorer. Refer Enabling "open command prompt" from folder and embed terminal in explorer in ubuntu

  4. Installing Java (Oracle JDK)


    • sudo apt-get install python-software-properties
    • sudo add-apt-repository ppa:webupd8team/java
    • sudo apt-get update
    • sudo apt-get install oracle-java7-installer
    • Add line JAVA_HOME="/usr/lib/jvm/java-7-oracle" to /etc/environment file. Then reload the file using source /etc/environment. You can verify this setup with echo $JAVA_HOME  and java -version

  5. Install and configure Compiz (For proper Cube Set Horizontal Virtual size to 4 and Vertical Virtual Size to 1 in General Options -> Desktop Size) (I also like wobbly windows effect)

    • sudo apt-get install compiz compizconfig-settings-manager compiz-plugins




  6. Install latest Eclipse
    • Download Eclipse from its official site
    • Run the following commands -
      • cd /opt/
      • sudo tar -zxvf ~/Downloads/eclipse-*.tar.gz
      • sudo gedit /usr/share/applications/eclipse.desktop
        Add the following content -

        [Desktop Entry]
        Name=Eclipse 4
        Type=Application
        Exec=/opt/eclipse/eclipse
        Terminal=false
        Icon=/opt/eclipse/icon.xpm
        Comment=Integrated Development Environment
        NoDisplay=false
        Categories=Development;IDE;
        Name[en]=Eclipse

    • You can then launch eclipse from unity dashboard. 
     
     
  7. Install Gimp : sudo apt-get install gimp . It is an image editing software like photoshop.

  8. Configure pidgin -
    1. How to configure Pidgin for Google Talk in Ubuntu
    2. How to disable Pidgin Notifications in Ubuntu? 

  9. Install Skype :
    • sudo add-apt-repository "deb http://archive.canonical.com/ $(lsb_release -sc) partner"
    • sudo apt-get update && sudo apt-get install skype
  10.  Install Maven
    1. How to install maven on Ubuntu?
Note : I am going to keep updating this List as an when I find something useful. If you want to add something to this list do post it in comments.
t> UA-39527780-1 back to top