Saturday, July 19, 2014

Insertion Sort Algorithm using Java

Insertion Sort is simple sort algorithm. In insertion sort, we pickup element and find correct place of element where it needs to be inserted and insert that element at correct place by moving elements to right side.We will keep doing same until we have all sorted elements available on left side.

Java Program using Insert Sort Algorithm :
package com.anuj.algorithms;

import java.util.Arrays;

/**
 *
 * @author Anuj
 * @source goldenpackagebyanuj.blogspot.com
 */
public class InsertionSort {

    public static void main(String[] args) {
        int arr[] = {12, 9, 4, 99, 120, 1, 3, 10};

        System.out.println("Before Sorting :" + Arrays.toString(arr));
        insertionSort(arr);
        System.out.println("After Sorting : " + Arrays.toString(arr));
    }

    public static void insertionSort(int arr[]) {
        System.out.println("Intermediate Happenings : ");
        for (int i = 1; i < arr.length; i++) {
            int valueToSort = arr[i];

            int j = i;
            while (j > 0 && arr[j - 1] > valueToSort) {
                arr[j] = arr[j - 1];
                j--;
            }
            arr[j] = valueToSort;
            System.out.println(Arrays.toString(arr));
        }
    }
}

Output:
run:
Before Sorting :[12, 9, 4, 99, 120, 1, 3, 10]
Intermediate Happenings : 
[9, 12, 4, 99, 120, 1, 3, 10]
[4, 9, 12, 99, 120, 1, 3, 10]
[4, 9, 12, 99, 120, 1, 3, 10]
[4, 9, 12, 99, 120, 1, 3, 10]
[1, 4, 9, 12, 99, 120, 3, 10]
[1, 3, 4, 9, 12, 99, 120, 10]
[1, 3, 4, 9, 10, 12, 99, 120]
After Sorting : [1, 3, 4, 9, 10, 12, 99, 120]
BUILD SUCCESSFUL (total time: 0 seconds)

Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/

Quick Sort Algorithm using Java

Quick Sort works on Divide and Conquer algorithm. Here, given array is divided into two parts, left and right. and both array are being sorted individually. After then we combine and will have sorted array.

How it works:
  1. Pick up any element in Array. ex. middle element of array. we called this one as Pivot.
  2. All elements which are smaller than Pivot are placed in one array and All elements which are larger than pivot are placed in another array
  3. Using recursion sort both array using quicksort
  4. Combine array as mentioned below.
Java Program using Quick sort algorithm:

package com.anuj.algorithms;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 *
 * @author Anuj
 * @source goldenpackagebyanuj.blogspot.com
 */
public class QuickSort {

    public static void main(String[] args) {
        QuickSort quickSort = new QuickSort();
        List<Integer> input = quickSort.generateRandomNumbers(10);

        System.out.println("Before Sorting : " + input);
        System.out.println("After Sorting : " + quickSort.quickSort(input));
    }

    private List<Integer> generateRandomNumbers(int n) {
        List<Integer> input = new ArrayList<>();
        Random random = new Random();

        for (int i = 0; i < n; i++) {
            input.add(random.nextInt(n * 10));
        }
        return input;
    }

    private List<Integer> quickSort(List<Integer> input) {
        if (input.size() <= 1) {
            return input;
        }

        int middle = (int) Math.ceil((double) input.size() / 2);
        int pivot = input.get(middle);

        List<Integer> less = new ArrayList<>();
        List<Integer> greater = new ArrayList<>();

        for (int i = 0; i < input.size(); i++) {
            if (input.get(i) <= pivot) {
                if (i == middle) {
                    continue;
                }
                less.add(input.get(i));
            } else {
                greater.add(input.get(i));
            }
        }

        return concate(quickSort(less), pivot, quickSort(greater));
    }

    private List<Integer> concate(List<Integer> less, int pivot, List<Integer> greater) {
        List<Integer> list = new ArrayList<>();

        for (Integer i : less) {
            list.add(i);
        }
        list.add(pivot);
        for (Integer j : greater) {
            list.add(j);
        }
        return list;
    }
}


Output :
run:
Before Sorting : [34, 41, 82, 50, 33, 61, 97, 54, 84, 31]
After Sorting : [31, 33, 34, 41, 50, 54, 61, 82, 84, 97]
BUILD SUCCESSFUL (total time: 0 seconds)

Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/

