Sunday, March 31, 2013
-------------------------UPDATE-------------------------
I have updated the code on request of some followers so that they can directly use this code for their project without requiring to make any changes.
Following changes have been made
  • A copy method has been introduced to copy the streams. I reduces unnecessary duplicate codes for copying files.
  • Another important update added is that the file decrypted will have the same name it had before encryption along with its extension.
  • The last feature added is try with resources. This reduces extra bit of coding to flush and close the streams.
--------------------------------------------------

Today I am going to discuss how you can encrypt any file in Java.For encryption we need a key based on which the encryption will be done. Not only that, I will also show how you can decrypt that file and get back the original one. The encryption algorithm can be chosen by the user. Here we will use some classes Cipher,CipherInputStream,CipherOutputStream,SecretKeySpec. One thing you have to always remember is that the same key must be used both for encryption and decryption. We will use Cipher stream classes as only one function call is required for both either reading/writing and encryption/decryption. Otherwise we would have to call update() method for encryption/decryption and then write() for writing to file.
SecretKeySpec class : This class specifies a secret key in a provider-independent fashion and is only useful for raw secret keys that can be represented as a byte array and have no key parameters associated with them, e.g., DES or Triple DES keys.
Cipher class : This class provides the functionality of a cryptographic cipher for encryption and decryption. It forms the core of the Java Cryptographic Extension (JCE) framework. Its getInstance() method is called to get the object based on algorithm. Then the init() method is called for initializing the object with encryption mode and key.
CipherInputStream class : It is composed of an InputStream and a Cipher so that read() methods return data that are read in from the underlying InputStream but have been additionally processed by the Cipher. The Cipher must be fully initialized before being used by a CipherInputStream. It is used for decryption and does read and then update operation.
CipherOutputStream class : Just like above it is also composed of a stream and cipher and the cipher must be fully initialised before using this stream. It is used for encryption purpose.

So below is the code which solves your question how to encrypt a file in Java and also how to decrypt a file. This code actually shows you how to encrypt and decrypt a file using DES or Triple DES in Java.
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------
The code after update applied
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.SecretKeySpec;

public class FileEncryptor{
    
 private String algo;
 private String path;
 
    public FileEncryptor(String algo,String path) {
     this.algo = algo; //setting algo
     this.path = path;//setting file path
    }
    
    public void encrypt() throws Exception{
         //generating key
         byte k[] = "HignDlPs".getBytes();   
         SecretKeySpec key = new SecretKeySpec(k,algo.split("/")[0]);  
         //creating and initialising cipher and cipher streams
         Cipher encrypt =  Cipher.getInstance(algo);  
         encrypt.init(Cipher.ENCRYPT_MODE, key);
         //opening streams
         FileOutputStream fos =new FileOutputStream(path+".enc");
         try(FileInputStream fis =new FileInputStream(path)){
            try(CipherOutputStream cout=new CipherOutputStream(fos, encrypt)){
                copy(fis,cout);
            }
         }
     }
     
     public void decrypt() throws Exception{
         //generating same key
         byte k[] = "HignDlPs".getBytes();   
         SecretKeySpec key = new SecretKeySpec(k,algo.split("/")[0]);  
         //creating and initialising cipher and cipher streams
         Cipher decrypt =  Cipher.getInstance(algo);  
         decrypt.init(Cipher.DECRYPT_MODE, key);
         //opening streams
         FileInputStream fis = new FileInputStream(path);
         try(CipherInputStream cin=new CipherInputStream(fis, decrypt)){  
            try(FileOutputStream fos =new FileOutputStream(path.substring(0,path.lastIndexOf(".")))){
               copy(cin,fos);
           }
         }
      }
     
  private void copy(InputStream is,OutputStream os) throws Exception{
     byte buf[] = new byte[4096];  //4K buffer set
     int read = 0;
     while((read = is.read(buf)) != -1)  //reading
        os.write(buf,0,read);  //writing
  }
  
     public static void main (String[] args)throws Exception {
      new FileEncryptor("DES/ECB/PKCS5Padding","sample.txt").encrypt();
      new FileEncryptor("DES/ECB/PKCS5Padding","sample.txt.enc").decrypt();
  }
}
The original code before update
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.SecretKeySpec;

public class FileEncryptor{
    
    private String algo;
    private File file;
 
    public FileEncryptor(String algo,String path) {
     this.algo=algo; //setting algo
     this.file=new File(path); //settong file
    }
    
     public void encrypt() throws Exception{
         //opening streams
         FileInputStream fis =new FileInputStream(file);
         file=new File(file.getAbsolutePath()+".enc");
         FileOutputStream fos =new FileOutputStream(file);
         //generating key
         byte k[] = "HignDlPs".getBytes();   
         SecretKeySpec key = new SecretKeySpec(k,algo.split("/")[0]);  
         //creating and initialising cipher and cipher streams
         Cipher encrypt =  Cipher.getInstance(algo);  
         encrypt.init(Cipher.ENCRYPT_MODE, key);  
         CipherOutputStream cout=new CipherOutputStream(fos, encrypt);
         
         byte[] buf = new byte[1024];
         int read;
         while((read=fis.read(buf))!=-1)  //reading data
             cout.write(buf,0,read);  //writing encrypted data
         //closing streams
         fis.close();
         cout.flush();
         cout.close();
     }
     
