File Encryption and Decryption Simple Example

Encryption and decryption are fundamental requirements of every secure-aware application, therefore the Java platform provides strong support for encryption and decryption through its Java Cryptographic Extension (JCE) framework which implements the standard cryptographic algorithms such as AES, DES, DESede and RSA. This tutorial shows you how to basically encrypt and decrypt files using the Advanced Encryption Standard (AES) algorithm. AES is a symmetric-key algorithm that uses the same key for both encryption and decryption of data.

1. Basic Steps

Here are the general steps to encrypt/decrypt a file in Java:

  • Create a Key from a given byte array for a given algorithm.
  • Get an instance of Cipher class for a given algorithm transformation. See document of the Cipher class for more information regarding supported algorithms and transformations.
  • Initialize the Cipher with an appropriate mode (encrypt or decrypt) and the given Key.
  • Invoke doFinal(input_bytes) method of the Cipher class to perform encryption or decryption on the input_bytes, which returns an encrypted or decrypted byte array.
  • Read an input file to a byte array and write the encrypted/decrypted byte array to an output file accordingly.

Now, let’s see some real examples.

2. The CryptoUtils class

Here’s a utility class that provides two utility methods, one for encrypt a file and another for decrypt a file:

package net.codejava.crypto;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
 * A utility class that encrypts or decrypts a file.