Bubble Sort Algorithm using Java

In Bubble Sort, smaller elements bubbles to top of list in ascending sorting hence it's called Bubble Sort.

How it works :
  1. In Bubble Sort, You take first element and second element initially and compare both elements.
  2. If second element is smaller than first element then you swipe places. how? using temp :) as below
  3. You keep doing same meaning stepping through array and comparing element with pair of adjacent elements until no swapping required and you have sorted array
Java Program using Bubble Sort Algorithm :

package com.anuj.algorithms;

import java.util.Arrays;

/**
 *
 * @author Anuj Patel
 * @source goldenpackagebyanuj.blogspot.com
 */
public class BubbleSort {

    protected void doBubbleSort(int data[], String sortingType) {
        int temp;
        for (int i = 0; i < data.length; i++) {
            //data[i] - individual array values
            for (int j = 0; j < data.length - 1; j++) {
                if (sortingType.equalsIgnoreCase("Ascending")) {
                    if (data[j] > data[j + 1]) {
                        temp = data[j];
                        data[j] = data[j + 1];
                        data[j + 1] = temp;                        
                    }                    
                } else if (sortingType.equalsIgnoreCase("Descending")) {
                    if (data[j] < data[j + 1]) {
                        temp = data[j];
                        data[j] = data[j + 1];
                        data[j + 1] = temp;
                    }
                }
            }
        }
        System.out.println("After " + sortingType + " Sorting : " + Arrays.toString(data));
   }

    public static void main(String[] args) {
        BubbleSort bubbleSort = new BubbleSort();

        int data[] = {1, 2, 33, 56, 8, 31};
        System.out.println("Before Sorting : " + Arrays.toString(data));
        bubbleSort.doBubbleSort(data, "Ascending");
        bubbleSort.doBubbleSort(data, "Descending");
    }
}

Output :
run:
Before Sorting : [1, 2, 33, 56, 8, 31]
After Ascending Sorting : [1, 2, 8, 31, 33, 56]
After Descending Sorting : [56, 33, 31, 8, 2, 1]
BUILD SUCCESSFUL (total time: 0 seconds)

Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/

Binary Search Algorithm using Java

Binary search works faster than sequential search.It search on sorted elements.
In Binary Search, Let's say You have an array and you want to search specific item in array

How it Works :
  1. Initialize low=0 and high as max length of search array - 1.
  2. while low<=high each item you, take middle element of array and if given searchItem is less than middle element then you need to search in array of elements array which are less than middle element. Hence, high = middle - 1
  3. If given searchItem is larger than middle element then search in array of elements which are greater than middle element. Hence low = middle+1
  4. If searchItem == middle element then you have found your element.

Java Program for Binary Search Algorithm :
package com.anuj.algorithms;

import java.util.Arrays;

/**
 *
 * @author Anuj Patel
 * @source goldenpackagebyanuj.blogspot.com
 */
public class BinarySearch {

    public static void main(String[] args) {
        BinarySearch bs = new BinarySearch();
        int a[] = {1, 51, 3, 42, 5, 6, 17, 19, 12};
        int searchItem = 12;

        System.out.println("Before Sorting : " + Arrays.toString(a));
        Arrays.sort(a);
        System.out.println("After Sorting : " + Arrays.toString(a));
        System.out.println("Item being searched : " + searchItem);

        //int searchResult = Arrays.binarySearch(a, searchItem);
        int searchResult = bs.search(a, searchItem);
        System.out.println("The index of " + searchItem + " is : " + searchResult);
    }

    /**
     * Binary Search Algorithm
     *
     * @param a
     * @param searchItem
     * @return index of searchItem
     */
    public static int search(int[] a, int searchItem) {
        int low = 0;
        int high = a.length - 1;

        while (low <= high) {
            int middle = (low + high) / 2;
            // int middle = (low+high) >>> 1;
            int midVal = a[middle];

            if (searchItem > midVal) {
                low = middle + 1;
            } else if (searchItem < midVal) {
                high = middle - 1;
            } else {
                return middle;
            }
        }
        return -(low + 1); //Key not found
    }
}
Output :
run:
Before Sorting : [1, 51, 3, 42, 5, 6, 17, 19, 12]
After Sorting : [1, 3, 5, 6, 12, 17, 19, 42, 51]
Item being searched : 12
The index of 12 is : 4
BUILD SUCCESSFUL (total time: 0 seconds)

Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/

