首页 > 解决方案 > Java FileInputStream 每次运行时都会给出随机输出

问题描述

我需要为 AES 加密文件生成 IV,我正在这样做:

private void generateIv() {
    SecureRandom rnd = new SecureRandom();

    byte tempiv[] = new byte[16];
    rnd.nextBytes(tempiv); 

    System.out.println("IV Generated: " + tempiv.toString() + ", Length: " + tempiv.length);

    try{
        File outfile = new File("initvector.iv");
        FileOutputStream ivfile = new FileOutputStream(outfile);  
        DataOutputStream dos = new DataOutputStream(ivfile);
        dos.write(tempiv);
        ivfile.close();
        dos.close();
    } catch(Exception e){
        e.printStackTrace();
    }
}

然后,我将它显示到控制台,如下所示:

private void displayiv() {
    FileInputStream ivout = null;

    try {
        ivout = new FileInputStream("initvector.iv");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    // DataInputStream dis = new DataInputStream(ivout);

     byte[] fileiv = new byte[16];

     try {
        ivout.read(fileiv);
        //dis.close();
        ivout.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

     System.out.println(fileiv);
}

但问题是每次调用 displayiv() 方法时输出都不同……这是控制台的示例输出。

IV Generated: [B@6276ae34, Length: 16
[B@42dafa95
[B@6500df86
[B@402a079c
[B@59ec2012

正如您所看到的,iv 生成得很好,但是每次尝试从文件中读取它都会产生不同的结果。在 displayiv() 方法中,我还尝试将 fileinputstream 包装在 DataInputStream 中,但问题仍然存在。为什么是这样?

标签: javaioaes

解决方案


推荐阅读