I need to generate an IV for an AES encrypted file, and I'm doing it like so:
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();
}
}
Then, I display it to the console like this:
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);
}
But the problem is that the output is different every time I call the displayiv() method... This is a sample output from the console.
IV Generated: [B@6276ae34, Length: 16
[B@42dafa95
[B@6500df86
[B@402a079c
[B@59ec2012
As you you can see the iv is generated fine, but trying to read it from the file gives a different result every time. In the displayiv() method I also tried to wrap the fileinputstream in a DataInputStream but the problem still persists. Why is this?