Sequential Search Algorithm using Java

Sequential Search is simplest algorithm. You try to search given element in given collections sequentially and return only if you found element.

Java Program using Sequential Search Algorithm :
package com.anuj.algorithms;

/**
 * 
 * @author Anuj
 * @source goldenpackagebyanuj.blogspot.com
 */
public class SequentialSearch {

    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5, 19, 17, 7};

        int searchItem = 3;
        SequentialSearch sequentialSearch = new SequentialSearch();
        boolean searchItemFound = sequentialSearch.contains(a, searchItem);
        System.out.println("SearchItem " + searchItem + " found : " + searchItemFound);
    }

    public boolean contains(int[] a, int searchItem) {
        for (int i : a) {
            if (i == searchItem) {
                return true;
            }
        }
        return false;
    }
}


Output :
SearchItem 3 found : true
BUILD SUCCESSFUL (total time: 0 seconds)

Tuesday, April 08, 2014

Building Application with Spring Boot

Spring Boot makes very easy to build standalone as well as production grade Spring based application. I found features like "Embedded Tomcat and Jetty. no need to deploy war. also XML based configuration eliminated" - interesting !

Spring Boot Features :
  • Create Stand Alone Spring based Application
  • No need for XML Configuration
  • Embedded Tomcat and Jetty (no need to deploy war)
  • Configure Spring Automatically whenever possible
  • Maven Configuration simplified
  • Provide production ready features like health check and externalized Configuration.

If you are using Maven then add following into pom.xml

    org.springframework.boot
    spring-boot-starter-parent
    1.0.1.RELEASE


    
        org.springframework.boot
        spring-boot-starter-web
    


If You are using Gradle then Add following dependencies into build.gradle
dependencies {
    compile("org.springframework.boot:spring-boot-starter-web:1.0.1.RELEASE")
}

Build Sample Spring Application using Spring Boot :

Home Controller
package com.anuj.controllers;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 
 * @author Anuj
 * @source goldenpackagebyanuj.blogspot.com
 */
@RestController
public class HomeController {
    
    @RequestMapping("/home")
    public String handleHome() {
        return "Welcome to Spring Boot!";
    }
    
}

Here, @RestController is newly introduced in Spring 4 while previously using @Controller in spring 3.2. @RestController combines @Controller and @ResponseBody hence due to same, then we hit request from browser, it returns data rather than View.

Application
package com.anuj;
import java.util.Arrays;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * 
 * @author Anuj
 * @source goldenpackagebyanuj.blogspot.com
 */
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application {
    
    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(Application.class, args);
        
        System.out.println("Beans provided by Spring Boot:");
        
        String[] beanNames = ctx.getBeanDefinitionNames();
        Arrays.sort(beanNames);
        for (String beanName : beanNames) {
            System.out.println(beanName);
        }
    }
}
Here, @EnableAutoConfiguration tells Spring to start adding beans based on classpath settings,other beans etc.
@ComponentScan tells Spring to look/scan components/services/config into package "com.anuj"
@Configuration marks class as Config class, Source of bean definations

