1

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

长版:我有一段代码正在使用 javax.crypto 库进行基于密码的加密。我使用随机数生成器生成一个 8 字节的随机盐,然后使用 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;
}

启用加密代码后,我得到了一个半解密文件。没有它,我只会得到不一致的写入然后读取。

4

1 回答 1

2

您只是通过使用它的toString()实现来打印出一个字节数组 - 它不显示数据,只是一个哈希码。

尝试Arrays.toString(salt)改用:

System.out.println("Recovered salt: " + Arrays.toString(salt));

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

怀疑你现在会看到你实际上一直在正确地阅读盐分。

于 2011-06-05T16:37:21.583 回答