     public void decrypt() throws Exception{
         //opening streams
         FileInputStream fis =new FileInputStream(file);
         file=new File(file.getAbsolutePath()+".dec");
         FileOutputStream fos =new FileOutputStream(file);               
         //generating same key
         byte k[] = "HignDlPs".getBytes();   
         SecretKeySpec key = new SecretKeySpec(k,algo.split("/")[0]);  
         //creating and initialising cipher and cipher streams
         Cipher decrypt =  Cipher.getInstance(algo);  
         decrypt.init(Cipher.DECRYPT_MODE, key);  
         CipherInputStream cin=new CipherInputStream(fis, decrypt);
              
         byte[] buf = new byte[1024];
         int read=0;
         while((read=cin.read(buf))!=-1)  //reading encrypted data
              fos.write(buf,0,read);  //writing decrypted data
         //closing streams
         cin.close();
         fos.flush();
         fos.close();
     }
     
     public static void main (String[] args)throws Exception {
         new FileEncryptor("DES/ECB/PKCS5Padding","sample.txt").encrypt();
         new FileEncryptor("DES/ECB/PKCS5Padding","sample.txt.enc").decrypt();
  }
}

NOTE : The generated decrypted file name is not the same as that of original so that you can check whether same contents have been generated or not. You can change this part.
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------
DOWNLOAD the source from Mediafire

DOWNLOAD the complete file encryptor project from Mediafire
NOTE : the project archive contains the java source file, the sample file for encryption and the encrypted file produced after encryption of sample file.
--------------------------------------------------------------------------------------------------------------------------
Related Posts
--------------------------------------------------------------------------------------------------------------------------
AES - 256bits encryption and decryption of file

Search keywords : how to, encrypt, decrypt, files, using DES, for encryption and decryption, java

Happy coding :)
Wednesday, March 20, 2013
Today I am going to tell how you can save your application preferences, settings and configuration. You must have always wondered that how different softwares save the user data for that particular application. We can do this very easily in Java using the class java.util.prefs.Preferences .
Preferences class : This class allows applications to store and retrieve user and system preference and configuration data. This data is stored persistently in an implementation-dependent backing store. Typical implementations include flat files, OS-specific registries, directory servers and SQL databases. The user of this class needn't be concerned with details of the backing store. A node is created using node() method.
         There are two separate trees of preference nodes, one for user preferences (method used is userRoot()) and one for system preferences (method used is systemRoot()). Each user has a separate user preference tree, and all users in a given system share the same system preference tree. The precise description of "user" and "system" will vary from implementation to implementation. Typical information stored in the user preference tree might include font choice, color choice, or preferred window location and size for a particular application. Typical information stored in the system preference tree might include installation configuration data for an application. The put() method has two arguments of key-value pair. There are different put() methods for different data types. There is also a get() method for retreiving values of keys. The two parameters are key and default value. The default value is returned if key is not found. The keys and  nodes are removed using remove() and removeNode().
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------

import java.util.prefs.Preferences;

public class AppPreferences{
  public static void main (String[] args) throws Exception{
    Preferences p=Preferences.userRoot().node("myapp");
    System.out.println(p); //display current preference
    p.put("user","nirupam"); //adding a user key
    System.out.println(p.get("user","Hello World")); //shows default value if 
key not found
    p.remove("user"); //removing key
    p.removeNode();  //removing node
    }
}
--------------------------------------------------------------------------------------------------------------------------
Oitput
--------------------------------------------------------------------------------------------------------------------------
Screenshot of the windows registry
Windows Registry
To see the above outout in your registry you must comment the last two lines of code as they removes the node. So keep this in mind.

Output on Console

User Preference Node: /myapp
nirupam

--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------
DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared

Friday, March 8, 2013
Today I am going to post programs related with networking. Actually today I am going to implement a connectionless packet delivery service using datagram packets. Each machine will be routed from one machine to another solely on the information contained in the packet. But to deliver this datagrams we will have to open a datagram socket programatically. This socket can be used for both sending and receiving datagrams. But to deliver packets we must know the IP address and port number. The following classes will be used for this -->
java.net.InetAddress : This class is used to get the IP address based on the host name using its static method getByName() .
java.net.DatagramSocket : This class represents a socket for sending and receiving datagram packets. Where possible, a newly constructed DatagramSocket has the SO_BROADCAST socket option enabled so as to allow the transmission of broadcast datagrams. In order to receive broadcast packets a DatagramSocket should be bound to the wildcard address.
java.net.DatagramPacket : Each message is routed from one machine to another based solely on information contained within that packet. Multiple packets sent from one machine to another might be routed differently, and might arrive in any order. Packet delivery is not guaranteed.
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------
/* THE RECEIVER CODE */

import java.net.DatagramSocket;
import java.net.DatagramPacket;
import java.util.Scanner;

