Encrypt and Decrypt Images Using Java

Hi, Most of you would find it useful to Encrypt a special picture of yours such that only you can view it. By using JCE(Java Cryptography Extension) classes, this becomes very simple. As I have already done before using Java to encrypt a String is very simple. If you are new to this, please read the article which I had already posted named "Java Encryption and Decryption"
at "http://ruchiram4.blogspot.com/2009/04/java-encryption-and-decryption.html"
Also, you need to have a basic understanding of Java IO. If you are new, it is better to read the Sun Java tutorial on IO.

Before we move on, lets recall the basic steps in Encrypting plaintext.



1. Creating an instance of "Cipher" object and setting the mode of Encryption (Eg: AES, DES)

2. Generating a key by using a KeyGenerator object.

3. Setting the mode of Cipher operation on the Cipher object. As we intent to Encrypt, we simply set it by setting a property of Cipher object by calling its "init" method.

4. Calling the "doFinal" method of the Cipher object




Now, Encrypting an image is pretty much similar except, we first need to read the image from the hard disk as a File Input. Initializing steps are the same for the Cipher object and Key.
We first initialize a Cipher object for Encrypting as we have done. We pass the Cipher object with the necessary key used for Encryption. This can be done by calling the "init" method of the Cipher object and passing the necessary parameters.
Once we initialize a Cipher Object, we pass the initialized Cipher object to a "CipherInputStream" object. (A CipherInputStream object is an object provided by JCE. We need to show which file to read from and which cipher object to use). Then we can simply read through the CipherInputStream object and Encryption is done while reading from the CipherInputStream object.



Creating a Cipher object and a Key

Cipher cipher=Cipher.getInstance("AES");
KeyGenerator keyGen=KeyGenerator.getInstance("AES");
Key key=keyGen.generateKey();

Now, we initialize the Cipher object

cipher.init(Cipher.ENCRYPT_MODE, key);

Create a CipherInputStream object by passing the realavent image to be Encrypted along with the Cipher object which we initilalized

cipherIn=new CipherInputStream(new FileInputStream(new File("./image.jpg")), cipher);

Now, we create an output stream for writing back the Encrypted image to disk

FileOutputStream fos=new FileOutputStream(new File("./filename.jpg"));

Now, we read from the CipherInputStream object just like reading from a FileInputStream.
We simply write back the Encrypted file to the Disk

int i;
while((i=cipherIn.read())!=-1){
fos.write(i);
}

NOTE: It is more efficient to use Buffer objects when doing file IO. But, in order to make things clear and simple, I ommited them.

Decrypting is very similar. You first need to call make another Cipher object and call init method with parameter for Decryption. This can be done as follows

cipher.init(Cipher.DECRYPT_MODE, key);

NOTE: YOU MUST USE THE SAME KEY GENERATED WHICH WAS USED FOR ENCRYPTING. OTHERWISE, YOU MAY NOT BE ABLE TO DECRYPT IT BACK.

Now, we can use a CipherInputStream object to read the Encrypted image. Since, we have set the mode to decryption, the CipherInputStream would basically decrypt as it reads from the Encrypted image.

Comments

suji said…
hai,
This helps me to encrypt a image but the decryption is not working properly will u pls guide me for that.



suji
ruchira said…
Hi Suji,

I think you are not using the same key for decryption. You MUST use the same key for encryption and decryption. So, you must save the key in some form and use it later for decryption.

Take the following code segment for an example.

KeyGenerator keyGen=KeyGenerator.getInstance("AES");
Key key1=keyGen.generateKey();
Key key2=keyGen.generateKey();

When you use the generateKey() method consecutively, it generates a randomn key. It will be different from the first key. So, if you call the generateKey() method from another place, the key would be different.

Therefore, you must store the key in a different place if you wish to decrypt the ciphertext.
Unknown said…
hey ruchira,
I'd like to ask how do you do make the key not random , becouse if you want to store the key or decipher it on other pc that would make it impossible.
aditee gautam said…
This comment has been removed by the author.
aditee gautam said…
This comment has been removed by the author.
aditee gautam said…
This comment has been removed by the author.
Vijay said…
This comment has been removed by the author.
Vijay said…
Hey, thanx a lot for this helpful writing this helpful post. But, I wanted to know how can we save the key(the one used in encryption) so that it can be later used for decryption.
Thanx in advance.
Nitish said…
hai..
This helps me lot for encrypting my image.But i am unable to decrypt it back and if possible please tell how to store the Key that has been used during the encryption process.
This would be very helpfull to me
Thanxx
Hai..i want to ask question..can i convert the image to byte array and then i convert to string before i encrypt it?
Unknown said…
I have written encryption and decryption for image in java. Encryption using getrgb() followed by shuffling of pixel and setrgb(). decryption doesn't retrieve original image. could anyone help me?
Unknown said…
i hv write code like this ..
still its hav no clear pic
pls tell me wts problem

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.imageio.stream.FileImageInputStream;

