Path: blob/master/src/java.base/share/classes/javax/crypto/CipherOutputStream.java
41152 views
/*1* Copyright (c) 1997, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package javax.crypto;2627import java.io.*;2829/**30* A CipherOutputStream is composed of an OutputStream and a Cipher so31* that write() methods first process the data before writing them out32* to the underlying OutputStream. The cipher must be fully33* initialized before being used by a CipherOutputStream.34*35* <p> For example, if the cipher is initialized for encryption, the36* CipherOutputStream will attempt to encrypt data before writing out the37* encrypted data.38*39* <p> This class adheres strictly to the semantics, especially the40* failure semantics, of its ancestor classes41* java.io.OutputStream and java.io.FilterOutputStream. This class42* has exactly those methods specified in its ancestor classes, and43* overrides them all. Moreover, this class catches all exceptions44* that are not thrown by its ancestor classes. In particular, this45* class catches BadPaddingException and other exceptions thrown by46* failed integrity checks during decryption. These exceptions are not47* re-thrown, so the client will not be informed that integrity checks48* failed. Because of this behavior, this class may not be suitable49* for use with decryption in an authenticated mode of operation (e.g. GCM)50* if the application requires explicit notification when authentication51* fails. Such an application can use the Cipher API directly as an52* alternative to using this class.53*54* <p> It is crucial for a programmer using this class not to use55* methods that are not defined or overridden in this class (such as a56* new method or constructor that is later added to one of the super57* classes), because the design and implementation of those methods58* are unlikely to have considered security impact with regard to59* CipherOutputStream.60*61* @author Li Gong62* @see java.io.OutputStream63* @see java.io.FilterOutputStream64* @see javax.crypto.Cipher65* @see javax.crypto.CipherInputStream66*67* @since 1.468*/6970public class CipherOutputStream extends FilterOutputStream {7172// the cipher engine to use to process stream data73private Cipher cipher;7475// the underlying output stream76private OutputStream output;7778/* the buffer holding one byte of incoming data */79private byte[] ibuffer = new byte[1];8081// the buffer holding data ready to be written out82private byte[] obuffer = null;8384// stream status85private boolean closed = false;8687/**88* Ensure obuffer is big enough for the next update or doFinal89* operation, given the input length <code>inLen</code> (in bytes)90*91* @param inLen the input length (in bytes)92*/93private void ensureCapacity(int inLen) {94int minLen = cipher.getOutputSize(inLen);95if (obuffer == null || obuffer.length < minLen) {96obuffer = new byte[minLen];97}98}99100/**101*102* Constructs a CipherOutputStream from an OutputStream and a103* Cipher.104* <br>Note: if the specified output stream or cipher is105* null, a NullPointerException may be thrown later when106* they are used.107*108* @param os the OutputStream object109* @param c an initialized Cipher object110*/111public CipherOutputStream(OutputStream os, Cipher c) {112super(os);113output = os;114cipher = c;115};116117/**118* Constructs a CipherOutputStream from an OutputStream without119* specifying a Cipher. This has the effect of constructing a120* CipherOutputStream using a NullCipher.121* <br>Note: if the specified output stream is null, a122* NullPointerException may be thrown later when it is used.123*124* @param os the OutputStream object125*/126protected CipherOutputStream(OutputStream os) {127super(os);128output = os;129cipher = new NullCipher();130}131132/**133* Writes the specified byte to this output stream.134*135* @param b the <code>byte</code>.136* @exception IOException if an I/O error occurs.137*/138@Override139public void write(int b) throws IOException {140ibuffer[0] = (byte) b;141ensureCapacity(1);142try {143int ostored = cipher.update(ibuffer, 0, 1, obuffer);144if (ostored > 0) {145output.write(obuffer, 0, ostored);146}147} catch (ShortBufferException sbe) {148// should never happen; re-throw just in case149throw new IOException(sbe);150}151};152153/**154* Writes <code>b.length</code> bytes from the specified byte array155* to this output stream.156* <p>157* The <code>write</code> method of158* <code>CipherOutputStream</code> calls the <code>write</code>159* method of three arguments with the three arguments160* <code>b</code>, <code>0</code>, and <code>b.length</code>.161*162* @param b the data.163* @exception NullPointerException if <code>b</code> is null.164* @exception IOException if an I/O error occurs.165* @see javax.crypto.CipherOutputStream#write(byte[], int, int)166*/167@Override168public void write(byte b[]) throws IOException {169write(b, 0, b.length);170}171172/**173* Writes <code>len</code> bytes from the specified byte array174* starting at offset <code>off</code> to this output stream.175*176* @param b the data.177* @param off the start offset in the data.178* @param len the number of bytes to write.179* @exception IOException if an I/O error occurs.180*/181@Override182public void write(byte b[], int off, int len) throws IOException {183ensureCapacity(len);184try {185int ostored = cipher.update(b, off, len, obuffer);186if (ostored > 0) {187output.write(obuffer, 0, ostored);188}189} catch (ShortBufferException e) {190// should never happen; re-throw just in case191throw new IOException(e);192}193}194195/**196* Flushes this output stream by forcing any buffered output bytes197* that have already been processed by the encapsulated cipher object198* to be written out.199*200* <p>Any bytes buffered by the encapsulated cipher201* and waiting to be processed by it will not be written out. For example,202* if the encapsulated cipher is a block cipher, and the total number of203* bytes written using one of the <code>write</code> methods is less than204* the cipher's block size, no bytes will be written out.205*206* @exception IOException if an I/O error occurs.207*/208@Override209public void flush() throws IOException {210// simply call output.flush() since 'obuffer' content is always211// written out immediately212output.flush();213}214215/**216* Closes this output stream and releases any system resources217* associated with this stream.218* <p>219* This method invokes the <code>doFinal</code> method of the encapsulated220* cipher object, which causes any bytes buffered by the encapsulated221* cipher to be processed. The result is written out by calling the222* <code>flush</code> method of this output stream.223* <p>224* This method resets the encapsulated cipher object to its initial state225* and calls the <code>close</code> method of the underlying output226* stream.227*228* @exception IOException if an I/O error occurs.229*/230@Override231public void close() throws IOException {232if (closed) {233return;234}235236closed = true;237ensureCapacity(0);238try {239int ostored = cipher.doFinal(obuffer, 0);240if (ostored > 0) {241output.write(obuffer, 0, ostored);242}243} catch (IllegalBlockSizeException | BadPaddingException244| ShortBufferException e) {245}246obuffer = null;247try {248flush();249} catch (IOException ignored) {}250output.close();251}252}253254255