Search code examples
javaencryptionfile-ioinitialization-vector

Appending IV onto encrypted file for later decryption


I am trying to append a 16 byte securely generated IV onto each file after it is encrypted but before it is written. This is so that I can decrypt it later by pulling the IV off the file. This is my code so far:

public static void encrypt(byte[] file, String password, String fileName, String dir)
        throws Exception {
    SecureRandom r = new SecureRandom();
    //128 bit IV generated for each file
    byte[] iv = new byte[IV_LENGTH];
    r.nextBytes(iv);

    SecretKeySpec keySpec = new SecretKeySpec(password.getBytes(), "AES");

    IvParameterSpec ivspec = new IvParameterSpec(iv);
    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
    cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivspec);

    FileOutputStream fos = new FileOutputStream(dir + fileName);
    CipherOutputStream cos = new CipherOutputStream(fos, cipher);

    // Have to append IV --------


    cos.write(file);

    fos.flush();
    cos.flush();
    cos.close();
    fos.close();

Any suggestions on how to do this?


Solution

  • FileOutputStream fos = new FileOutputStream(dir + fileName);
    fos.write(iv);
    
    CipherOutputStream cos = new CipherOutputStream(fos, cipher);
    

    should do the trick. The IV can be written to the file before the Cipher is even set up.