build.gradle
buildscript {
    repositories {
        maven { url "http://repo.spring.io/libs-snapshot" }
        mavenLocal()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.0.1.RELEASE")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'

jar {
    baseName = 'SpringBoot'
    version =  '1.0'
}

repositories {
    mavenCentral()
    maven { url "http://repo.spring.io/libs-snapshot" }
}

dependencies {
    // tag::jetty[]
    compile("org.springframework.boot:spring-boot-starter-web") {
        exclude module: "spring-boot-starter-tomcat"
    }
    compile("org.springframework.boot:spring-boot-starter-jetty")
    // end::jetty[]
    // tag::actuator[]
    compile("org.springframework.boot:spring-boot-starter-actuator")
    // end::actuator[]
    testCompile("junit:junit")
}

task wrapper(type: Wrapper) {
 gradleVersion = '1.9'
}

Run Application from eclipse and hit http://localhost:8080/home into Browser

Output :










See, The beauty is that no need to start or deploy, everything is handled :)


Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/

Sunday, March 30, 2014

Hibernate Named Queries Example

Hibernate provides @NamedQueries template using which you can associate unique query name to query.
Since Named Queries are global access , their name should be unique. You can use Named Queries in XML Mappings or using Annotation.

If You are using XML instead of annotation then you can add Named Queries as below in Hibernate hbm.xml file. It should be after Class tags.

       <![CDATA[from Customer cust where cust.customerType = :customerType]]>


Hibernate Names Queries Tutorial using Annotation:

Customer.java
package com.anuj.core.entities;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

@NamedQueries({
 @NamedQuery(
   name="retrieveCustomerByType",
   query="from Customer cust where cust.customerType = :customerType"
 )
})

/**
 * 
 * @author Anuj
 * @source goldenpackagebyanuj.blogspot.com
 */
@Entity
@Table(name = "customer")
public class Customer implements Serializable{

 private String customerId;
 private String customerName;
 private String customerType;

 public Customer(){
  
 }
 
 public Customer(String customerName,String customerType){
  this.customerName = customerName;
  this.customerType = customerType;
 }
 
 @Id
 @GeneratedValue
 @Column(name="CustomerId",nullable=false,unique=true)
 public String getCustomerId() {
  return customerId;
 }

 public void setCustomerId(String customerId) {
  this.customerId = customerId;
 }

 @Column(name="CustomerName",nullable=false)
 public String getCustomerName() {
  return customerName;
 }

 public void setCustomerName(String customerName) {
  this.customerName = customerName;
 }

 @Column(name="CustomerType",nullable=false)
 public String getCustomerType() {
  return customerType;
 }

 public void setCustomerType(String customerType) {
  this.customerType = customerType;
 }

}


HibernateUtils :
package com.anuj.hibernate.utils;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

/**
 * 
 * @author Anuj
 * @source goldenpackagebyanuj.blogspot.com
 */
public class HibernateUtils {

 private static SessionFactory sessionFactory = buildSessionFactory();
 
 private static SessionFactory buildSessionFactory(){
  try {
   return new AnnotationConfiguration().configure().buildSessionFactory();
  } catch (Throwable ex) {
   // TODO: handle exception
   System.err.println("Initialization of Session Factory Failed");
   throw new ExceptionInInitializerError(ex);
  }
 }
 
 public static SessionFactory getSessionFactory(){
  return sessionFactory;
 }
}


Hibername Configuration Xml :

 
  com.mysql.jdbc.Driver
  PASSWORD
  jdbc:mysql://localhost/DBNAME
  USERNAME
  org.hibernate.dialect.MySQLDialect
  false
  
 


Note that Transaction commit and rollback mentioned below will be useful when query will be insert/update/delete.

CustomerApp :
package com.anuj.main;

import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.anuj.core.entities.Customer;
import com.anuj.hibernate.utils.HibernateUtils;

/**
 * 
 * @author Anuj
 * @source goldenpackagebyanuj.blogspot.com
 */
public class CustomerApp {

 private static Session session = null;
 
 public static void main(String[] args) {
  
  CustomerApp customerApp = new CustomerApp();
  customerApp.retrieveCustomer("Business");
 }
 
 /**
  * Retrieve Existing Customer
  * @param customerType
  */
 public void retrieveCustomer(String customerType){
  Transaction transaction = null;
  
  try {
   session = HibernateUtils.getSessionFactory().openSession();
   transaction = session.beginTransaction();
   
   Query query = session.getNamedQuery("retrieveCustomerByType");
   query.setParameter("customerType",customerType);
   
   List customer = query.list();
   Iterator itr = customer.iterator();
   
   while(itr.hasNext()){
    Customer cust = (Customer)itr.next();
    System.out.println("CustomerId : "+cust.getCustomerId());
    System.out.println("Customer Name : "+cust.getCustomerName());
    System.out.println("Customer Type : "+cust.getCustomerType());        
   }
   
   transaction.commit();
   
  } catch (HibernateException e) {
   transaction.rollback();
   e.printStackTrace();   
  }
  finally{
   if(session != null){
    session.close();
   }
  }
 } 
}


Output :
CustomerId : 1
Customer Name : Anuj
Customer Type : Business
CustomerId : 10
Customer Name : Zvika
Customer Type : Business
CustomerId : 11
Customer Name : David
Customer Type : Business
CustomerId : 6
Customer Name : Prithvi
Customer Type : Business

Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/

Sunday, February 02, 2014

What is Javaassist?

Javaassist stand for Java Programming Assistance. It's java library providing means to manipulate java bytecode. 
  • It enables java program to create new java classes at runtime and to modify classes before JVM loads it.
  • It's sub project of Jboss.

Now Question is "Why we require to manipulate java bytecode"?
  • You want to create subclasses at runtime which intercepts methods invocations. Meaning "Generating Proxies" which intercepts methods invocations.
  • Hibernate uses proxies to intercept methods invocation on entities to implement lazy loading. ie. fetching objects from database once it's accessed. 
  • Spring also uses proxies to implement it's AOP Support. 

We should know :
  • There are many third parties libaries like Javaassist, CGLib, ASM etc but I perfer Javaassist.
  • It seems that Hibernate 3.6 deprecated CGlib for some reasons. Hibernate 3.6 Deprecated List  shows that support for cglib as bytecode provider has been deprecated.
  • Difference between JDK Dynamic Proxy and Cglib/javaasssit is that JDK Dynamic proxy can only proxy by interface (so your target class needs to implement an interface, which will also be implemented by the proxy class).CGLIB and javassist can create a proxy by subclassing. Here, proxy becomes a subclass of the target class. No need for interfaces.
    So Java Dynamic proxies can proxy: public class Aimplements iA where CGLIB can proxy: public class A

You can use following dependencies for  Javaassist in pom.xml:

  javassist
  javassist
  3.12.1.GA


For More Details Visit:

Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/

Tuesday, October 08, 2013

RSA Public Key Encryption and Private Key Decryption using Java

In Previous Post, I have discussed about What is Cryptography, What are Types of it and How we can encrypt and decrypt data using DES Algorithm in Java

Asymmetric Cryptography :
  • Here, We share Public Key with others so they can encrypt data using Public Key
  • We can only decrypt data using Private Key associated with Public Key. Private key is secret one and we don't share with anyone.
  • Most common used algorithm is RSA ALGORITHM. named after Rivest,Shamir and Adleman
Understanding and making working example for RSA encryption and decryption using public and private key takes lots lots of time for me. Believe me, It's complex stuff :)

Steps 1 :

Let's Break down tasks which helps us to encrypt and decrypt data using RSA Algorithm.
  1. Generate Public Key and Private Key
  2. Pull out parameters for Public Key and Private Key which help us in saving Keys to File
  3. Save Public Key and Private Key to file so public key can be distributed and private key can be kept secret.
  4. Encrypt Data using Public Key (use public key from stored file as above)
  5. Decrypt Data using Private Key (use private key from stored file as above)
Now,
Procedure to encryt and decrypt data using Cipher remains similar as we have done in DES Algorithm having some differences.

Steps 2 :  Encrypt Data

Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey); //pubKey stored earlier
cipher.doFinal(dataToEncrypt);

