RC4 image encryption/Decryption - java

I am trying to carry out Image Encryption/Decryption process.The code is running without any errors but the output is not correct. I am unable to determine where I am going wrong.
The same code is used for both encryption and decryption. The only difference being the change of path as input.
PS: I am a new to java and image handling concepts.
package crptography;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageOutputStream;
public class RC4Final {
public static int s[]=new int[256];
public static int t;
public static void main(String args[])throws IOException
{
int i=0,j=0,temp=0;
String key;
int k[]=new int[256];
String path = "C:\\rc4\\Koala.jpg";
//String path = "C:\\rc4\\encrypted.jpg";
BufferedImage old_img = null;
try { old_img = ImageIO.read(new File(path));}
catch (Exception e) { e.printStackTrace(); }
BufferedImage new_img = new BufferedImage( old_img.getWidth(),
old_img.getHeight(),
BufferedImage.TYPE_INT_RGB);
int n = new_img.getWidth();
int m = new_img.getHeight();
//initialization array s
DataInputStream in=new DataInputStream(System.in);
System.out.print("\n\nENTER KEY TEXT\t\t");
key = in.readLine();
char keyc[]=key.toCharArray();
int keyi[]=new int[key.length()];
for(int a=0;a<key.length();a++)
{
keyi[a]=(int)keyc[a];
}
for( i=0;i<255;i++)
{
s[i]=i;
k[i]=keyi[i%key.length()];
}
//end
//initial permutation of array s
j=0;
for( i=0;i<255;i++)
{
j = (j+s[i]+k[i])%256;
temp = s[i];
s[i]=s[j];
s[j]=temp;
}
//end
//encryption start
i=0;
j=0;
int t1;
int red,green,blue,cr,cg,cb;
int rgb ;
for ( i = 0; i < n; ++i)
{
for ( j = 0; j < m; ++j)
{
rgb = old_img.getRGB(i,j);
blue = (rgb)&0xFF;
green = (rgb>>8)&0xFF;
red = (rgb>>16)&0xFF;
t1= permutate(i,j);
cr=s[t1]^red;
t1= permutate(i,j);
cg=s[t1]^green;
t1=permutate(i,j);
cb=s[t1]^blue;
int rgb1=new Color(cr, cg, cb).getRGB();
new_img.setRGB(i, j, rgb1);
}
}
saveToFile( new_img, new File( "C:\\rc4\\encrypted.jpg" ) );
//saveToFile( new_img, new File( "C:\\rc4\\decrypted.jpg" ) );
}
//permute method
public static int permutate(int x,int y)
{
int temp;
x=(x+1)%256;
y=(y+s[x])%256;
temp = s[x];
s[x]=s[y];
s[y]=temp;
t = s[(s[x]+s[y])%256];
return t;
}
//end
public static void saveToFile( BufferedImage img, File file ) throws IOException {
ImageWriter writer = null;
java.util.Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
if( iter.hasNext() ){
writer = (ImageWriter)iter.next();
}
ImageOutputStream ios = ImageIO.createImageOutputStream( file );
writer.setOutput(ios);
ImageWriteParam param = new JPEGImageWriteParam( java.util.Locale.getDefault() );
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT) ;
param.setCompressionQuality(0.98f);
writer.write(null, new IIOImage( img, null, null ), param);
}
}

Related

Given a 200x200 RGB PNG file , extract the 2 least significant bits of each pixel data to create a new 200x200 image saved to disk

Here is the code, I am getting black image.
package example;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class imageCopy {
public static void main(String[] args) {
BufferedImage img = null;
File f = null;
try {
f = new File("E:\\unnamed.png");
img = ImageIO.read(f);
}catch(Exception e) {
e.printStackTrace();
}
int width = img.getWidth();
int height = img.getHeight();
for(int i=0;i<height;i++) {
for(int j=0;j<width;j++) {
int p = img.getRGB(j, i);
int k = p << -2 >>> -2;
img.setRGB(j, i, k);
}
}
try {
f = new File("E:\\Output.png");
ImageIO.write(img, "png", f);
}catch(Exception e) {
e.printStackTrace();
}
}
}
png

Dereferncing Error In Java Array HW

