Merge "CipherInputStream: increase buffers for speed"
diff --git a/benchmarks/src/benchmarks/regression/CipherInputStreamBenchmark.java b/benchmarks/src/benchmarks/regression/CipherInputStreamBenchmark.java
new file mode 100644
index 0000000..9dce12a
--- /dev/null
+++ b/benchmarks/src/benchmarks/regression/CipherInputStreamBenchmark.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright (C) 2012 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package benchmarks.regression;
+
+import com.google.caliper.Param;
+import com.google.caliper.SimpleBenchmark;
+
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.spec.AlgorithmParameterSpec;
+
+import javax.crypto.CipherInputStream;
+import javax.crypto.KeyGenerator;
+import javax.crypto.SecretKey;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.crypto.Cipher;
+import javax.crypto.spec.IvParameterSpec;
+
+/**
+ * CipherInputStream benchmark.
+ */
+public class CipherInputStreamBenchmark extends SimpleBenchmark {
+
+    private static final int DATA_SIZE = 1024 * 1024;
+    private static final byte[] DATA = new byte[DATA_SIZE];
+
+    private static final int IV_SIZE = 16;
+    private static final byte[] IV = new byte[IV_SIZE];
+
+    static {
+        for (int i = 0; i < DATA_SIZE; i++) {
+            DATA[i] = (byte) i;
+        }
+        for (int i = 0; i < IV_SIZE; i++) {
+            IV[i] = (byte) i;
+        }
+    }
+
+    private SecretKey key;
+
+    private byte[] output = new byte[8192];
+
+    private Cipher cipherEncrypt;
+
+    private AlgorithmParameterSpec spec;
+
+    @Override protected void setUp() throws Exception {
+        KeyGenerator generator = KeyGenerator.getInstance("AES");
+        generator.init(128);
+        key = generator.generateKey();
+
+        spec = new IvParameterSpec(IV);
+
+        cipherEncrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");
+        cipherEncrypt.init(Cipher.ENCRYPT_MODE, key, spec);
+    }
+
+    public void timeEncrypt(int reps) throws Exception {
+        for (int i = 0; i < reps; ++i) {
+            cipherEncrypt.init(Cipher.ENCRYPT_MODE, key, spec);
+            InputStream is = new CipherInputStream(new ByteArrayInputStream(DATA), cipherEncrypt);
+            while (is.read(output) != -1) {
+            }
+        }
+    }
+}
diff --git a/luni/src/main/java/java/io/BufferedInputStream.java b/luni/src/main/java/java/io/BufferedInputStream.java
index f579e49..85236b6 100644
--- a/luni/src/main/java/java/io/BufferedInputStream.java
+++ b/luni/src/main/java/java/io/BufferedInputStream.java
@@ -37,6 +37,13 @@
  */
 public class BufferedInputStream extends FilterInputStream {
     /**
+     * The default buffer size if it is not specified.
+     *
+     * @hide
+     */
+    public static final int DEFAULT_BUFFER_SIZE = 8192;
+
+    /**
      * The buffer containing the current bytes read from the target InputStream.
      */
     protected volatile byte[] buf;
@@ -73,7 +80,7 @@
      * @param in the {@code InputStream} the buffer reads from.
      */
     public BufferedInputStream(InputStream in) {
-        this(in, 8192);
+        this(in, DEFAULT_BUFFER_SIZE);
     }
 
     /**
diff --git a/luni/src/main/java/javax/crypto/CipherInputStream.java b/luni/src/main/java/javax/crypto/CipherInputStream.java
index f2f59c1..3061655 100644
--- a/luni/src/main/java/javax/crypto/CipherInputStream.java
+++ b/luni/src/main/java/javax/crypto/CipherInputStream.java
@@ -17,6 +17,7 @@
 
 package javax.crypto;
 
+import java.io.BufferedInputStream;
 import java.io.FilterInputStream;
 import java.io.IOException;
 import java.io.InputStream;
@@ -34,11 +35,8 @@
  * CipherInputStream} tries to read the data an decrypt them before returning.
  */
 public class CipherInputStream extends FilterInputStream {
-
-    private static final int I_BUFFER_SIZE = 20;
-
     private final Cipher cipher;
-    private final byte[] inputBuffer = new byte[I_BUFFER_SIZE];
+    private final byte[] inputBuffer;
     private byte[] outputBuffer;
     private int outputIndex; // index of the first byte to return from outputBuffer
     private int outputLength; // count of the bytes to return from outputBuffer
@@ -60,6 +58,11 @@
     public CipherInputStream(InputStream is, Cipher c) {
         super(is);
         this.cipher = c;
+        int blockSize = Math.max(c.getBlockSize(), 1);
+        int bufferSize = Math.max(blockSize,
+                BufferedInputStream.DEFAULT_BUFFER_SIZE / blockSize * blockSize);
+        inputBuffer = new byte[bufferSize];
+        outputBuffer = new byte[bufferSize + ((blockSize > 1) ? 2 * blockSize : 0)];
     }
 
     /**
@@ -76,19 +79,13 @@
     }
 
     /**
-     * Reads the next byte from this cipher input stream.
-     *
-     * @return the next byte, or {@code -1} if the end of the stream is reached.
-     * @throws IOException
-     *             if an error occurs.
+     * Attempts to fill the input buffer and process some data through the
+     * cipher. Returns {@code true} if output from the cipher is available to
+     * use.
      */
-    @Override
-    public int read() throws IOException {
+    private boolean fillBuffer() throws IOException {
         if (finished) {
-            return (outputIndex == outputLength) ? -1 : outputBuffer[outputIndex++] & 0xFF;
-        }
-        if (outputIndex < outputLength) {
-            return outputBuffer[outputIndex++] & 0xFF;
+            return false;
         }
         outputIndex = 0;
         outputLength = 0;
@@ -107,7 +104,7 @@
                     throw new IOException("Error while finalizing cipher", e);
                 }
                 finished = true;
-                break;
+                return outputLength != 0;
             }
             try {
                 outputLength = cipher.update(inputBuffer, 0, byteCount, outputBuffer, 0);
@@ -115,7 +112,25 @@
                 throw new AssertionError(e);  // should not happen since we sized with getOutputSize
             }
         }
-        return read();
+        return true;
+    }
+
+    /**
+     * Reads the next byte from this cipher input stream.
+     *
+     * @return the next byte, or {@code -1} if the end of the stream is reached.
+     * @throws IOException
+     *             if an error occurs.
+     */
+    @Override
+    public int read() throws IOException {
+        if (in == null) {
+            throw new NullPointerException("in == null");
+        }
+        if (outputIndex == outputLength && !fillBuffer()) {
+            return -1;
+        }
+        return outputBuffer[outputIndex++] & 0xFF;
     }
 
     /**
@@ -137,18 +152,18 @@
         if (in == null) {
             throw new NullPointerException("in == null");
         }
-
-        int i;
-        for (i = 0; i < len; ++i) {
-            int b = read();
-            if (b == -1) {
-                return (i == 0) ? -1 : i;
-            }
-            if (buf != null) {
-                buf[off+i] = (byte) b;
-            }
+        if (outputIndex == outputLength && !fillBuffer()) {
+            return -1;
         }
-        return i;
+        int available = outputLength - outputIndex;
+        if (available < len) {
+            len = available;
+        }
+        if (buf != null) {
+            System.arraycopy(outputBuffer, outputIndex, buf, off, len);
+        }
+        outputIndex += len;
+        return len;
     }
 
     @Override
@@ -158,7 +173,7 @@
 
     @Override
     public int available() throws IOException {
-        return 0;
+        return outputLength - outputIndex;
     }
 
     /**
diff --git a/luni/src/test/java/libcore/javax/crypto/CipherInputStreamTest.java b/luni/src/test/java/libcore/javax/crypto/CipherInputStreamTest.java
index 6c3f31e..67ed36c 100644
--- a/luni/src/test/java/libcore/javax/crypto/CipherInputStreamTest.java
+++ b/luni/src/test/java/libcore/javax/crypto/CipherInputStreamTest.java
@@ -18,6 +18,7 @@
 
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
+import java.io.FilterInputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.security.spec.AlgorithmParameterSpec;
@@ -49,15 +50,71 @@
             (byte) 0x30, (byte) 0x7E, (byte) 0x6A, (byte) 0x4A
     };
 
+    private final byte[] rc4CipherText = {
+            (byte) 0x88, (byte) 0x01, (byte) 0xE3, (byte) 0x52, (byte) 0x7B
+    };
+
     private final String plainText = "abcde";
     private SecretKey key;
+    private SecretKey rc4Key;
     private AlgorithmParameterSpec iv;
 
     @Override protected void setUp() throws Exception {
         key = new SecretKeySpec(aesKeyBytes, "AES");
+        rc4Key = new SecretKeySpec(aesKeyBytes, "RC4");
         iv = new IvParameterSpec(aesIvBytes);
     }
 
+    private static class MeasuringInputStream extends FilterInputStream {
+        private int totalRead;
+
+        protected MeasuringInputStream(InputStream in) {
+            super(in);
+        }
+
+        @Override
+        public int read() throws IOException {
+            int c = super.read();
+            totalRead++;
+            return c;
+        }
+
+        @Override
+        public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {
+            int numRead = super.read(buffer, byteOffset, byteCount);
+            if (numRead != -1) {
+                totalRead += numRead;
+            }
+            return numRead;
+        }
+
+        public int getTotalRead() {
+            return totalRead;
+        }
+    }
+
+    public void testAvailable() throws Exception {
+        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
+        cipher.init(Cipher.DECRYPT_MODE, key, iv);
+        MeasuringInputStream in = new MeasuringInputStream(new ByteArrayInputStream(aesCipherText));
+        InputStream cin = new CipherInputStream(in, cipher);
+        assertTrue(cin.read() != -1);
+        assertEquals(aesCipherText.length, in.getTotalRead());
+    }
+
+    public void testDecrypt_NullInput_Discarded() throws Exception {
+        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
+        cipher.init(Cipher.DECRYPT_MODE, key, iv);
+        InputStream in = new CipherInputStream(new ByteArrayInputStream(aesCipherText), cipher);
+        int discard = 3;
+        while (discard != 0) {
+            discard -= in.read(null, 0, discard);
+        }
+        byte[] bytes = readAll(in);
+        assertEquals(Arrays.toString(plainText.substring(3).getBytes("UTF-8")),
+                Arrays.toString(bytes));
+    }
+
     public void testEncrypt() throws Exception {
         Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
         cipher.init(Cipher.ENCRYPT_MODE, key, iv);
@@ -65,6 +122,21 @@
                 new ByteArrayInputStream(plainText.getBytes("UTF-8")), cipher);
         byte[] bytes = readAll(in);
         assertEquals(Arrays.toString(aesCipherText), Arrays.toString(bytes));
+
+        // Reading again shouldn't throw an exception.
+        assertEquals(-1, in.read());
+    }
+
+    public void testEncrypt_RC4() throws Exception {
+        Cipher cipher = Cipher.getInstance("RC4");
+        cipher.init(Cipher.ENCRYPT_MODE, rc4Key);
+        InputStream in = new CipherInputStream(
+                new ByteArrayInputStream(plainText.getBytes("UTF-8")), cipher);
+        byte[] bytes = readAll(in);
+        assertEquals(Arrays.toString(rc4CipherText), Arrays.toString(bytes));
+
+        // Reading again shouldn't throw an exception.
+        assertEquals(-1, in.read());
     }
 
     public void testDecrypt() throws Exception {
@@ -75,6 +147,14 @@
         assertEquals(Arrays.toString(plainText.getBytes("UTF-8")), Arrays.toString(bytes));
     }
 
+    public void testDecrypt_RC4() throws Exception {
+        Cipher cipher = Cipher.getInstance("RC4");
+        cipher.init(Cipher.DECRYPT_MODE, rc4Key);
+        InputStream in = new CipherInputStream(new ByteArrayInputStream(rc4CipherText), cipher);
+        byte[] bytes = readAll(in);
+        assertEquals(Arrays.toString(plainText.getBytes("UTF-8")), Arrays.toString(bytes));
+    }
+
     public void testSkip() throws Exception {
         Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
         cipher.init(Cipher.DECRYPT_MODE, key, iv);
@@ -99,4 +179,28 @@
         is.read(new byte[4]);
         is.close();
     }
+
+    public void testCipherInputStream_NullInputStream_Failure() throws Exception {
+        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
+        cipher.init(Cipher.DECRYPT_MODE, key, iv);
+        InputStream is = new CipherInputStream(null, cipher);
+        try {
+            is.read();
+            fail("Expected NullPointerException");
+        } catch (NullPointerException expected) {
+        }
+
+        byte[] buffer = new byte[128];
+        try {
+            is.read(buffer);
+            fail("Expected NullPointerException");
+        } catch (NullPointerException expected) {
+        }
+
+        try {
+            is.read(buffer, 0, buffer.length);
+            fail("Expected NullPointerException");
+        } catch (NullPointerException expected) {
+        }
+    }
 }