Encrypt and Decrypt a file in java

Source code of the Decrypter Class
The decrypter class has a Decrypt function which accepts the encrypted file and the password to be used for the decryption process. The filename to be passed has to be a .enc file and the same password that was used for the encryption process is required to be used.

package encdecexample;

import java.awt.Color;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

 * @author Me
public class Decrypter {
     public static String currentFileWithoutEncExt = "";
     public static void Decrypt(File SourceFile, char[] PassWord){
          //Accepts a .enc file, creates a decrypted file without extension .enc.

          //As the file retains extension while crypting, the original file with original extension is obtained.

          //Deletes the .enc file in the end.

          FileInputStream inFile = null;

          FileOutputStream FileToWrite = null;

          try {

               int buffer = 4096; // The buffer for read and write FileIO

               String SourceFilePath = SourceFile.getPath();

               String DestFilePath = SourceFilePath.substring(0, SourceFilePath.length() - 4);//strip .enc 
               currentFileWithoutEncExt = DestFilePath;

               inFile = new FileInputStream(SourceFile);

               FileToWrite = new FileOutputStream(DestFilePath);

               byte[] keyData = null;;

               keyData = new String(PassWord).getBytes();

               SecretKeySpec secretKeySpec = new SecretKeySpec(keyData, "BlowFish");

               Cipher cipher = null;

               cipher = Cipher.getInstance("BlowFish");

               cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);

               byte[] input = new byte[buffer];

               byte[] output = null;

               int bytesRead;

               while ((bytesRead = inFile.read(input)) != -1) {

                    output = cipher.update(input, 0, bytesRead);

                    if (output != null) {



               }//end while

               output = null;

               output = cipher.doFinal();

               if (output != null) {







               SourceFile.delete();//delete the enc file

          } catch (BadPaddingException | IllegalBlockSizeException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IOException ex) {

               Logger.getLogger(Decrypter.class.getName()).log(Level.SEVERE, null, ex);

               if (ex.toString().contains("IOException") || ex.toString().contains("FileNotFound") || ex.toString().contains("AccessDenied") || ex.toString().contains("FileAlreadyExists")) {

                    System.out.println("\nERROR : Failure in decrypting : " + SourceFile.getPath() + "\nError details : " + ex.toString());

                    // An unexpected error has happened , usually file system aaccess permissions,disk full etc

               } else {

                    System.out.println("\nERROR : Failure in decrypting. Please check the algorithm and password.\n" + "Error while decrypting the file : " + SourceFile.getPath() + "\nError details : " + ex.toString());

               try {





                    File f = new File(currentFileWithoutEncExt);

                    boolean success = f.delete();

                    if (success) {

                         System.out.println("\nSuccessfully deleted the partially decrypted file : " + currentFileWithoutEncExt);

                    } else {

                         System.out.println("\nERROR : Error deleting the partially decrypted file : " + currentFileWithoutEncExt);

                         System.out.println("\nYou must manually delete the file.");



               } catch (IOException ex1) {

                    Logger.getLogger(Decrypter.class.getName()).log(Level.SEVERE, null, ex);







Compile and build the jar file.

Copy the jar file in a convenient folder.

Open command prompt

The syntax of the command to run is

java -jar encdec.jar <encrypt|decrypt>

for example

To Encrypt ( assuming desert.jpg and encdec.jar are in the same folder)

java -jar encdec.jar desert.jpg encrypt 12345a

encryption will create the file desert.jpg.enc

To Decrypt ( assuming desert.jpg.enc and encdec.jar are in the same folder)

java -jar encdec.jar desert.jpg.enc decrypt 12345a

decryption will again create the file desert.jpg

That is all.

If you liked this article please do leave a reply and share it with friends.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.