Friday, April 4, 2014
Today I will show you how to do 256bits AES encryption and decryption of a file in Java. You can write codes for AES - 128bits without doing any extra configuration but to use AES - 256bits first of all you have to carry out the following steps. This is because when you install JDK it has default strength which is Strong but you will have to increase it to Unlimited.

  • Download the right version of Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files. For JDK7 download it from here
  • Extract the archive and copy the two JAR files (local_policy.jar and US_export_policy.jar) and paste it in the directory JAVA_HOME/jre/lib/security for example C:/Program Files/Java/jdk1.7.0/jre/lib/security
In order to perform the encryption, first of all a KeYGenerator instance is created for AES key and the key length is set to 256 using init() method. Then the key is generated which is used for initializing Cipher instance. The generated key is saved to the output file(which will contain encrypted contents) to be used later. The cipher instance is used by the CipherOutputStream to encrypt and write the contents in encrypted format.
    In order to decrypt the encrypted file, initially the key that was saved is read from the file. Then that key is used for initializing Cipher for decryption. The cipher instance is used by CipherInputStream to read encrypted contents and generate the original contents which are then written to file using FileOutputStream.
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
package com.javaingrab.security.encrypt;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;


public class AESEncryptor {

 public void encrypt(String fname) throws Exception{
  KeyGenerator keyGen = KeyGenerator.getInstance("AES");
  keyGen.init(256);  //using AES-256
  SecretKey key = keyGen.generateKey();  //generating key
  Cipher aesCipher = Cipher.getInstance("AES");  //getting cipher for AES
  aesCipher.init(Cipher.ENCRYPT_MODE, key);  //initializing cipher for encryption with key
  
  //creating file output stream to write to file
  try(FileOutputStream fos = new FileOutputStream(fname+".aes")){
   //creating object output stream to write objects to file
   ObjectOutputStream oos = new ObjectOutputStream(fos);
   oos.writeObject(key);  //saving key to file for use during decryption

   //creating file input stream to read contents for encryption
   try(FileInputStream fis = new FileInputStream(fname)){
    //creating cipher output stream to write encrypted contents
    try(CipherOutputStream cos = new CipherOutputStream(fos, aesCipher)){
     int read;
     byte buf[] = new byte[4096];
     while((read = fis.read(buf)) != -1)  //reading from file
      cos.write(buf, 0, read);  //encrypting and writing to file
    }
   }
  }
  
 }
 
 public void decrypt(String fname)throws Exception{
  SecretKey key =null;
    
  //creating file input stream to read from file
  try(FileInputStream fis = new FileInputStream(fname)){
   //creating object input stream to read objects from file
   ObjectInputStream ois = new ObjectInputStream(fis);
   key = (SecretKey)ois.readObject();  //reading key used for encryption
   
   Cipher aesCipher = Cipher.getInstance("AES");  //getting cipher for AES
   aesCipher.init(Cipher.DECRYPT_MODE, key);  //initializing cipher for decryption with key
   //creating file output stream to write back original contents
   try(FileOutputStream fos = new FileOutputStream(fname+".dec")){
    //creating cipher input stream to read encrypted contents
    try(CipherInputStream cis = new CipherInputStream(fis, aesCipher)){
     int read;
     byte buf[] = new byte[4096];
     while((read = cis.read(buf)) != -1)  //reading from file
      fos.write(buf, 0, read);  //decrypting and writing to file
    }
   }
  }
 
 }
 
 public static void main(String[] args) throws Exception {
  AESEncryptor obj = new AESEncryptor();
  obj.encrypt("clear.txt");
  obj.decrypt("clear.txt.aes");
 }

}
NOTE : You will need the clear.txt file which is the file to be encrypted to execute the code. The encrypted file will be placed in the same directory with same name as original file but with an extension ".aes". The decrypted file will have the same name as the encrypted file but with extension ".dec", this is done deliverately for you people to check whether the original conetents are same as the decrypted one.
-------------------------------------------------------------------------------------------------------------------------
Download Links
-------------------------------------------------------------------------------------------------------------------------
DOWNLOAD the source from Mediafire

6 comments:

  1. It probably is a stupid question... But why would you store the key along with the encrypted file? Isn't it easy for someone who could have access to the file to realize that the file structure is composed of the key + content?
    It wouldn't allow the operating system or any user to open it as I understood it, but wouldn't it be easy for a experienced user with bad intentions to figure it out alone?
    Sorry for the eventual English mistakes...

    ReplyDelete
  2. hello,
    i got the following errors, please help
    Exception in thread "main" java.security.InvalidKeyException: Illegal key size or default parameters
    at javax.crypto.Cipher.checkCryptoPerm(Cipher.java:1011)
    at javax.crypto.Cipher.implInit(Cipher.java:786)
    at javax.crypto.Cipher.chooseProvider(Cipher.java:849)
    at javax.crypto.Cipher.init(Cipher.java:1213)
    at javax.crypto.Cipher.init(Cipher.java:1153)
    at com.javaingrab.security.encrypt.AESEncryptor.encrypt(AESEncryptor.java:22)
    at com.javaingrab.security.encrypt.AESEncryptor.main(AESEncryptor.java:71)

    ReplyDelete
    Replies
    1. hi, I have seen this error before. But if you use 256 bit AES you need extra jar file that I did't remember its name. So Default 128 if you use you can't see this error. I hope this help you.

      Delete
  3. try adding this to your code (main method)

    try {
    Field field = Class.forName("javax.crypto.JceSecurity").
    getDeclaredField("isRestricted");
    field.setAccessible(true);
    field.set(null, java.lang.Boolean.FALSE);
    } catch (Exception ex) {
    ex.printStackTrace();
    }

    ReplyDelete

Total Pageviews

Followers


Labels

Popular Posts

free counters