Steps 3 : Decrypt Data
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey); //privKey stored earlier
byte[] descryptedData = cipher.doFinal(data);
System.out.println("Decrypted Data: " + new String(descryptedData));

If you would like to correct any issue then let me know your views and suggestions ! You can fork on my GitHub RSA Algorithm Repository

Java Program - RSA Public Key Encryption and Private Key Decryption :
package com.anuj.security.encryption;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import javax.crypto.Cipher;

/**
 * 
 * @author Anuj
 * Blog www.goldenpackagebyanuj.blogspot.com
 * RSA - Encrypt Data using Public Key
 * RSA - Descypt Data using Private Key
 */
public class RSAEncryptionDescription {

 private static final String PUBLIC_KEY_FILE = "Public.key";
 private static final String PRIVATE_KEY_FILE = "Private.key";
 
 public static void main(String[] args) throws IOException {

  try {
   System.out.println("-------GENRATE PUBLIC and PRIVATE KEY-------------");
   KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
   keyPairGenerator.initialize(2048); //1024 used for normal securities
   KeyPair keyPair = keyPairGenerator.generateKeyPair();
   PublicKey publicKey = keyPair.getPublic();
   PrivateKey privateKey = keyPair.getPrivate();
   System.out.println("Public Key - " + publicKey);
   System.out.println("Private Key - " + privateKey);

   //Pullingout parameters which makes up Key
   System.out.println("\n------- PULLING OUT PARAMETERS WHICH MAKES KEYPAIR----------\n");
   KeyFactory keyFactory = KeyFactory.getInstance("RSA");
   RSAPublicKeySpec rsaPubKeySpec = keyFactory.getKeySpec(publicKey, RSAPublicKeySpec.class);
   RSAPrivateKeySpec rsaPrivKeySpec = keyFactory.getKeySpec(privateKey, RSAPrivateKeySpec.class);
   System.out.println("PubKey Modulus : " + rsaPubKeySpec.getModulus());
   System.out.println("PubKey Exponent : " + rsaPubKeySpec.getPublicExponent());
   System.out.println("PrivKey Modulus : " + rsaPrivKeySpec.getModulus());
   System.out.println("PrivKey Exponent : " + rsaPrivKeySpec.getPrivateExponent());
   
   //Share public key with other so they can encrypt data and decrypt thoses using private key(Don't share with Other)
   System.out.println("\n--------SAVING PUBLIC KEY AND PRIVATE KEY TO FILES-------\n");
   RSAEncryptionDescription rsaObj = new RSAEncryptionDescription();
   rsaObj.saveKeys(PUBLIC_KEY_FILE, rsaPubKeySpec.getModulus(), rsaPubKeySpec.getPublicExponent());
   rsaObj.saveKeys(PRIVATE_KEY_FILE, rsaPrivKeySpec.getModulus(), rsaPrivKeySpec.getPrivateExponent());
   
   //Encrypt Data using Public Key
   byte[] encryptedData = rsaObj.encryptData("Anuj Patel - Classified Information !");
   
   //Descypt Data using Private Key
   rsaObj.decryptData(encryptedData);
   
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  }catch (InvalidKeySpecException e) {
   e.printStackTrace();
  }

 }
 