I'm getting an error about dereferencing in the following code (I've commented out where it gets caught up)
The main method works fine, but the Mply method is causing me lots of headaches. Hope this is sort of clear.
//multiply matrixes
import java.io.FileInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.*;
import java.util.StringTokenizer;
public class Assignment1 {
public static void main(String[] args){
int a=5;
int b=2;
int x[][] = new int[a][b];
for(int i=0;i<a;i++)
for(int j=0;j<b;j++)
x[i][j]=0;
System.out.println(x[1][1]);
/*
for(int j= 0; j<
for (int i = 0; i < array.length; i++)
array[i] = s.nextInt();
*/
// read from file
FileInputStream fstream=null;
try{
fstream = new FileInputStream("C:\\javastuff\\principles\\input.txt");
}
catch (Exception e){
System.out.println(e.getMessage());
}
try (BufferedReader br = new BufferedReader(new InputStreamReader(fstream))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
/* StringTokenizer tokenizer = new StringTokenizer(line, " ");
while (tokenizer.hasMoreElements()) {
// parse each integer in file
int i = Integer.parseInt(tokenizer.nextToken());
System.out.println("Number " + i);
}
*/
}
br.close();
}
catch(Exception e){
}
// write to file
BufferedWriter outputWriter = null;
try{
outputWriter = new BufferedWriter(new FileWriter("C:\\javastuff\\principles\\output.txt"));
for (int i = 0; i < a; i++) {
outputWriter.write(Integer.toString(x[i][0]));
outputWriter.newLine();
}
outputWriter.flush();
outputWriter.close();
}
catch (Exception e){
}
}
public static void Mply(int x[][], int a, int b){ //multiplies arraries and checks if they are same values
int aRows = a.length;
int aColumns = a[0].length;//starts dereferecning herer
int bRows = b.length;
int bColumns = b[0].length;
for (int i=0; i<a; ++i)
for (int j=0; j<b; ++j)
for (int k=0; k<a[0][0].length(); ++k)
x[i][k] += a[i][k] * b[k][j];
}
}
based on the method header for Mply
public static void Mply(int x[][], int a, int b)
The type of x is int[][], the type of a is int, and the type of b is int. Specifically, note that a and b are not arrays.
Thus trying to access them as arrays by using a[0] is illegal.
If you want a and b to be 2-dimensional arrays, you have to update your method header to say that.
public static void Mply(int[][] x, int[][] a, int[][] b)

how to convert image from coordinate x,y values in java?

