使用字节数组和DataOutputStream写入、然后读取的结果不一致



简短版本:我使用DataOutputStream将一个8字节、充满随机字节的数组写入磁盘,然后用另一种方法中的DataInputStream将其读回。数据似乎不相同。我应该从哪里开始寻找问题?

长版本:我有一段代码正在使用javax.crypto库进行基于密码的加密。我使用随机数生成器生成一个8字节的随机salt,然后使用1000的迭代计数来生成密钥。

当我写文件时,它的格式是:

[ 8-byte Salt ][int iteration count][encrypted payload]

当我读取文件的开头以恢复重建密钥的参数时,字节数组似乎与所写的不一样。但是,迭代计数已成功恢复。

整个代码都在这里:

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

(写出来的时候也是如此。)

我怀疑你现在会发现你一直在正确地阅读盐。

相关内容