【发布时间】:2011-05-31 14:18:18
【问题描述】:
所以我在这里做一项普林斯顿练习:http://www.cs.princeton.edu/courses/archive/fall10/cos126/assignments/lfsr.html 并且我已经使用提供的数据通过 LFSR 类进行了全面测试,所以我确信我没有出错。但是,我的 PhotoMagic 类会生成管道的加密照片,如下所示:
这不是它应该出现的样子。知道我的代码哪里出错了吗?
import java.awt.Color;
public class PhotoMagic
{
private LFSR lfsr;
public static void main(String args[])
{
new PhotoMagic("src/pictures/shield.png","01101000010100010000",16);
}
public PhotoMagic(String imageName,String binaryPassword,int tap)
{
Picture pic = new Picture(imageName);
lfsr = new LFSR(binaryPassword,tap);
for (int x = 0; x < pic.width(); x++)
{
for (int y = 0; y < pic.height(); y++)
{
Color color = pic.get(x, y);
int red = color.getRed();
int blue = color.getBlue();
int green = color.getGreen();
int transparency = color.getTransparency();
int alpha = color.getAlpha();
int newRed = xor(Integer.toBinaryString(red),paddedBitPattern(lfsr.generate(8)));
int newGreen = xor(Integer.toBinaryString(green),paddedBitPattern(lfsr.generate(8)));
int newBlue = xor(Integer.toBinaryString(blue),paddedBitPattern(lfsr.generate(8)));
Color newColor = new Color(newRed, newGreen, newBlue);
pic.set(x, y, newColor);
}
}
pic.show();
}
/**
* Pads bit pattern to the left with 0s if it is not 8 bits long
* @param bitPattern
* @return
*/
public String paddedBitPattern(int bitPattern)
{
String tempBit = Integer.toBinaryString(bitPattern);
String newPattern = "";
for(int i = 1; i < 9-tempBit.length(); i++)
{
newPattern += "0";
}
newPattern += tempBit;
return newPattern;
}
/**
* Performs the bitwise XOR
* @param colorComponent
* @param generatedBit
* @return
*/
public int xor(String colorComponent, String generatedBit)
{
String newColor = "";
for(int i = 0; i < colorComponent.length(); i++)
{
if(colorComponent.charAt(i) != generatedBit.charAt(i))
{
newColor += 1;
}
else
{
newColor += 0;
}
}
return Integer.valueOf(newColor,2);
}
}
【问题讨论】:
-
为什么要将所有内容都转换为
Strings?您可以直接在 int 上使用 java xor 运算符并将代码大小缩小一半。
标签: java image encryption feedback