 /**
  * Save Files
  * @param fileName
  * @param mod
  * @param exp
  * @throws IOException
  */
 private void saveKeys(String fileName,BigInteger mod,BigInteger exp) throws IOException{
  FileOutputStream fos = null;
  ObjectOutputStream oos = null;
  
  try {
   System.out.println("Generating "+fileName + "...");
   fos = new FileOutputStream(fileName);
   oos = new ObjectOutputStream(new BufferedOutputStream(fos));
   
   oos.writeObject(mod);
   oos.writeObject(exp);   
   
   System.out.println(fileName + " generated successfully");
  } catch (Exception e) {
   e.printStackTrace();
  }
  finally{
   if(oos != null){
    oos.close();
    
    if(fos != null){
     fos.close();
    }
   }
  }  
 }
 
 /**
  * Encrypt Data
  * @param data
  * @throws IOException
  */
 private byte[] encryptData(String data) throws IOException {
  System.out.println("\n----------------ENCRYPTION STARTED------------");
  
  System.out.println("Data Before Encryption :" + data);
  byte[] dataToEncrypt = data.getBytes();
  byte[] encryptedData = null;
  try {
   PublicKey pubKey = readPublicKeyFromFile(PUBLIC_KEY_FILE);
   Cipher cipher = Cipher.getInstance("RSA");
   cipher.init(Cipher.ENCRYPT_MODE, pubKey);
   encryptedData = cipher.doFinal(dataToEncrypt);
   System.out.println("Encryted Data: " + encryptedData);
   
  } catch (Exception e) {
   e.printStackTrace();
  } 
  
  System.out.println("----------------ENCRYPTION COMPLETED------------");  
  return encryptedData;
 }

 /**
  * Encrypt Data
  * @param data
  * @throws IOException
  */
 private void decryptData(byte[] data) throws IOException {
  System.out.println("\n----------------DECRYPTION STARTED------------");
  byte[] descryptedData = null;
  
  try {
   PrivateKey privateKey = readPrivateKeyFromFile(PRIVATE_KEY_FILE);
   Cipher cipher = Cipher.getInstance("RSA");
   cipher.init(Cipher.DECRYPT_MODE, privateKey);
   descryptedData = cipher.doFinal(data);
   System.out.println("Decrypted Data: " + new String(descryptedData));
   
  } catch (Exception e) {
   e.printStackTrace();
  } 
  
  System.out.println("----------------DECRYPTION COMPLETED------------");  
 }
 
