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

时间:2011-06-05 16:33:41

标签: java cryptography dataoutputstream

简短版本: 我使用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;
}

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

1 个答案:

答案 0 :(得分:2)

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

请尝试使用Arrays.toString(salt)

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

(同样在写出来的时候。)

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

相关问题