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
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...
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?
ReplyDeleteIt 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...
hello,
ReplyDeletei 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)
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.
Deletetry adding this to your code (main method)
ReplyDeletetry {
Field field = Class.forName("javax.crypto.JceSecurity").
getDeclaredField("isRestricted");
field.setAccessible(true);
field.set(null, java.lang.Boolean.FALSE);
} catch (Exception ex) {
ex.printStackTrace();
}
didn't work
Deleteit can not decrypt file
ReplyDelete