如何强制CipherOutputStream完成加密但是让底层流保持打开状态?

时间:2011-03-27 12:07:40

标签: java outputstream encryption

我有一个由另一个OutputStream支持的CipherOutputStream。在我将所有需要加密的数据写入CipherOutputStream后,我需要附加一些未加密的数据。

The documentation for CipherOutputStream表示调用flush()不会强制最终阻止加密器;为此,我需要致电close()。但是close()也会关闭底层的OutputStream,我还需要写更多内容。

如何在不关闭流的情况下强制最后一个块退出加密器?我是否需要编写自己的NonClosingCipherOutputStream?

3 个答案:

答案 0 :(得分:8)

如果您没有Cipher的引用,则可以将FilterOutputStream传递给创建CipherOutputStream的方法。在FilterOutputStream中,覆盖close方法,以便它实际上不会关闭流。

答案 1 :(得分:1)

也许你可以在输入cipheroutputstream之前包装你的输出流

/**
 * Represents an {@code OutputStream} that does not close the underlying output stream on a call to {@link #close()}.
 * This may be useful for encapsulating an {@code OutputStream} into other output streams that does not have to be
 * closed, while closing the outer streams or reader.
 */
public class NotClosingOutputStream extends OutputStream {

    /** The underlying output stream. */
    private final OutputStream out;

    /**
     * Creates a new output stream that does not close the given output stream on a call to {@link #close()}.
     * 
     * @param out
     *            the output stream
     */
    public NotClosingOutputStream(final OutputStream out) {
        this.out = out;
    }

    /*
     * DELEGATION TO OUTPUT STREAM
     */

    @Override
    public void close() throws IOException {
        // do nothing here, since we don't want to close the underlying input stream
    }

    @Override
    public void write(final int b) throws IOException {
        out.write(b);
    }

    @Override
    public void write(final byte[] b) throws IOException {
        out.write(b);
    }

    @Override
    public void write(final byte[] b, final int off, final int len) throws IOException {
        out.write(b, off, len);
    }

    @Override
    public void flush() throws IOException {
        out.flush();
    }
}

希望有所帮助

答案 2 :(得分:0)

如果你引用Cipher包裹的CipherOutputStream对象,你应该可以执行CipherOutputStream.close()所做的事情:

调用Cipher.doFinal,然后调用flush() CiperOutputStream,然后继续。