 /**
  * read Public Key From File
  * @param fileName
  * @return PublicKey
  * @throws IOException
  */
 public PublicKey readPublicKeyFromFile(String fileName) throws IOException{
  FileInputStream fis = null;
  ObjectInputStream ois = null;
  try {
   fis = new FileInputStream(new File(fileName));
   ois = new ObjectInputStream(fis);
   
   BigInteger modulus = (BigInteger) ois.readObject();
      BigInteger exponent = (BigInteger) ois.readObject();
   
      //Get Public Key
      RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(modulus, exponent);
      KeyFactory fact = KeyFactory.getInstance("RSA");
      PublicKey publicKey = fact.generatePublic(rsaPublicKeySpec);
            
      return publicKey;
      
  } catch (Exception e) {
   e.printStackTrace();
  }
  finally{
   if(ois != null){
    ois.close();
    if(fis != null){
     fis.close();
    }
   }
  }
  return null;
 }
 
 /**
  * read Public Key From File
  * @param fileName
  * @return
  * @throws IOException
  */
 public PrivateKey readPrivateKeyFromFile(String fileName) throws IOException{
  FileInputStream fis = null;
  ObjectInputStream ois = null;
  try {
   fis = new FileInputStream(new File(fileName));
   ois = new ObjectInputStream(fis);
   
   BigInteger modulus = (BigInteger) ois.readObject();
      BigInteger exponent = (BigInteger) ois.readObject();
   
      //Get Private Key
      RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(modulus, exponent);
      KeyFactory fact = KeyFactory.getInstance("RSA");
      PrivateKey privateKey = fact.generatePrivate(rsaPrivateKeySpec);
            
      return privateKey;
      
  } catch (Exception e) {
   e.printStackTrace();
  }
  finally{
   if(ois != null){
    ois.close();
    if(fis != null){
     fis.close();
    }
   }
  }
  return null;
 }
}

Output :
-------GENRATE PUBLIC and PRIVATE KEY-------------
Public Key - Sun RSA public key, 2048 bits
modulus: 21581189033711728218884545603483534136048436157764307737563263470622465209956484999186502236746398592183132361416574917491992616495836589976123829407441678145892864499340377518038083961762657109551322980788812471344883222074336738095812428432922899347944377728829986328978579520777569602492356009886434195381263189086322743017222283576658366049322746591279563891358961018804857343098186437284431498111857540148953385584647472608550518878892606670675504722021939011562806733746871866813023994221533891973381208433651324985362129897175578902143642720519685766703550582631650738544841113850242327026858745837631433020149
public exponent: 65537
Private Key - Sun RSA private CRT key, 2048 bits
modulus: 21581189033711728218884545603483534136048436157764307737563263470622465209956484999186502236746398592183132361416574917491992616495836589976123829407441678145892864499340377518038083961762657109551322980788812471344883222074336738095812428432922899347944377728829986328978579520777569602492356009886434195381263189086322743017222283576658366049322746591279563891358961018804857343098186437284431498111857540148953385584647472608550518878892606670675504722021939011562806733746871866813023994221533891973381208433651324985362129897175578902143642720519685766703550582631650738544841113850242327026858745837631433020149
public exponent: 65537
private exponent: 16818884445379350882395107598729290416080593813537574464745772338710078438111715082067390966047001054301440184313465125210240366320168055190663664601447788444717915899473729065013582226025416358245476925153555960357354022421635853002786514216572883778571785289225804534119366907605083654230390210185843516320290211843466509006336799394129511533245623813347345392660622411996306876517607316550963240563612473897071827862623073628753325937287805770949617787789425780112692109708570540461688127920714311987581602948589935567788167325085963891768759393262829208398129726072686050759571366259756340489722725543813760017473
prime p: 169306732673760790355930286583843583805308330869543277096562778910166303721930997866328982804816821819049730113874193091618529576910909406581209778870502424642394784256694354812411284399682213039455474743549204317489176290410742719482125745160659824679134175050540597373872559990275244248263694864065118289029
prime q: 127467990746102133899249581938138767929216080178107251583999590555445542238038489740168537885259598373126437993872087614678308989656079509601390372258522297126080029882334388941627788832329332096331303686348060808722035897823890209585664124526602293844519631122458634394071272791623445251919411933626571407281
prime exponent p: 119333901496849599293704132446823728072975688967404864411271868504773060528055275408385106164501021564724723181564468948550204262420398221130137530179366136709128313306521237344549101427812082746106271950635036621111395400810892143995572494105716759714409340496355063773002962656679194311000577640962509866565
prime exponent q: 87599841848325282034397392631823732681751728567706372035518219616807479391168584759867720185760822911137855574805147536162722715185622854768100782400042506374437622501342120383019881612208077700942453678524044597159341666571405330569429887003580278506237997865700511687666143632786492373791879306019609527633
crt coefficient: 7792255011181278160725143182305151172136668404207729019083906871364836764302818205034762517433549401848970490160009739693902133369434504868735056960398036976540900479169732396057070661243627622278554530394073212878117541087837917760429802642524231978699857141434244570696796138207734744378146597148568299985

