【发布时间】:2019-01-25 15:06:21
【问题描述】:
Java:我正在使用键盘上任意两个 ASCII 字符的键对文本文件进行加密和解密。我让它们正常工作,除非我将加密文件读入字符串进行解密。它用不同的不正确字母替换某些特定字母,但并非所有正确字母都被替换。例如,一些 t 被 s 替换。当我使用不同的键时,我还看到一些 b 被 e 替换。
我已经查看了我的加密/解密算法。我将加密的文本文件复制并粘贴到我的代码中,然后再次运行算法,结果很完美。替换字母的唯一时间是从要解密的文本文件中读取加密算法时。
public static String readFileToString(string filePath) {
StringBuilder builder = new StringBuilder();
try (Stream<String> stream = Files.get(filePath), StandardCharsets.UTF_8)){
stream.forEach(s->builder.append(s).append("\n");
}
catch(IOException e){
e.printStackTrace();
}
return builder.toString();
}
public static void writeFile(String crypt) throws IOException {
Scanner sc = new Scanner(System.in);
System.out.println("New file name: ");
String fileName = sc.nextLine();
String writtenString = crypt;
String userHome = System.getProperty("user.home");
File textFile = new File(userHome, fileName + ".txt");
BufferedWriter out = new BufferedWriter(new FileWriter(textFile));
out.write(writtenString);
out.close();
//Converts string and key into binary characters for 1-to-1 xOr to prevent any possible translation errors.
public static String crypt(String input, String key) throws UnsupportedEncodingException {
if (input.length() % 2 == 1) {
input = input + " ";
}
int n = input.length() / 2;
key = new String(new char[n]).replace("\0", key);
byte[] a = input.getBytes();
byte[] c = key.getBytes();
StringBuilder binaryBuilder = new StringBuilder();
StringBuilder binaryKeyBuilder = new StringBuilder();
//Creates a StringBuilder of bits using the file text
for(byte b: a) {
int value = b;
for(int i = 0; i < 8; i++) {
binaryBuilder.append((value & 128) == 0 ? 0 : 1);
value <<= 1;
}
binaryBuilder.append(' ');
}
//Converts binary StringBuilder to String
String binary = binaryBuilder.toString();
//Creates a StringBuilder of bits using the provided key
for(byte d: c) {
int keyValue = d;
for(int j = 0; j < 8; j++) {
binaryKeyBuilder.append((keyValue & 128) == 0 ? 0 : 1);
keyValue <<= 1;
}
binaryKeyBuilder.append(' ');
}
//Converts binaryKey StringBuilder to String
String binaryKey = binaryKeyBuilder.toString();
//Creates StringBuilder of bits using the provided key
StringBuilder xOr = new StringBuilder();
for(int q = 0; q < binary.length();q++) {
xOr.append(binary.charAt(q) ^ binaryKey.charAt(q));
}
String xOrResult = xOr.toString();
String cryptedString = "";
char next;
//Iterates through binary string to convert to ASCII characters 8 bits at a time.
for(int k = 0; k <= xOrResult.length()-8; k+=9) {
next = (char)Integer.parseInt(xOrResult.substring(k,k+8), 2);
cryptedString += next;
}
return cryptedString;
}
当我使用“ty”键时
“四分,七年前,我们的父辈提出了这一点”是正确的措辞。 但是,我得到的是:“四分,七年前我们的fasher 提出了这一点”
【问题讨论】:
-
从您问题中的代码来看,没有加密/解密
-
不认为我需要展示它,因为它无需读取或写入文件即可工作,但我会添加它
-
如果您只显示有问题的代码的一部分,您希望人们如何帮助调试您的代码?任何查看标题的读者都希望看到加密/解密代码......
标签: java binary readfile xor writefile