public class CryptoUtils {
    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES";
    public static void encrypt(String key, File inputFile, File outputFile)
            throws CryptoException {
        doCrypto(Cipher.ENCRYPT_MODE, key, inputFile, outputFile);
    public static void decrypt(String key, File inputFile, File outputFile)
            throws CryptoException {
        doCrypto(Cipher.DECRYPT_MODE, key, inputFile, outputFile);
    private static void doCrypto(int cipherMode, String key, File inputFile,
            File outputFile) throws CryptoException {
        try {
            Key secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(cipherMode, secretKey);
            FileInputStream inputStream = new FileInputStream(inputFile);
            byte[] inputBytes = new byte[(int) inputFile.length()];
            byte[] outputBytes = cipher.doFinal(inputBytes);
            FileOutputStream outputStream = new FileOutputStream(outputFile);
        } catch (NoSuchPaddingException | NoSuchAlgorithmException
                | InvalidKeyException | BadPaddingException
                | IllegalBlockSizeException | IOException ex) {
            throw new CryptoException("Error encrypting/decrypting file", ex);

Both the methods encrypt() and decrypt() accepts a key, an input file and an output file as parameters, and throws aCryptoException which is a custom exception written as below:

package net.codejava.crypto;
public class CryptoException extends Exception {
    public CryptoException() {
    public CryptoException(String message, Throwable throwable) {
        super(message, throwable);

This custom exception eliminates the messy throws clause, thus make the caller invoking those methods without catching a lengthy list of original exceptions.

3. The CryptoUtilsTest class

The following code is written for a test class that tests the CryptoUtils class above:

package net.codejava.crypto;
 * A tester for the CryptoUtils class.
public class CryptoUtilsTest {
    public static void main(String[] args) {
        String key = "Mary has one cat1";
        File inputFile = new File("document.txt");
        File encryptedFile = new File("document.encrypted");
        File decryptedFile = new File("document.decrypted");
        try {
            CryptoUtils.encrypt(key, inputFile, encryptedFile);
            CryptoUtils.decrypt(key, encryptedFile, decryptedFile);
        } catch (CryptoException ex) {

This test program simply encrypts a text file, and then decrypts the encrypted file. Note that the key used for encryption and decryption here is a string “Mary has one cat”;

4. Note about key size

The AES algorithm requires that the key size must be 16 bytes (or 128 bit). So if you provide a key whose size is not equal to 16 bytes, a will be thrown. In case your key is longer, you should consider using a padding mechanism that transforms the key into a form in which its size is multiples of 16 bytes. See the Cipher class Javadoc for more details.References


Transporting bike via train from Bhubanswar to Chennai


I just got my bike transported from Bhubanswar to Chennai. I thought of sharing my experience with others, so it might be of some help.

Well there are two way to get your bike transported via a train, either as parcel or luggage. I parceled my bike, which means they will take my bike to Chennai by some train and I can receive the bike in Chennai. Luggage I suppose would be to take the bike on the same train by which you are traveling.

Well the procedure is quite straight forward. The only documents you need are RC Book, identity proof and insurance (carry photocopy of all these documents). Many other private courier services also stress on having a NOC.

To parcel your bike you need to take it to the parcel office. To go to Bhubanswar City parcel office take the first gate of the station, then take the first right, go straight, then there will a V- shaped road ahead, take the right one and keep going straight. You can spot the parcel office on your left hand side. You will find people outside the parcel office who will pack your bike well. They charge 250/- and you can negotiate if you have the quality to do so. Put your bike in the parcel office. There will be a guy to write all the necessary stuff (to and from address) on the bike packing and he will ask you for 20/-. Then there will be an officer present who will make the parcel receipts. Next step is to show you parcel receipt at the cash counter and pay for it. It cost me just 420/- for Bhubanswar to Chennai distance. Get this receipt written on your bike. That’s it. You are done with the parcel.

I booked the bike on Saturday and I reached Chennai on Monday morning. I asked for the parcel office from coolies, headed to it. It’s in the opposite direction to way out of station. I found a guy (Raja) on my way to parcel office and he took my receipt and asked me to follow him. Obviously he was doing it excepting some money in return. I followed him for almost 20-30 min from platform to platform carrying my bag. Then I asked him to hand over the receipt to me and search for the bike and call me when he finds it. I thought I had to pay him anyhow so why take pain J. I just sat on a bench while Raja was searching. As he found it he called me. We took the bike to parcel office to get all the formalities done. They had not yet made an entry of my bike in the registers in Chennai parcel office. It was 5:40 in the morning there was only one officer in the parcel office and he was making all sorts of excuses to avoid the work, again expecting some money to do the work. I talked to Raja and asked him to pay the officer and get it done. As with any government office, the work was done paying some money to the officer. You just need to show the receipt you got from Bhubanswar parcel office to collect the bike. I got my bike out of the station premises. I also took help from Raja to get some petrol from nearby petrol pump. In the end I paid Raja 200/- and drove off my bike. You can save on this 200/- depending on how good you are at it.

Overall the process was quite simple. No pain.

Hope this info is useful for someone.

Multiple back-reference properties with name ‘defaultReference’

If you use @JsonBackReference on your getter/setter method in your project more than twice,you should distinguish them with a specific Reference name.Maybe only one ‘defaultReference’ is allowed in the latest version.


in MovementView.class

public User getUser() {
return user;
in User.class

public User getMovementView() {
return movementView;

How to use WD “My Passport” with Ubuntu Linux

I have bought a new WD my passport ultra. In my laptop have Linux operating system.

When i unboxed my  WD my passport ultra hard disk. and connected it is not able to connect .it saying no permission.

Then i search in google ,but still i have not got any solution.

Then i thought ,i will connect to windows and i will give permission.

step 1 : connect windows PC.

step 2 : open your WD hard disk  properties.then go to sharing

: then click on Advance sharing

step 3 : click on share this folder

step 4: then click on permission button

step 5 : give all permission

step 6 : apply

step 7 : ok

thats it. Now you can connect to Linux ….you can able to transfer and read data using WD hard disk.




Advanced Encryption Standard(AES)

The more popular and widely adopted symmetric encryption algorithm likely to be encountered nowadays is the Advanced Encryption Standard (AES). It is found at least six time faster than triple DES.

A replacement for DES was needed as its key size was too small. With increasing computing power, it was considered vulnerable against exhaustive key search attack. Triple DES was designed to overcome this drawback but it was found slow.

The features of AES are as follows −

  • Symmetric key symmetric block cipher
  • 128-bit data, 128/192/256-bit keys
  • Stronger and faster than Triple-DES
  • Provide full specification and design details
  • Software implementable in C and Java

Operation of AES

AES is an iterative rather than Feistel cipher. It is based on ‘substitution–permutation network’. It comprises of a series of linked operations, some of which involve replacing inputs by specific outputs (substitutions) and others involve shuffling bits around (permutations).

Interestingly, AES performs all its computations on bytes rather than bits. Hence, AES treats the 128 bits of a plaintext block as 16 bytes. These 16 bytes are arranged in four columns and four rows for processing as a matrix −

Unlike DES, the number of rounds in AES is variable and depends on the length of the key. AES uses 10 rounds for 128-bit keys, 12 rounds for 192-bit keys and 14 rounds for 256-bit keys. Each of these rounds uses a different 128-bit round key, which is calculated from the original AES key.

The schematic of AES structure is given in the following illustration −

AES Structure

Encryption Process

Here, we restrict to description of a typical round of AES encryption. Each round comprise of four sub-processes. The first round process is depicted below −

First Round Process

Byte Substitution (SubBytes)

The 16 input bytes are substituted by looking up a fixed table (S-box) given in design. The result is in a matrix of four rows and four columns.


Each of the four rows of the matrix is shifted to the left. Any entries that ‘fall off’ are re-inserted on the right side of row. Shift is carried out as follows −

  • First row is not shifted.
  • Second row is shifted one (byte) position to the left.
  • Third row is shifted two positions to the left.
  • Fourth row is shifted three positions to the left.
  • The result is a new matrix consisting of the same 16 bytes but shifted with respect to each other.


Each column of four bytes is now transformed using a special mathematical function. This function takes as input the four bytes of one column and outputs four completely new bytes, which replace the original column. The result is another new matrix consisting of 16 new bytes. It should be noted that this step is not performed in the last round.


The 16 bytes of the matrix are now considered as 128 bits and are XORed to the 128 bits of the round key. If this is the last round then the output is the ciphertext. Otherwise, the resulting 128 bits are interpreted as 16 bytes and we begin another similar round.

Decryption Process

The process of decryption of an AES ciphertext is similar to the encryption process in the reverse order. Each round consists of the four processes conducted in the reverse order −

  • Add round key
  • Mix columns
  • Shift rows
  • Byte substitution

Since sub-processes in each round are in reverse manner, unlike for a Feistel Cipher, the encryption and decryption algorithms needs to be separately implemented, although they are very closely related.

AES Analysis

In present day cryptography, AES is widely adopted and supported in both hardware and software. Till date, no practical cryptanalytic attacks against AES has been discovered. Additionally, AES has built-in flexibility of key length, which allows a degree of ‘future-proofing’ against progress in the ability to perform exhaustive key searches.

However, just as for DES, the AES security is assured only if it is correctly implemented and good key management is employed.