java - 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???
解决方案
您的加密函数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
的!
推荐阅读
- flutter - 使用水平列表视图修复渲染框错误
- c# - 如何在字符串加入中添加换行符?
- javascript - EJS 变量未在 html 中定义
- sql - 如何在保留所有数据而不创建重复列的同时在部分重叠的键列上连接表?
- swift - 无法将“UnsafeMutableRawPointer”类型的值转换为预期的参数类型“UnsafePointer”
? - aws-sam - 一个本地模拟器上的多个 SAM 模板
- java - Java 的 Arrays.sort 实例比 std::sort 运行得更快
- database-design - 如何解决部分和传递的依赖关系?
- amazon-web-services - 我可以将变量传递给使用 terraform 和 user_data 创建的 AWS EC2 实例吗?或更新已创建的资源
- python - Python 作为一种动态类型的语言如何使得不需要使用抽象类/继承?