Encrypt and Decrypt a file in java

This article will describe how to encrypt and decrypt a file in java. We shall demonstrate file encryption using example source code.This source code has been tested to work not only on text files but also on audio video files and images.The name of the file, encrypt/decrypt and the password to be used for the encryption shall be passed as arguments to the .jar file.

This encryption occurs by writing encrypted data back to the place from where it was read,thus after encryption there is no trace of non encrypted data on your disk. The program doesn’t leave the non encrypted data on the disk by creating a new encrypted file,instead writes the encrypted data back from where read.This is accomplished by the use of random access file and filepointers.

Thus file recovery softwares will not be able to recover the plain non encrypted files from the disk.

Source code of the Encrypter Class

The encrypter class has a Encrypt function which accepts the source file name and the password as arguments. the function produces the encrypted file with a the same name but a .enc extension appended to the filename.

package encdecexample;

import java.awt.Color;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
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 Encrypter {

public static void Encrypt(File SourceFile, char[] PassWord) {

RandomAccessFile FileToReadWrite = null;

int MainBufferSize = 4096;


try {

String SourceFilePath = SourceFile.getPath();

FileToReadWrite = new RandomAccessFile(SourceFilePath, "rw");

//////////////////////////

char[] passWord = PassWord;

byte[] keyData = null;


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

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

Cipher cipher = null;

cipher = Cipher.getInstance("BlowFish");

cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

byte[] input = new byte[MainBufferSize];

byte[] output = null;

int bytesRead;

//start while

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

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

//we have to come to the begining of read position of the block read

FileToReadWrite.seek(FileToReadWrite.getFilePointer() - bytesRead);

if (output != null) {

//cipher output written at same block from where it was read

//this way we prevent any file recovery software from reading

//the plain file,as it is overwritten with cipher data.

FileToReadWrite.write(output);

}

}//end while

output = null;

output = cipher.doFinal();

if (output != null) {

FileToReadWrite.write(output);

}

FileToReadWrite.getChannel().close();

FileToReadWrite.close();

//The SourceFile Path has the encrypted data

//now we simply rename the source file to .enc

SourceFile.renameTo(new File(SourceFilePath + ".enc"));



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

Logger.getLogger(Encrypter.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 encrypting : " + 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 Encrypting. Please check the algorithm and password.\n" + "Error while encrypting the file : " + SourceFile.getPath() + "\nError details : " + ex.toString());


}

return;

}

}
}

In the next page you will read about the source code of the main class and passing of the file name and other arguments to the .jar file


Continue reading the remaining 2 pages of the article through page links below ....

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.