这是我用Java编写的密码,但我不知道它是否正常工作,因为当我传递一个文件如.gif时会生成一个较小的输出字符串,当我将其转换回来时,gif不起作用它比原来的几个字节小。我认为这可能是ascii转换的二进制问题。有谁知道如何解决它?
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
public class XOR {
public static void main(String args[]) throws UnsupportedEncodingException, FileNotFoundException {
String data = "this is a string";
String rawKey = "this is a key.".toLowerCase();
//Checks the key is valid.
if (rawKey.length() % 2 != 0) {
System.err.println("The key has to be an even length.");
System.exit(1);
}
for(int p = 0; p < rawKey.length()-1; p++){
if (rawKey.charAt(p) == rawKey.charAt(p+1)) {
System.err.println("The key can't have repeated characters next to each other.");
System.exit(1);
}
}
long dataLength = data.length();
String content = strToBin(data);
String working = content;
for (int i = 0; i < rawKey.length(); i++) {
working = XOR(working, String.valueOf(strToBin(String.valueOf(rawKey.charAt(i)))), 8, dataLength);
}
System.out.println(working);
System.out.println(binToStr(working));
for (int i = 0; i < rawKey.length(); i++) {
working = XOR(working, String.valueOf(strToBin(String.valueOf(rawKey.charAt(i)))), 8, dataLength);
}
System.out.println(binToStr(working));
}
public static String XOR(String input, String key, int blockSize, long length) {
long tries = length;
String original = input; //INPUTS MUST BE IN BINARY
String compare = key; //INPUTS MUST BE IN BINARY
String build = "";
long o = 0; //The offset so we skip characters we have already done.
for (int t = 0; t < tries; t++) { //Do each block.
for(int i = 0; i < blockSize; i++) { //Do each block one at a time.
if (original.charAt((int) (i+o)) == compare.charAt(i)) { //Compares the block to the key
build += "0"; //If the key and the character are the same false.
} else {
build += "1"; //If the key and the character are the different true.
}
}
o += blockSize+1; //+1 to include the space.
if (t != tries-1) {build += " ";}; //Adds space. If statement prevents adding a pointless space onto the end.
}
return build;
}
public static String strToBin(String input) {
byte[] bytes = input.getBytes();
StringBuilder binary = new StringBuilder();
for (byte b : bytes)
{
int val = b;
for (int i = 0; i < 8; i++)
{
binary.append((val & 128) == 0 ? 0 : 1);
val <<= 1;
}
binary.append(' ');
}
return binary.toString();
}
public static String binToStr( String s ) {
String[] ss = s.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < ss.length; i++) {
sb.append( (char)Integer.parseInt( ss[i], 2 ) );
}
return sb.toString();
}
}