将 IV 附加到加密文件以供以后解密

Appending IV onto encrypted file for later decryption

我试图在每个文件加密之后但在写入之前将安全生成的 16 字节 IV 附加到每个文件上。这样我以后就可以通过从文件中提取 IV 来解密它。到目前为止,这是我的代码:

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();

关于如何做到这一点有什么建议吗?

FileOutputStream fos = new FileOutputStream(dir + fileName);
fos.write(iv);

CipherOutputStream cos = new CipherOutputStream(fos, cipher);

应该可以解决问题。甚至可以在设置密码之前将 IV 写入文件。