Friday, March 15, 2013

Simple Image Encryption and Decryption

             In this blog, I am explaining how to encrypt image in a simple way. This mechanism uses very simple logic, ie, it encrypts the pixels than encrypting the whole image file. So first I am giving the theoretical explanation. Basically an image contains lot of pixels, so as i told earlier our encryption mechanism encrypts only the pixels.For encryption and decryption it uses the same key. Based on the key, every pixel value of the image will be XOR-ed and that XOR-ed value will be replaced in the encrypted image. The decryption and encryption process is the same.

This is only for 'bmp' images.



import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.security.SecureRandom;
import javax.imageio.ImageIO;

public class ImageEncryptAndDecrypt {
    public static void main(String s[]){
    String sPath=s[0],dPath=s[1],password=s[2];
    StringBuilder sb=new StringBuilder();
    char st; 
    int value;
    try{
        for (int i = 0; i < password.length(); i++) {
             st=password.charAt(i);
             value=(int)st;
             sb.append(value);
        }
    SecureRandom sr= SecureRandom.getInstance("SHA1PRNG");
    sr.setSeed(sb.toString().getBytes());
    BufferedImage FSImg=ImageIO.read(new File(sPath));  
        for (int w = 0; w < FSImg.getWidth(); w++) {
            for (int h = 0; h < FSImg.getHeight(); h++) {
                Color color=new Color(FSImg.getRGB(w, h));
                Color newColor=new Color(color.getRed()^sr.nextInt(255), color.getGreen()^sr.nextInt(255), color.getBlue()^sr.nextInt(255));
                FSImg.setRGB(w, h, newColor.getRGB());
            }
        }
    System.out.println("Process Completed!!..");
    ImageIO.write(FSImg, "bmp", new File(dPath));
    System.out.println("Wrote to "+dPath);
    }catch(Exception e){
    e.printStackTrace();}
    }
    
}

Usage: Save the code with the file name 'ImageEncryptAndDecrypt.java'
In the command prompt,
 javac ImageEncryptAndDecrypt.java
 java ImageEncryptAndDecrypt <source file> <destination file> <password>
 Example: Let the source image be c:/picture.bmp, the destination be c:/picture2.bmp and the password be 'passwordToSecureMyImage', then
 java ImageEncryptAndDecrypt c:/picture.bmp c:/picture2.bmp passwordToSecureMyImage

Source Image:

Encrypted Image:
Decrypted Image:


Code Explanation:

         Pseudo Random Numbers are generated using SHA1PRNG algorithm. SecureRandom is used to generate random numbers. The password is converted to ascii code, that value is given as seed for the random number generation. Every pixel in the image is retrieved, and the RGB values are XOR-ed with the random value. The new image is created using the newly obtained pixel values. 
      
       Code for encryption and decryption is the same.


Thank You.