首页 > 解决方案 > decrypt with XOR JAVA working on first line only

问题描述

I am working on a file/directory processing assignment and I encrypted the file (to hex then XOR). The file I need to decrypt is in hexadecimal so I need to decrypt then un hex. However only the first line of my file gets decrypted correctly.(key is shorter than file so it is repeated hence the keyItr) This is the encrypt code:

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);

This is the Decrypt code:

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);

input:

new new new new
old old old old

encrypted: 3f1212521a1c024901152c115c56533e1b01521b151149001c3f115d5f40 output:

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

tested with key:Qwertyuiop[123$4$567] What am I doing wrong???

标签: javaencryptionxor

解决方案


您的加密函数int keyItr = 0中有while循环,因此它会在源文本的每一行末尾重置。然而,在解密函数中,由于加密的文本只是没有中断的单行,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++){
...

这是一个演示

PS:请close()Scanner的!


推荐阅读