public class Receiver{
   public static void main(String[] args)throws Exception{
     String str="";
     Scanner sc=new Scanner(System.in);
     System.out.print("Enter port : ");
     int PORT=sc.nextInt(); //receiver port
     DatagramSocket rsock=new DatagramSocket(PORT); //creating socket
     do{
       byte buf[]=new byte[512];
       DatagramPacket packet=new DatagramPacket(buf,512);
       rsock.receive(packet); //receiving packets
       str=new String(buf); //converting to string
       System.out.println("Received : "+str);
     }while(!str.contains("bye")); //goes on till bye is sent

     rsock.close();  //closing socket
   }
}

/* THE SENDER CODE */

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramSocket;
import java.net.DatagramPacket;
import java.net.InetAddress;

public class Sender{
   public static void main(String[] args)throws Exception{
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     DatagramSocket ssock=new DatagramSocket(); //binding socket to any 
available port
     System.out.print("Enter host name : ");
     String str=br.readLine();  //getting host-name
     System.out.print("Enter receiver's port : ");
     int PORT=Integer.parseInt(br.readLine()); //getting receiver port
     InetAddress addr=InetAddress.getByName(str); //getting IP of receiver

     do{
       System.out.print("Sending : ");
       str=br.readLine(); //getting data to be sent
       byte buf[]=str.getBytes();
       //creating packet with receiver info inside packet
       DatagramPacket packet=new DatagramPacket(buf,buf.length,addr,PORT);
       ssock.send(packet);  //sending packet
     }while(!str.equals("bye"));
     
     ssock.close();  //closing socket
   }
}
--------------------------------------------------------------------------------------------------------------------------
Output
--------------------------------------------------------------------------------------------------------------------------
Screenshots of output
Receiver
Sender









--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------
DOWNLOAD the source package from Mediafire
DOWNLOAD the source package from 4shared

Saturday, March 2, 2013
Today I am going to show how you can create your own stack using linked list. Hope that you already know how to create a stack. But that stack can take input of only one type of objects. For different types you have to write seperate programs. But this can be avoided if we use java.lang.Object as data type for stack elements. But if you use this then a problem will arise. When you are pushing into stack then you can push any object in this case. But while popping you won't be able to understand the data type of the elements and so won't be able to typecast and use it properly and hence not type safe. So a new feature GENERICS was introduced to make it type safe. Using generics you can only insert one type of object , only you have to mention about data type during creating stack object and thus only need to create seperate stack objects and not programs. The following code will explain better.
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------
/* The STACK class */
public class Stack<T> {
    //T is the type parameter
    Node top; //topmost element of stack

    //defines each node of stack
    class Node{
       T value; //value of each node
       Node next;  //pointer to next node
 
       public Node(T value){
         this.value=value;  //initializing
         next=null;
       }
    }
    //This function pushes new element
    public void push(T value){
     Node current=new Node(value);
     if(isEmpty())
        top=current; //if empty stack
     else{
        current.next=top;
        top=current;
     }
    }
    //This function pops topmost element
    public T pop(){
     T value=null;
     if(!isEmpty()){
         top=top.next;
         value=top.value;
     }
     return value;  //returning popped value
    }
    //This function returns the entire stack
    public String toString(){
     Node current=top;
        StringBuilder s=new StringBuilder();
     System.out.println("\n---------------STACK--------------");
     
     while(current!=null){
       s.append(current.value+"  ");
       current=current.next;
     }

        return s.toString();
    }
    //This function returns topmost element
    public T peek(){
     return top.value;
    }
    //This function checks emptiness of stack
    public boolean isEmpty(){
     return (top==null)?true:false;
    }    
}


/* The main class testing stack */
public class Test{
    public static void main(String[] args) {
        //creating and using stack of integers
        Stack<Integer> s=new Stack<Integer>();
        s.push(15);  s.push(10);  s.push(12);
        System.out.println(s);
        s.pop();  s.pop();
        System.out.println(s);

        //creating and using stack of floats
        Stack<Float> s2=new Stack<Float>();
        s2.push(5.5f);  s2.push(1.2f);  s2.push(8.6f);
        System.out.println(s2);
        s2.pop();  s2.pop();
        System.out.println(s2);
    }
}

NOTE : The type parameter while creating stack object of primitive data types, you should mention object type i.e. Integer and not int,Double and not double.
--------------------------------------------------------------------------------------------------------------------------
Output
--------------------------------------------------------------------------------------------------------------------------

---------------STACK--------------
12  10  15

---------------STACK--------------
15

---------------STACK--------------
8.6  1.2  5.5

---------------STACK--------------
5.5

--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------

Total Pageviews

Subscribe via Email

Followers


Popular Posts

About Me

My photo

I am a student of BTech Computer Science Engineering from RCCIIT,Kolkata. I am a crazy lover of Java and wants to settle as a Java developer. I have a seven years Java experience with an application developer experience for 2 years. Recently from March 2012 I am a registered S40 app developer for Nokia and has corrected an app of them. I am currently writing blogs to encourage and grow interest in all those who don't know or learning Java.