------- PULLING OUT PARAMETERS WHICH MAKES KEYPAIR----------

PubKey Modulus : 21581189033711728218884545603483534136048436157764307737563263470622465209956484999186502236746398592183132361416574917491992616495836589976123829407441678145892864499340377518038083961762657109551322980788812471344883222074336738095812428432922899347944377728829986328978579520777569602492356009886434195381263189086322743017222283576658366049322746591279563891358961018804857343098186437284431498111857540148953385584647472608550518878892606670675504722021939011562806733746871866813023994221533891973381208433651324985362129897175578902143642720519685766703550582631650738544841113850242327026858745837631433020149
PubKey Exponent : 65537
PrivKey Modulus : 21581189033711728218884545603483534136048436157764307737563263470622465209956484999186502236746398592183132361416574917491992616495836589976123829407441678145892864499340377518038083961762657109551322980788812471344883222074336738095812428432922899347944377728829986328978579520777569602492356009886434195381263189086322743017222283576658366049322746591279563891358961018804857343098186437284431498111857540148953385584647472608550518878892606670675504722021939011562806733746871866813023994221533891973381208433651324985362129897175578902143642720519685766703550582631650738544841113850242327026858745837631433020149
PrivKey Exponent : 16818884445379350882395107598729290416080593813537574464745772338710078438111715082067390966047001054301440184313465125210240366320168055190663664601447788444717915899473729065013582226025416358245476925153555960357354022421635853002786514216572883778571785289225804534119366907605083654230390210185843516320290211843466509006336799394129511533245623813347345392660622411996306876517607316550963240563612473897071827862623073628753325937287805770949617787789425780112692109708570540461688127920714311987581602948589935567788167325085963891768759393262829208398129726072686050759571366259756340489722725543813760017473

--------SAVING PUBLIC KEY AND PRIVATE KEY TO FILES-------

Generating Public.key...
Public.key generated successfully
Generating Private.key...
Private.key generated successfully

----------------ENCRYPTION STARTED------------
Data Before Encryption :Anuj Patel - Classified Information !
Encryted Data: [B@749436
----------------ENCRYPTION COMPLETED------------

----------------DECRYPTION STARTED------------
Decrypted Data: Anuj Patel - Classified Information !
----------------DECRYPTION COMPLETED------------

PLEASE NOTE that current program is for learning purpose only and one should not use it as part of production or project. Also one must check with Sun/Oracle/any other licenses if associated before using.

Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/

Friday, October 04, 2013

Calibration Data Missing in Netbeans 7.3

While I was doing profiling using netbeans 7.3,I encountered with Issue "Calibration Data Missing" when we are using profiling first time and after reading netbeans documentation found solutions which is mentioned as below.

To Solve, "Calibration Data Missing" Issue,

1. Go to Profile->Advance Commands->Run Profiler Calibration->and Select Java Platform-> Next-> Finish.
2. Click on Profile Main Project from Netbeans bar -> Select either from below

Monitor Application :


Analyze Memory :


Analyze performance :


Output After Profiling :