我正在尝试执行图像加密/解密过程。代码运行时没有任何错误,但输出不正确。我无法确定我哪里出错了。 相同的代码用于加密和解密。唯一的区别是路径的变化作为输入。 PS:我是java和图像处理概念的新手。
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);
}
}