8

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

CipherOutputStream 的文档说调用flush()不会强制最后一个块退出加密器;为此我需要打电话close()。但close()也关闭了底层的 OutputStream,我仍然需要写更多的东西。

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

4

3 回答 3

8

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

于 2011-03-27T12:59:48.093 回答
1

也许你可以在放入密码输出流之前包装你的输出流

/**
 * 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();
    }
}

希望有帮助

于 2013-08-16T00:05:31.000 回答
0

如果您有Cipher对包装对象的引用CipherOutputStream,您应该能够执行CipherOutputStream.close()以下操作:

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

于 2011-03-27T12:21:59.703 回答