仅在第一行使用 XOR JAVA 解密

decrypt with XOR JAVA working on first line only

我正在处理 file/directory 处理任务,我加密了文件(先是十六进制,然后是 XOR)。我需要解密的文件是十六进制的,所以我需要解密然后取消十六进制。但是,只有我的文件的第一行被正确解密。(密钥比文件短,因此它被重复因此是 keyItr) 这是加密代码:

String encrypHexa="";
Scanner x = new Scanner(f);
while(x.hasNext()){
String a= x.nextLine();
int keyItr=0;
for (int i=0; i<a.length();i++){
//XOR
int temp = a.charAt(i) ^ key.charAt(keyItr);             
encrypHexa += String.format("%02x",(byte)temp);                     
keyItr++;      
if(keyItr==key.length()){ 
                keyItr=0;                                       }                                            }
        } System.out.println("Encrypted is: " +encrypHexa);

这是解密代码:

String hexiToDeci="";

Scanner x = new Scanner(f);

while(x.hasNext()){

String a= x.nextLine();

for (int i=0;i<a.length()-1;i+=2){

String output=a.substring(i,i+2);

int decimal = Integer.parseInt(output,16);

hexiToDeci += (char)decimal;

}
                                                    //Decrypt with XOR
int keyItr=0;
for (int i=0; i<hexiToDeci.length();i++){
//XOR
int temp = hexiToDeci.charAt(i) ^ key.charAt(keyItr);
decrypText +=(char)temp;                                                         keyItr++;
                                                        if(keyItr==key.length()){                                                             keyItr=0;                                                    }                                                    }
}
System.out.println("Encrypted is: " +decrypText);

输入:

new new new new
old old old old

加密: 3f1212521a1c024901152c115c56533e1b01521b151149001c3f115d5f40 输出:

new new new new?4d,H1wyMe$*)e

测试 key:Qwertyuiop[123$4$567] 我做错了什么???

您在加密函数的 while 循环中有 int keyItr = 0,因此它会在源文本的每一行末尾重置。然而在解密函数中,由于密文只是一行不间断,while循环从不重复,keyItr只有在达到限制后才重置。

因此,将 keyItr 初始化移到加密函数中的 while 循环之前,它就不会再给你垃圾了。但是解密的文本仍然不会是源文本的准确再现,因为源文本中的换行符被加密的 Scanner 吞没了。为避免这种情况,可以:

a) 如果您的源文件很小,请使用 EOF 字符作为加密扫描程序的分隔符。

[或]

b) 在你的加密函数中手动添加换行符,然后像这样加密:

...
String a = x.nextLine();
// Add this if
if (x.hasNext()) {
    a += System.lineSeparator();
}
for (int i=0; i<a.length();i++){
...

Here is a demo

P.S:请close()你的Scanner