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 :)

29 comments:

  1. Hey guyz the reading and writing operation has been made much easier and simpler. Just check out the new version of our post

    ReplyDelete
    Replies
    1. is this code run's on android too?

      Delete
  2. is des use only 64 bit(8 char only accept) key for encrypt?

    ReplyDelete
  3. hi there ! IM HAVING PROBLEM WITH YOUR CODING WHICH IS "import java.io.File;".. HW TO OVERCOME IT?

    ReplyDelete
    Replies
    1. I have imported File class of java.io package. Plz specify what problem you are facing

      Delete
  4. hi there,i have a problem that while i encrypt the file, and try to download the file using file download code, this encoded file changes.

    ReplyDelete
  5. when i open encoded file in notepad ,the japanese language like characters appears which ,i think is causing the problem of file download code

    ReplyDelete
  6. Thanks, I tried encrypting my protect using lots of encryption tutorials and this was the only one that worked! Great tutorial and encryption!

    ReplyDelete
  7. Nirupam could you discuss Encrypting and Decrypting a file using AES 256bits please?

    ReplyDelete
    Replies
    1. Check out this article
      http://javaingrab.blogspot.com/2014/04/aes-256bits-encryption-and-decryption.html

      Delete
  8. Hey guys,

    What actualy present in DES/ECB/PKCS5Padding...

    ReplyDelete
  9. Thanks very much sir, it really worked.

    ReplyDelete
  10. Thanks Buddy, it is perfect example

    ReplyDelete
  11. I want to know whether we should have "DES/ECB/PKCS5Padding" link in our computer or not?

    ReplyDelete
  12. SecretKeySpec key = new SecretKeySpec(k,algo.split("/")[0]);
    what is the use of algo.split("/")[0]

    ReplyDelete
    Replies
    1. See tthe main method. While creating the key I only need the name of algo which is DES and the input is DES/ECB/PKCS5Padding. To extract the DES thing only split is used. The input is such because while encrypting the file I want to add padding to it.

      Delete
  13. Awesome. After 2 days of work, i found this blog where you have achieved it very easily..!

    Thanks a lot for the help..!

    ReplyDelete
  14. Key use for encryption and decryption must be the same but here i used key for encryption ex.12345678 and for decryption i used key ex. abcdefgh though i got same data which is wrong so can u explain where i am wrong? and also why we do not use not more and less than 8 character.

    ReplyDelete
  15. please discuss the encryption of video files

    ReplyDelete
  16. Exception in thread "main" java.io.FileNotFoundException: sample.txt (The system cannot find the file specified) this is error plz give me solution

    ReplyDelete
    Replies
    1. Do you have the input file?? Without ot the code wont work

      Delete
  17. getting this error..java.io.ioexception pad block corrupted, Please help me in this

    ReplyDelete
    Replies
    1. There must be some problem with your input file. It would be better if you can mail me your input fileso that I can have a look at what is going wrong.

      Delete
  18. Hi, My java is developed in java and is encrypted, Can u decrypt ??? if s , email me at shasi.kitu@gmail.com

    ReplyDelete
  19. please send me encrption decrption project donloade link in java

    ReplyDelete
    Replies
    1. The project download link is available. You can download now. Also note that some updates have been made to the code for better functioning and usage

      Delete
  20. Tried this and decryption was off few bytes/characters. Not sure if its the encryption or decryption that drops characters/bytes.

    ReplyDelete
    Replies
    1. If this problem is after using the updated code, then try using the older code that is posted and tell me if the problem persists. And you can send me the file that you want to encrypt as I checked the code and tested but found nothing.

      Delete
  21. Kudos man :) This is what I wanted. Easily written back into the file (y). Loved your blog.

    ReplyDelete

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.