In my project we need spot the difference among a set of images,so at first i tried it for three images and I have written code to differentiate between three images based on RGB values.I have stored coordinate values from this values i need to get a image.
import java.io.*;
import java.awt.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
class spe
{
public static void main(String args[])
throws IOException
{
long start = System.currentTimeMillis();
int q=0;
File file1 = new File("filename.txt");
FileWriter fw = new FileWriter(file1.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
File file= new File("2010.png");
BufferedImage image = ImageIO.read(file);
int width = image.getWidth(null);
int height = image.getHeight(null);
int[][] clr= new int[width][height];
File files= new File("2011.png");
BufferedImage images = ImageIO.read(files);
int widthe = images.getWidth(null);
int heighte = images.getHeight(null);
File file2=new File("2009.png");
BufferedImage image2=ImageIO.read(file2);
int wid=image2.getWidth(null);
int heig=image2.getHeight(null);
int[][] colo=new int[wid][heig];
int[][] clre= new int[widthe][heighte];
int smw=0;
int smh=0;
int p=0;
// bw.write("hai");
//CALUCLATING THE SMALLEST VALUE AMONG WIDTH AND HEIGHT
if(width>widthe)
{
smw =widthe;
}
else
{
smw=width;
}
if(height>heighte)
{
smh=heighte;
}
else
{
smh=height;
}
//CHECKING NUMBER OF PIXELS SIMILARITY
for(int a=0;a<smw;a++)
{
for(int b=0;b<smh;b++)
{
clre[a][b]=images.getRGB(a,b);
clr[a][b]=image.getRGB(a,b);
colo[a][b]=image2.getRGB(a,b);
if(clr[a][b]==clre[a][b] && colo[a][b]==clre[a][b])
{
p=p+1;
bw.write("\t");
bw.write(Integer.toString(a));
bw.write("\t");
bw.write(Integer.toString(b));
bw.write("\n");
System.out.println(a+"\t"+b);
}
else
q=q+1;
}
}
float w,h=0;
if(width>widthe)
{
w=width;
}
else
{
w=widthe;
}
if(height>heighte)
{
h = height;
}
else
{
h = heighte;
}
float s = (smw*smh);
//CALUCLATING PERCENTAGE
float x =(100*p)/s;
System.out.println("THE PERCENTAGE SIMILARITY IS APPROXIMATELY ="+x+"%");
long stop = System.currentTimeMillis();
System.out.println("TIME TAKEN IS ="+(stop-start));
System.out.println("NO OF PIXEL GETS VARIED:="+q);
System.out.println("NO OF PIXEL GETS MATCHED:="+p);
}
}

LZW Encoder Decoder - Symbol Table

My LZW Compression works when I use a symbol table(dictionary) of length 256, Encoder and Decoder both work with 256 and everything works fine but when I increase this number for example to 512, 1024, 4096 the decoded file output is not the same with the first input file...Any hints?
Source Code:
LZWEncoder.java:
import java .io .*;
public class LZWEncoder
{
public static void main ( String [] args )
throws FileNotFoundException , IOException
{
File file = new File ("calgary/book1");
File fileOut = new File ( "calgary/book1_enc");
FileInputStream reader = new FileInputStream ( file );
FileOutputStream writer = new FileOutputStream ( fileOut );
int size_st;
long file_size;
file_size = file.length();
size_st = (int) file_size/1024;
System.out.println("File size " + file_size + " Sysmbol tree" + size_st);
if (size_st < 256)
size_st = 256;
else if (size_st < 512)
size_st = 512;
else if (size_st < 1024)
size_st = 1024;
else if (size_st < 2048)
size_st = 2048;
else
size_st = 4096;
byte[] size_stInBytes = (Integer.toString(size_st)+"\n").getBytes();
// writer.write(size_stInBytes);
System.out.println("File size " + file_size + " Sysmbol tree " + size_st);
// input stream with lookahead
LookAheadIn in = new LookAheadIn ( file );
LZWst st = new LZWst (4096); // specialised ST
while (! in.isEmpty ())
{
int codeword = st.getput (in );
writer.write ( codeword );
}
writer.close ();
reader.close ();
}
}
LZWDecoder.java:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
public class LZWDecoder
{
public static void main ( String [] args )
throws FileNotFoundException , IOException
{
File file = new File ("calgary/book1_enc");
Scanner first_line = new Scanner("calgary/book1_enc");
File fileOut = new File ( "calgary/book1_dec2");
FileInputStream reader = new FileInputStream ( file );
FileOutputStream writer = new FileOutputStream ( fileOut );
String size_st;
size_st =first_line.nextLine();
System.out.println(" Sysmbol tree " + size_st);
String [] st = new String [4096];
int i;
for (i=0; i <128; i++)
st[i] = Character.toString (( char ) i);
String prev = "";
int codeword ;
while (( codeword = reader.read())!= -1)
{
String s;
if ( codeword == i) // Tricky situation !
s = prev + prev.charAt(0);
else
s = st[codeword ];
for (int j = 0; j<s.length(); j++)
writer.write(s.charAt (j));
if ( prev.length() > 0 && i < 4096 )
st[i++] = prev + s.charAt(0);
prev = s;
}
writer.close();
reader.close();
}
}
LZWst.java:
import java.io.FileNotFoundException;
import java.io.IOException;
public class LZWst
{
private int i; // next codeword to assign
private int codeword ; // codeword to return
private Node [] roots ; // array of TSTs
private int st_size;
public LZWst (int st_sz)
{
st_size = st_sz;
roots = new Node [128];
for (i=0; i <128; i++) // init with ASCII
roots [i] = new Node (( char ) i,i);
}
private class Node
{ // standard node code
Node (int c, int codeword )
{
this .c = c;
this . codeword = codeword ;
}
int c;
Node left , mid , right ;
int codeword ;
}
public int getput ( LookAheadIn in)
throws FileNotFoundException , IOException
{
int c = in. readChar ();
if ( c == -1) return -1; // EOF
roots [c] = getput (c, roots [c],in );
in. backup ();
return codeword ; // longest prefix
}
public Node getput ( int c, Node x, LookAheadIn in)
throws FileNotFoundException , IOException
{ // recursive search *and* insert
if (x== null ) {
if (i<st_size){
x = new Node (c,i++);
System.out.println("Value of i: " + i);
}
return x;
}
if (c<x.c) x. left = getput (c,x.left ,in );
else if (c>x.c) x. right = getput (c,x.right ,in );
else {
int next = in.readChar();
codeword = x. codeword ;
x.mid = getput (next ,x.mid ,in );
}
return x;
}
}
LookAheadIn.java:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class LookAheadIn
{
private FileInputStream in = null ;
private int last ;
private boolean backup = true ;
public LookAheadIn ( File file )
throws FileNotFoundException , IOException
{
in = new FileInputStream ( file );
last = in. read ();
backup = true ;
}
public void backup () { backup = true ; }
public int readChar () throws FileNotFoundException , IOException
{
if (! backup ) last = in. read();
backup = false ;
return last ;}
public boolean isEmpty(){ return last == -1; }
}
You're reading bytes, they can't store larger values. If you want to do LZW with codes larger than 255, you'll need to either encode bit streams, or for testing (as a temporary hack) write two byte words (unsigned int of size 16).
Replace
writer.write ( codeword );
with
writer.write ( codeword>>8 );
writer.write ( codeword&0xff );
and it check if it works. If it does, you can spend some time implementing a bit based stream. You'll need to update the reader and decoder too.

Cannot read image in jar

i have written a program to encrypt an image in Netbeans. The program works fine when running from netbeans but when i build it into a .jar file its not working, it cannot read the image even though i placed the image file in the same folder as the .jar file.
package test;
import java.io.IOException;
import java.io.File;
/**
*
* #author AMaR
*/
public class Test {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException, Exception {
File EnImage = new File("encrypted.png");
File DeImage = new File("decrypted.png");
int[] pixels;
LoadImage l = new LoadImage();
l.load();
pixels= l.getImagePixels();
RC4New rc4 = new RC4New();
int key[]= {13,2,4,6,};
// int data[]={5,10,90,5};
rc4.KSA(key);
int[] text = rc4.PRNG(pixels);
l.write((int)512,(int)512,text,EnImage);
//RC4New rc41 = new RC4New();
rc4.KSA(key);
int[] text1 = rc4.PRNG(text);
l.write((int)512,(int)512,text1,DeImage);
/* for(int i=0;i<text.length;i++){
System.out.println(text[i]);
}
RC4New rc41 = new RC4New();
rc4.KSA(key);
int[] text1 = rc4.PRNG(text);
for(int i=0;i<text1.length;i++){
System.out.println(text1[i]);
}
*/
System.out.println("length:"+pixels.length);
// l.write((int)512,(int)512,text);
// TODO code application logic here
}
}
//encryption
package test;
/**
*
* #author AMaR
*/
public class RC4New {
int state[] = new int[256];
int j;
/**
*
* #param key
*/
public void KSA(int[] key){
int tmp;
for (int i=0; i < 256; i++) {
state[i] = i;
}
j=0;
for (int i=0; i < 256; i++) {
j = (j + state[i] + key[i % key.length]) % 256;
tmp = state[i];
state[i] = state[j];
state[j] = tmp;
}
}
public int[] PRNG(int[] data){
int tmp,k;
int i=0;
j=0;
int[] cipherText = new int[data.length];
for(int x=0;x<data.length;x++){
i = (i + 1) % 256;
j = (j + state[i]) % 256;
tmp = state[i];
state[i] = state[j];
state[j] = tmp;
k = state[(state[i] + state[j]) % 256];
cipherText[x]= (data[x] ^ k);
}
return cipherText;
}
}
//loading/writing image
package test;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.io.File;
import java.awt.image.WritableRaster;
/**
*
* #author AMaR
*/
public class LoadImage {
BufferedImage image;
void load()throws Exception {
// FIle newfile = new File("lena.png)
image = ImageIO.read(getClass().getResourceAsStream("lena.png"));
}
public Dimension getImageSize() {
return new Dimension(image.getWidth(), image.getHeight());
}
public int[] getImagePixels() {
int [] dummy = null;
int wid, hgt;
// compute size of the array
wid = image.getWidth();
hgt = image.getHeight();
// start getting the pixels
Raster pixelData;
pixelData = image.getData();
return pixelData.getPixels(0, 0, wid, hgt, dummy);
}
#SuppressWarnings("empty-statement")
public void write(int width ,int height, int[] pixels,File outputfile) {
try {
// retrieve image
BufferedImage writeImage = new BufferedImage(512, 512, BufferedImage.TYPE_BYTE_GRAY);;
// File outputfile = new File("encrypted.png");
WritableRaster raster = (WritableRaster) writeImage.getData();
raster.setPixels(0,0,width,height,pixels);
writeImage.setData(raster);
ImageIO.write(writeImage, "png", outputfile);
} catch (IOException e) {
}
}
}
It's not clear which of the below is triggering your error. This
File EnImage = new File("encrypted.png");
will read from the current directory, which is not necessarily the same directory as that your jar file is in.
This
image = ImageIO.read(getClass().getResourceAsStream("lena.png"));
will read from the directory in the jar file that your class is in. Note that you're reading from the jar file, not the directory.
Given the above code, I would:
determine or explicitly specify the working directory for the File() operations. Your working directory is the one you invoke java from, and this may differ within/without the IDE
package the lena.png as a resource within your .jar file.

Categories

Resources