Posted by : Nirupam Das Sunday, March 31, 2013

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.
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------
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
--------------------------------------------------------------------------------------------------------------------------
Related Posts
--------------------------------------------------------------------------------------------------------------------------
AES - 256bits encryption and decryption of file

{ 23 comments... read them below or Comment }

  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

Total Pageviews

Subscribe via Email

Followers


Popular Post

Ads

- Copyright © Java Code House -Java Code House- Powered by Blogger - Designed by Nirupam Das -