public class encrypt {

encrypt() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException
{
Cipher cipher=Cipher.getInstance("AES");
KeyGenerator keygen=KeyGenerator.getInstance("AES");
Key key=keygen.generateKey();
cipher.init(Cipher.ENCRYPT_MODE,key);
CipherInputStream cin=new CipherInputStream(new FileInputStream(new File("./11.jpg")),cipher);;

FileOutputStream fos=new FileOutputStream(new File("./12.JPEG"));
int i;
while((i=cin.read())!=-1){
fos.write(i);
}
//******************************decrypt*****************
Cipher cipher1=Cipher.getInstance("AES");

cipher1.init(Cipher.DECRYPT_MODE,key);
CipherInputStream cin1=new CipherInputStream(new FileInputStream(new File("./12.JPEG")),cipher1);

FileOutputStream fos1=new FileOutputStream(new File("./13.JPEG"));
int i1;
while((i1=cin1.read())!=-1){
fos1.write(i);
}









}



public static void main(String[] args) {
try {
encrypt s=new encrypt();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}




}

}
Unknown said…
This comment has been removed by the author.
Unknown said…
this is program working correctly.you will do it.


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;

/**
*
* @author hi
*/
public class images {


public static void encryption() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException
{

try
{
Cipher cipher=Cipher.getInstance("AES");
KeyGenerator kg=KeyGenerator.getInstance("AES");
Key key=kg.generateKey();

cipher.init(Cipher.ENCRYPT_MODE, key);

CipherInputStream cipt=new CipherInputStream(new FileInputStream(new File("D:\\images\\Winter.jpg")), cipher);

FileOutputStream fip=new FileOutputStream(new File("D:\\ji.jpg"));

int i;
while((i=cipt.read())!=-1)
{
fip.write(i);

}



cipher.init(Cipher.DECRYPT_MODE, key);

CipherInputStream ciptt=new CipherInputStream(new FileInputStream(new File("D:\\ji.jpg")), cipher);

FileOutputStream fop=new FileOutputStream(new File("D:\\kj.jpg"));

int j;
while((j=ciptt.read())!=-1)
{
fop.write(j);
}




}
catch(Exception e)
{
e.printStackTrace();
}


}





public static void main(String[] args)
{
try
{
images.encryption();

}catch(Exception e)
{
e.printStackTrace();
}

}
}
Brij said…
Hey Ruchira, Need a bit of help...

I am able to do encryption n decryption. After the file is decrypted, its directly written to the File itself using FileOutputStream.

However, I want after the file is decrypted, how can I get a File object?
For example
File myDecryptedFile = ........

Please give me some idea about it. The reason is that I am encrypting and decrypting a xml file. So after property file is decrypted, I want to use it on the fly to extract some values....

Thanks in advance!
Unknown said…
Hi sir,

how to store a image in oracle database using jsp or java

plz help me
Unknown said…
The code works great!! Thanks a lot. But how to decide on the rounds of AES ?? Is there any option to change the number of rounds ?? Please help!!!
Unknown said…
Its working great.But how can i store in database
ankit said…
Great post sir. Can there be any way to encrypt/decrypt the sound files.If yes please provide source code.It will be very helpful.
Unknown said…
hey ruchira,
im working on my final year project on keyless image encryption. im using SDS algorithm. can i get some idea how i should proceed with the project??? im thinking to use java lang for it... kindly help us..
waiting for your reply...
Unknown said…
Thanks for giving solution but this code only encrypt image. but not decrypt in original image
Aliya Manasa said…
I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.
python Training in Pune
python Training in Chennai
python Training in Bangalore
Unknown said…
This is a nice post in an interesting line of content.Thanks for sharing this article, great way of bring this topic to discussion.
Best Devops Training in pune
Devops Training in Bangalore
Power bi training in Chennai
priya said…
Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.
Data Science Tutorial
Data Science training in anna nagar
Data science training in jaya nagar
Data science training in pune
Data Science Training in Marathahalli
Data science training in kalyan nagar
Jaweed Khan said…
Thanks For sharing Your Information The Information shared Is Very Valuable Please Keep Updating Us Python Online Course Hadoop Online Course Data Science Online Course Aws Online Course
anusha said…

MEAN Stack Training in Chennai MEAN Stack Training in Chennai with real time projects. We are Best MEAN Stack Training Institute in Chennai. Our Mean Stack courses are taught by Industrial Experts which would help you to learn MEAN Stack development from the scratch.


Full Stack Development Training in Chennai Searching for Full Stack Development training in chennai ? Bita Academy is the No 1 Training Institute in Chennai. Call for more details.
jeni said…
Wow, amazing weblog format! How lengthy have you been running a blog for? you make running a blog look easy. The total glance of your website is wonderful, let alone the content!


angular js training in chennai

angular js training in velachery

full stack training in chennai

full stack training in velachery

php training in chennai

php training in velachery

photoshop training in chennai

photoshop training in velachery
Reshma said…

This post is so interactive and informative.keep update more information...
Artificial Intelligence Course in Bangalore
Artificial Intelligence course in Pune
David Fincher said…
This post is so interactive and informative.keep update more information...
Android Training in Anna Nagar
Android Training in Chennai
Matt Reeves said…
This post is so interactive and informative.keep update more information...
DevOps course in Tambaram
DevOps Training in Chennai
Thanks for sharing your info. I truly appreciate your efforts and I am waiting for your next post thank you once again.
SAP ABAP On HANA Training
Informatica Data Quality Training

Popular posts from this blog

Build your own Network sniffer

ASP Response.Write newline