Package javax.crypto

Class CipherOutputStream

All Implemented Interfaces:
Closeable, Flushable, AutoCloseable

public class CipherOutputStream
extends FilterOutputStream
This class wraps an output stream and a cipher so that write methods send the data through the cipher before writing them to the underlying output stream.

The cipher must be initialized for the requested operation before being used by a CipherOutputStream. For example, if a cipher initialized for encryption is used with a CipherOutputStream, the CipherOutputStream tries to encrypt the data writing it out.

  • Constructor Details

    • CipherOutputStream

      public CipherOutputStream​(OutputStream os, Cipher c)
      Creates a new CipherOutputStream instance for an OutputStream and a Cipher.
      Parameters:
      os - the output stream to write data to.
      c - the cipher to process the data with.
    • CipherOutputStream

      protected CipherOutputStream​(OutputStream os)
      Creates a new CipherOutputStream instance for an OutputStream without a cipher.

      A NullCipher is created to process the data.

      Parameters:
      os - the output stream to write the data to.
  • Method Details

    • write

      public void write​(int b) throws IOException
      Writes the single byte to this cipher output stream.
      Overrides:
      write in class FilterOutputStream
      Parameters:
      b - the byte to write.
      Throws:
      IOException - if an error occurs.
    • write

      public void write​(byte[] b, int off, int len) throws IOException
      Writes the len bytes from buffer b starting at offset off to this cipher output stream.
      Overrides:
      write in class FilterOutputStream
      Parameters:
      b - the buffer.
      off - the offset to start at.
      len - the number of bytes.
      Throws:
      IOException - if an error occurs.
    • flush

      public void flush() throws IOException
      Flushes this cipher output stream.
      Specified by:
      flush in interface Flushable
      Overrides:
      flush in class FilterOutputStream
      Throws:
      IOException - if an error occurs
    • close

      public void close() throws IOException
      Close this cipher output stream.

      On the underlying cipher doFinal will be invoked, and any buffered bytes from the cipher are also written out, and the cipher is reset to its initial state. The underlying output stream is also closed.

      Specified by:
      close in interface AutoCloseable
      Specified by:
      close in interface Closeable
      Overrides:
      close in class FilterOutputStream
      Throws:
      IOException - if an error occurs.