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
--------------------------------------------------------------------------------------------------------------------------Search keywords : how to, encrypt, decrypt, files, using DES, for encryption and decryption, java
Happy coding :)
Subscribe to:
Post Comments
(Atom)
Total Pageviews
Followers
Labels
- Algorithms (7)
- Annotation (3)
- Files (6)
- Generics (3)
- Graphics2D (5)
- Graphics2D-Images (7)
- Inheritance (2)
- J2EE (9)
- Java 8 (4)
- Java FAQs (19)
- JDBC (3)
- Networking (2)
- Packages (1)
- Reflection (4)
- Security (7)
- Sorting (2)
- Swing (3)
- Threads (3)
- Utils (3)
Popular Posts
-
Today I will show you how you can implement Bankers algorithm in Java. The Banker's algorithm is a resource allocation and deadlock a...
-
------------------------- UPDATE ------------------------- I have updated the code on request of some followers so that they can directly...
-
Today I am going to show how to convert a postfix expression to an infix expression using stack in Java. In an earlier post here we ...
-
Today in this article I will tell you how to convert an infix expression to postfix expression using stack. This is an important applicat...
-
--------------------UPDATE------------------- I have updated my post so that now it can detect IE 11. This modification was necessary as t...
-
Today I am going to show you how you can generate and validate captcha. A CAPTCHA (an acronym for "Completely Automated Public Turin...
-
Today I am going to post a program that will be able to produce all the mColorings of a given graph G. What is mColoring : The problem st...
-
Today in this article I will show you how to create or develop a Tower of Hanoi game in Java. The Tower of Hanoi is a famous problem tha...
Hey guyz the reading and writing operation has been made much easier and simpler. Just check out the new version of our post
ReplyDeleteis this code run's on android too?
Deleteis des use only 64 bit(8 char only accept) key for encrypt?
ReplyDeletehi there ! IM HAVING PROBLEM WITH YOUR CODING WHICH IS "import java.io.File;".. HW TO OVERCOME IT?
ReplyDeleteI have imported File class of java.io package. Plz specify what problem you are facing
Deletehi 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.
ReplyDeletewhen i open encoded file in notepad ,the japanese language like characters appears which ,i think is causing the problem of file download code
ReplyDeleteThanks, I tried encrypting my protect using lots of encryption tutorials and this was the only one that worked! Great tutorial and encryption!
ReplyDeleteNirupam could you discuss Encrypting and Decrypting a file using AES 256bits please?
ReplyDeleteCheck out this article
Deletehttp://javaingrab.blogspot.com/2014/04/aes-256bits-encryption-and-decryption.html
Hey guys,
ReplyDeleteWhat actualy present in DES/ECB/PKCS5Padding...
Thanks very much sir, it really worked.
ReplyDeleteThanks Buddy, it is perfect example
ReplyDeleteI want to know whether we should have "DES/ECB/PKCS5Padding" link in our computer or not?
ReplyDeleteSecretKeySpec key = new SecretKeySpec(k,algo.split("/")[0]);
ReplyDeletewhat is the use of algo.split("/")[0]
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.
DeleteAwesome. After 2 days of work, i found this blog where you have achieved it very easily..!
ReplyDeleteThanks a lot for the help..!
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.
ReplyDeleteplease discuss the encryption of video files
ReplyDeleteException in thread "main" java.io.FileNotFoundException: sample.txt (The system cannot find the file specified) this is error plz give me solution
ReplyDeleteDo you have the input file?? Without ot the code wont work
Deletegetting this error..java.io.ioexception pad block corrupted, Please help me in this
ReplyDeleteThere 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.
DeleteHi, My java is developed in java and is encrypted, Can u decrypt ??? if s , email me at shasi.kitu@gmail.com
ReplyDeleteplease send me encrption decrption project donloade link in java
ReplyDeleteThe 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
Deleteit says to me
DeleteException in thread "main" java.io.FileNotFoundException: sample.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.(FileInputStream.java:138)
at java.io.FileInputStream.(FileInputStream.java:97)
at crypto.FileEncryptor.encrypt(FileEncryptor.java:36)
at crypto.FileEncryptor.main(FileEncryptor.java:67)
Tried this and decryption was off few bytes/characters. Not sure if its the encryption or decryption that drops characters/bytes.
ReplyDeleteIf 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.
DeleteKudos man :) This is what I wanted. Easily written back into the file (y). Loved your blog.
ReplyDeleteHow can I extend this algorithm to encrypt .pdf, .docx as well?
ReplyDeleteSir can u explain me about pgp encryption with an example program?????
ReplyDelete