简短版本: 我使用 DataOutputStream 将填充有随机字节的 8 字节字节数组写入磁盘,然后在另一种方法中使用 DataInputStream 将其读回。数据看起来不太一样。我应该从哪里开始寻找问题?
长版: 我有一段代码正在使用 javax.crypto 库进行基于密码的加密。我使用随机数生成器生成 8 字节随机盐,然后使用 1000 次迭代计数来生成 key 。
当我写入文件时,它的格式为:
[ 8-byte Salt ][int iteration count][encrypted payload]
当我读取文件的开头以恢复重建 key 的参数时,字节数组似乎与写入的内容不同。然而,迭代计数已成功恢复。
完整的代码在这里:
http://hg.kurt.im/479hw3/src/0c3c11f68f26/src/csc479_hw3/PBE.java
相关部分如下:
boolean encrypt(char[] password, String fileName){
Random randy = new Random();
byte[] salt = new byte[8];
randy.nextBytes(salt);
System.out.println("Salt: "+salt);
try{
File inFile = new File(fileName);
File outFile = new File(fileName+."encrypted);
DataOutputStream dOS = new DataOutputStream(new FileOutputStream(outFile));
dOS.write(salt);
dOS.flush();
dOS.writeInt(1000);
dOS.flush();
dOS.close();
/* Snip a bunch of stuff currently commented out related to encryption */
}catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}
boolean decrypt(char[] password, string fileName, string outFileName){
byte[] salt = new byte[8];
try{
DataInputStream dIS = new DataInputStream(new FileInputStream(newFile(fileName)));
dIS.read(salt,0,salt.length);
int iterationCount = dIS.readInt();
System.out.println("Recovered salt: "+salt);//Different than above written salt
System.out.println("Recovered count: "+iterationCount);//Same as above
/*Snip some more commented out crypto */
}catch (Exception e){
e.printStackTrace();
return false;
}
return true;
}
启用加密代码后,我得到了一半解密的文件。没有它,我只会得到不一致的写入然后读取。
最佳答案
您只需使用其 toString()
实现即可打印出字节数组 - 它不显示数据,仅显示哈希码。
尝试使用Arrays.toString(salt)
代替:
System.out.println("Recovered salt: " + Arrays.toString(salt));
(写出来时也是如此。)
我怀疑你现在会发现你实际上一直在正确地读取盐值。
关于java - 写入结果不一致,然后使用字节数组和 DataOutputStream 读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6244245/