You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by xu...@apache.org on 2016/05/04 05:45:57 UTC
[1/7] commons-crypto git commit: CRYPTO-37: Change all the 2 spaces
indent to 4 to comply Commons code style
Repository: commons-crypto
Updated Branches:
refs/heads/master e2cc6aeed -> 95a8d486e
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/test/java/org/apache/commons/crypto/stream/PositionedCryptoInputStreamTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/crypto/stream/PositionedCryptoInputStreamTest.java b/src/test/java/org/apache/commons/crypto/stream/PositionedCryptoInputStreamTest.java
index 2591bd9..09b8fd9 100644
--- a/src/test/java/org/apache/commons/crypto/stream/PositionedCryptoInputStreamTest.java
+++ b/src/test/java/org/apache/commons/crypto/stream/PositionedCryptoInputStreamTest.java
@@ -41,344 +41,350 @@ import java.util.Random;
public class PositionedCryptoInputStreamTest {
- private final int dataLen = 20000;
- private byte[] testData = new byte[dataLen];
- private byte[] encData;
- private Properties props = new Properties();
- private byte[] key = new byte[16];
- private byte[] iv = new byte[16];
- int bufferSize = 2048;
- int bufferSizeLess = bufferSize - 1;
- int bufferSizeMore = bufferSize + 1;
- int length = 1024;
- int lengthLess = length - 1;
- int lengthMore = length + 1;
-
- private final String jceCipherClass = JceCipher.class.getName();
- private final String opensslCipherClass = OpensslCipher.class.getName();
- private CipherTransformation transformation =
- CipherTransformation.AES_CTR_NOPADDING;
-
- @Before
- public void before() throws IOException {
- Random random = new SecureRandom();
- random.nextBytes(testData);
- random.nextBytes(key);
- random.nextBytes(iv);
- prepareData();
- }
-
- private void prepareData() throws IOException {
- CryptoCipher cipher = null;
- try {
- cipher = (CryptoCipher)ReflectionUtils.newInstance(
- ReflectionUtils.getClassByName(jceCipherClass),
- props, transformation);
- } catch (ClassNotFoundException cnfe) {
- throw new IOException("Illegal crypto cipher!");
+ private final int dataLen = 20000;
+ private byte[] testData = new byte[dataLen];
+ private byte[] encData;
+ private Properties props = new Properties();
+ private byte[] key = new byte[16];
+ private byte[] iv = new byte[16];
+ int bufferSize = 2048;
+ int bufferSizeLess = bufferSize - 1;
+ int bufferSizeMore = bufferSize + 1;
+ int length = 1024;
+ int lengthLess = length - 1;
+ int lengthMore = length + 1;
+
+ private final String jceCipherClass = JceCipher.class.getName();
+ private final String opensslCipherClass = OpensslCipher.class.getName();
+ private CipherTransformation transformation = CipherTransformation.AES_CTR_NOPADDING;
+
+ @Before
+ public void before() throws IOException {
+ Random random = new SecureRandom();
+ random.nextBytes(testData);
+ random.nextBytes(key);
+ random.nextBytes(iv);
+ prepareData();
}
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- // encryption data
- OutputStream out = new CryptoOutputStream(baos, cipher, bufferSize,
- new SecretKeySpec(key,"AES"), new IvParameterSpec(iv));
- out.write(testData);
- out.flush();
- out.close();
- encData = baos.toByteArray();
- }
-
- public void setUp() throws IOException {}
-
- private PositionedCryptoInputStream getCryptoInputStream(CryptoCipher cipher,
- int bufferSize) throws IOException {
- return new PositionedCryptoInputStream(new PositionedInputForTest(
- Arrays.copyOf(encData, encData.length)), cipher, bufferSize, key, iv, 0);
- }
-
- @Test
- public void doTest() throws Exception {
- testCipher(jceCipherClass);
- testCipher(opensslCipherClass);
- }
-
- private void testCipher(String cipherClass) throws Exception {
- doPositionedReadTests(cipherClass);
- doReadFullyTests(cipherClass);
- doSeekTests(cipherClass);
- doMultipleReadTest(cipherClass);
- }
-
- // when there are multiple positioned read actions and one read action,
- // they will not interfere each other.
- private void doMultipleReadTest(String cipherClass) throws Exception {
- PositionedCryptoInputStream in = getCryptoInputStream(
- getCipher(cipherClass), bufferSize);
- int position = 0;
- while (in.available() > 0) {
- ByteBuffer buf = ByteBuffer.allocate(length);
- byte[] bytes1 = new byte[length];
- byte[] bytes2 = new byte[lengthLess];
- // do the read and position read
- int pn1 = in.read(position, bytes1, 0, length);
- int n = in.read(buf);
- int pn2 = in.read(position, bytes2, 0, lengthLess);
-
- // verify the result
- if (pn1 > 0) {
- compareByteArray(testData, position, bytes1, pn1);
- }
-
- if (pn2 > 0) {
- compareByteArray(testData, position, bytes2, pn2);
- }
-
- if (n > 0) {
- compareByteArray(testData, position, buf.array(), n);
- position += n;
- } else {
- break;
- }
+ private void prepareData() throws IOException {
+ CryptoCipher cipher = null;
+ try {
+ cipher = (CryptoCipher) ReflectionUtils.newInstance(
+ ReflectionUtils.getClassByName(jceCipherClass), props,
+ transformation);
+ } catch (ClassNotFoundException cnfe) {
+ throw new IOException("Illegal crypto cipher!");
+ }
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ // encryption data
+ OutputStream out = new CryptoOutputStream(baos, cipher, bufferSize,
+ new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));
+ out.write(testData);
+ out.flush();
+ out.close();
+ encData = baos.toByteArray();
}
- in.close();
- }
-
- private void doPositionedReadTests(String cipherClass) throws Exception {
- // test with different bufferSize when position = 0
- testPositionedReadLoop(cipherClass, 0, length, bufferSize, dataLen);
- testPositionedReadLoop(cipherClass, 0, length, bufferSizeLess, dataLen);
- testPositionedReadLoop(cipherClass, 0, length, bufferSizeMore, dataLen);
- // test with different position when bufferSize = 2048
- testPositionedReadLoop(cipherClass, dataLen / 2, length, bufferSize, dataLen);
- testPositionedReadLoop(cipherClass, dataLen / 2 - 1, length,
- bufferSizeLess, dataLen);
- testPositionedReadLoop(cipherClass, dataLen / 2 + 1, length,
- bufferSizeMore, dataLen);
- // position = -1 or position = max length, read nothing and return -1
- testPositionedReadNone(cipherClass, -1, length, bufferSize);
- testPositionedReadNone(cipherClass, dataLen, length, bufferSize);
- }
-
- private void doReadFullyTests(String cipherClass) throws Exception {
- // test with different bufferSize when position = 0
- testReadFullyLoop(cipherClass, 0, length, bufferSize, dataLen);
- testReadFullyLoop(cipherClass, 0, length, bufferSizeLess, dataLen);
- testReadFullyLoop(cipherClass, 0, length, bufferSizeMore, dataLen);
- // test with different length when position = 0
- testReadFullyLoop(cipherClass, 0, length, bufferSize, dataLen);
- testReadFullyLoop(cipherClass, 0, lengthLess, bufferSize, dataLen);
- testReadFullyLoop(cipherClass, 0, lengthMore, bufferSize, dataLen);
- // test read fully failed
- testReadFullyFailed(cipherClass, -1, length, bufferSize);
- testReadFullyFailed(cipherClass, dataLen, length, bufferSize);
- testReadFullyFailed(cipherClass, dataLen - length + 1, length, bufferSize);
- }
-
- private void doSeekTests(String cipherClass) throws Exception {
- // test with different length when position = 0
- testSeekLoop(cipherClass, 0, length, bufferSize);
- testSeekLoop(cipherClass, 0, lengthLess, bufferSize);
- testSeekLoop(cipherClass, 0, lengthMore, bufferSize);
- // there should be none data read when position = dataLen
- testSeekLoop(cipherClass, dataLen, length, bufferSize);
- // test exception when position = -1
- testSeekFailed(cipherClass, -1, bufferSize);
- }
-
- private void testSeekLoop(String cipherClass, int position, int length,
- int bufferSize) throws Exception {
- PositionedCryptoInputStream in = getCryptoInputStream(
- getCipher(cipherClass), bufferSize);
- while (in.available() > 0) {
- in.seek(position);
- ByteBuffer buf = ByteBuffer.allocate(length);
- int n = in.read(buf);
- if (n > 0) {
- compareByteArray(testData, position, buf.array(), n);
- position += n;
- } else {
- break;
- }
+
+ public void setUp() throws IOException {
}
- in.close();
- }
-
- // test for the out of index position, eg, -1.
- private void testSeekFailed(String cipherClass, int position,
- int bufferSize) throws Exception {
- PositionedCryptoInputStream in = getCryptoInputStream(
- getCipher(cipherClass), bufferSize);
- try {
- in.seek(position);
- Assert.fail("Excepted exception for cannot seek to negative offset.");
- } catch (IllegalArgumentException iae) {
+
+ private PositionedCryptoInputStream getCryptoInputStream(
+ CryptoCipher cipher, int bufferSize) throws IOException {
+ return new PositionedCryptoInputStream(new PositionedInputForTest(
+ Arrays.copyOf(encData, encData.length)), cipher, bufferSize,
+ key, iv, 0);
}
- in.close();
- }
-
- private void testPositionedReadLoop(String cipherClass, int position,
- int length, int bufferSize, int total) throws Exception {
- PositionedCryptoInputStream in = getCryptoInputStream(
- getCipher(cipherClass), bufferSize);
- // do the position read until the end of data
- while (position < total) {
- byte[] bytes = new byte[length];
- int n = in.read(position, bytes, 0, length);
- if (n >= 0) {
- compareByteArray(testData, position, bytes, n);
- position += n;
- } else {
- break;
- }
+
+ @Test
+ public void doTest() throws Exception {
+ testCipher(jceCipherClass);
+ testCipher(opensslCipherClass);
}
- in.close();
- }
-
- // test for the out of index position, eg, -1.
- private void testPositionedReadNone(String cipherClass, int position,
- int length, int bufferSize) throws Exception {
- PositionedCryptoInputStream in = getCryptoInputStream(
- getCipher(cipherClass), bufferSize);
- byte[] bytes = new byte[length];
- int n = in.read(position, bytes, 0, length);
- Assert.assertEquals(n, -1);
- in.close();
- }
-
- private void testReadFullyLoop(String cipherClass,int position,
- int length, int bufferSize, int total) throws Exception {
- PositionedCryptoInputStream in = getCryptoInputStream(
- getCipher(cipherClass), bufferSize);
-
- // do the position read full until remain < length
- while (position + length <= total) {
- byte[] bytes = new byte[length];
- in.readFully(position, bytes, 0, length);
- compareByteArray(testData, position, bytes, length);
- position += length;
+
+ private void testCipher(String cipherClass) throws Exception {
+ doPositionedReadTests(cipherClass);
+ doReadFullyTests(cipherClass);
+ doSeekTests(cipherClass);
+ doMultipleReadTest(cipherClass);
}
- in.close();
- }
-
- // test for the End of file reached before reading fully
- private void testReadFullyFailed(String cipherClass, int position,
- int length, int bufferSize) throws Exception {
- PositionedCryptoInputStream in = getCryptoInputStream(
- getCipher(cipherClass), bufferSize);
- byte[] bytes = new byte[length];
- try {
- in.readFully(position, bytes, 0, length);
- Assert.fail("Excepted EOFException.");
- } catch (IOException ioe) {
- // excepted exception
+ // when there are multiple positioned read actions and one read action,
+ // they will not interfere each other.
+ private void doMultipleReadTest(String cipherClass) throws Exception {
+ PositionedCryptoInputStream in = getCryptoInputStream(
+ getCipher(cipherClass), bufferSize);
+ int position = 0;
+ while (in.available() > 0) {
+ ByteBuffer buf = ByteBuffer.allocate(length);
+ byte[] bytes1 = new byte[length];
+ byte[] bytes2 = new byte[lengthLess];
+ // do the read and position read
+ int pn1 = in.read(position, bytes1, 0, length);
+ int n = in.read(buf);
+ int pn2 = in.read(position, bytes2, 0, lengthLess);
+
+ // verify the result
+ if (pn1 > 0) {
+ compareByteArray(testData, position, bytes1, pn1);
+ }
+
+ if (pn2 > 0) {
+ compareByteArray(testData, position, bytes2, pn2);
+ }
+
+ if (n > 0) {
+ compareByteArray(testData, position, buf.array(), n);
+ position += n;
+ } else {
+ break;
+ }
+ }
+ in.close();
}
- in.close();
- }
-
- // compare the data from pos with length and data2 from 0 with length
- private void compareByteArray(byte[] data1, int pos, byte[] data2, int length) {
- byte[] expectedData = new byte[length];
- byte[] realData = new byte[length];
- // get the expected data with the position and length
- System.arraycopy(data1, pos, expectedData, 0, length);
- // get the real data
- System.arraycopy(data2, 0, realData, 0, length);
- Assert.assertArrayEquals(expectedData, realData);
- }
-
- private CryptoCipher getCipher(String cipherClass) throws IOException {
- try {
- return (CryptoCipher)ReflectionUtils.newInstance(
- ReflectionUtils.getClassByName(cipherClass), props, transformation);
- } catch (ClassNotFoundException cnfe) {
- throw new IOException("Illegal crypto cipher!");
+
+ private void doPositionedReadTests(String cipherClass) throws Exception {
+ // test with different bufferSize when position = 0
+ testPositionedReadLoop(cipherClass, 0, length, bufferSize, dataLen);
+ testPositionedReadLoop(cipherClass, 0, length, bufferSizeLess, dataLen);
+ testPositionedReadLoop(cipherClass, 0, length, bufferSizeMore, dataLen);
+ // test with different position when bufferSize = 2048
+ testPositionedReadLoop(cipherClass, dataLen / 2, length, bufferSize,
+ dataLen);
+ testPositionedReadLoop(cipherClass, dataLen / 2 - 1, length,
+ bufferSizeLess, dataLen);
+ testPositionedReadLoop(cipherClass, dataLen / 2 + 1, length,
+ bufferSizeMore, dataLen);
+ // position = -1 or position = max length, read nothing and return -1
+ testPositionedReadNone(cipherClass, -1, length, bufferSize);
+ testPositionedReadNone(cipherClass, dataLen, length, bufferSize);
}
- }
- class PositionedInputForTest implements Input {
+ private void doReadFullyTests(String cipherClass) throws Exception {
+ // test with different bufferSize when position = 0
+ testReadFullyLoop(cipherClass, 0, length, bufferSize, dataLen);
+ testReadFullyLoop(cipherClass, 0, length, bufferSizeLess, dataLen);
+ testReadFullyLoop(cipherClass, 0, length, bufferSizeMore, dataLen);
+ // test with different length when position = 0
+ testReadFullyLoop(cipherClass, 0, length, bufferSize, dataLen);
+ testReadFullyLoop(cipherClass, 0, lengthLess, bufferSize, dataLen);
+ testReadFullyLoop(cipherClass, 0, lengthMore, bufferSize, dataLen);
+ // test read fully failed
+ testReadFullyFailed(cipherClass, -1, length, bufferSize);
+ testReadFullyFailed(cipherClass, dataLen, length, bufferSize);
+ testReadFullyFailed(cipherClass, dataLen - length + 1, length,
+ bufferSize);
+ }
- byte[] data;
- long pos;
- long count;
+ private void doSeekTests(String cipherClass) throws Exception {
+ // test with different length when position = 0
+ testSeekLoop(cipherClass, 0, length, bufferSize);
+ testSeekLoop(cipherClass, 0, lengthLess, bufferSize);
+ testSeekLoop(cipherClass, 0, lengthMore, bufferSize);
+ // there should be none data read when position = dataLen
+ testSeekLoop(cipherClass, dataLen, length, bufferSize);
+ // test exception when position = -1
+ testSeekFailed(cipherClass, -1, bufferSize);
+ }
+
+ private void testSeekLoop(String cipherClass, int position, int length,
+ int bufferSize) throws Exception {
+ PositionedCryptoInputStream in = getCryptoInputStream(
+ getCipher(cipherClass), bufferSize);
+ while (in.available() > 0) {
+ in.seek(position);
+ ByteBuffer buf = ByteBuffer.allocate(length);
+ int n = in.read(buf);
+ if (n > 0) {
+ compareByteArray(testData, position, buf.array(), n);
+ position += n;
+ } else {
+ break;
+ }
+ }
+ in.close();
+ }
+
+ // test for the out of index position, eg, -1.
+ private void testSeekFailed(String cipherClass, int position, int bufferSize)
+ throws Exception {
+ PositionedCryptoInputStream in = getCryptoInputStream(
+ getCipher(cipherClass), bufferSize);
+ try {
+ in.seek(position);
+ Assert.fail("Excepted exception for cannot seek to negative offset.");
+ } catch (IllegalArgumentException iae) {
+ }
+ in.close();
+ }
- public PositionedInputForTest(byte[] data) {
- this.data = data;
- this.pos = 0;
- this.count = data.length;
+ private void testPositionedReadLoop(String cipherClass, int position,
+ int length, int bufferSize, int total) throws Exception {
+ PositionedCryptoInputStream in = getCryptoInputStream(
+ getCipher(cipherClass), bufferSize);
+ // do the position read until the end of data
+ while (position < total) {
+ byte[] bytes = new byte[length];
+ int n = in.read(position, bytes, 0, length);
+ if (n >= 0) {
+ compareByteArray(testData, position, bytes, n);
+ position += n;
+ } else {
+ break;
+ }
+ }
+ in.close();
}
- @Override
- public int read(ByteBuffer dst) throws IOException {
- int remaining = (int)(count - pos);
- if(remaining <= 0) {
- return -1;
- }
-
- int length = Math.min(dst.remaining(), remaining);
- dst.put(data, (int)pos, length);
- pos += length;
- return length;
+ // test for the out of index position, eg, -1.
+ private void testPositionedReadNone(String cipherClass, int position,
+ int length, int bufferSize) throws Exception {
+ PositionedCryptoInputStream in = getCryptoInputStream(
+ getCipher(cipherClass), bufferSize);
+ byte[] bytes = new byte[length];
+ int n = in.read(position, bytes, 0, length);
+ Assert.assertEquals(n, -1);
+ in.close();
}
- @Override
- public long skip(long n) throws IOException {
- if (n <= 0) {
- return 0;
- }
+ private void testReadFullyLoop(String cipherClass, int position,
+ int length, int bufferSize, int total) throws Exception {
+ PositionedCryptoInputStream in = getCryptoInputStream(
+ getCipher(cipherClass), bufferSize);
- long remaining = count - pos;
- if(remaining < n) {
- n = remaining;
- }
- pos += n;
+ // do the position read full until remain < length
+ while (position + length <= total) {
+ byte[] bytes = new byte[length];
+ in.readFully(position, bytes, 0, length);
+ compareByteArray(testData, position, bytes, length);
+ position += length;
+ }
- return n;
+ in.close();
}
- @Override
- public int read(long position, byte[] buffer, int offset, int length)
- throws IOException {
- if (buffer == null) {
- throw new NullPointerException();
- } else if (offset < 0 || length < 0 || length > buffer.length - offset) {
- throw new IndexOutOfBoundsException();
- }
-
- if (position < 0 || position >= count) {
- return -1;
- }
-
- long avail = count - position;
- if (length > avail) {
- length = (int)avail;
- }
- if (length <= 0) {
- return 0;
- }
- System.arraycopy(data, (int)position, buffer, offset, length);
- return length;
+ // test for the End of file reached before reading fully
+ private void testReadFullyFailed(String cipherClass, int position,
+ int length, int bufferSize) throws Exception {
+ PositionedCryptoInputStream in = getCryptoInputStream(
+ getCipher(cipherClass), bufferSize);
+ byte[] bytes = new byte[length];
+ try {
+ in.readFully(position, bytes, 0, length);
+ Assert.fail("Excepted EOFException.");
+ } catch (IOException ioe) {
+ // excepted exception
+ }
+ in.close();
}
- @Override
- public void seek(long position) throws IOException {
- if (pos < 0) {
- throw new IOException("Negative seek offset");
- } else if (position >= 0 && position < count) {
- pos = position;
- } else {
- // to the end of file
- pos = count;
- }
+ // compare the data from pos with length and data2 from 0 with length
+ private void compareByteArray(byte[] data1, int pos, byte[] data2,
+ int length) {
+ byte[] expectedData = new byte[length];
+ byte[] realData = new byte[length];
+ // get the expected data with the position and length
+ System.arraycopy(data1, pos, expectedData, 0, length);
+ // get the real data
+ System.arraycopy(data2, 0, realData, 0, length);
+ Assert.assertArrayEquals(expectedData, realData);
}
- @Override
- public void close() throws IOException {
+ private CryptoCipher getCipher(String cipherClass) throws IOException {
+ try {
+ return (CryptoCipher) ReflectionUtils.newInstance(
+ ReflectionUtils.getClassByName(cipherClass), props,
+ transformation);
+ } catch (ClassNotFoundException cnfe) {
+ throw new IOException("Illegal crypto cipher!");
+ }
}
- @Override
- public int available() throws IOException {
- return (int)(count - pos);
+ class PositionedInputForTest implements Input {
+
+ byte[] data;
+ long pos;
+ long count;
+
+ public PositionedInputForTest(byte[] data) {
+ this.data = data;
+ this.pos = 0;
+ this.count = data.length;
+ }
+
+ @Override
+ public int read(ByteBuffer dst) throws IOException {
+ int remaining = (int) (count - pos);
+ if (remaining <= 0) {
+ return -1;
+ }
+
+ int length = Math.min(dst.remaining(), remaining);
+ dst.put(data, (int) pos, length);
+ pos += length;
+ return length;
+ }
+
+ @Override
+ public long skip(long n) throws IOException {
+ if (n <= 0) {
+ return 0;
+ }
+
+ long remaining = count - pos;
+ if (remaining < n) {
+ n = remaining;
+ }
+ pos += n;
+
+ return n;
+ }
+
+ @Override
+ public int read(long position, byte[] buffer, int offset, int length)
+ throws IOException {
+ if (buffer == null) {
+ throw new NullPointerException();
+ } else if (offset < 0 || length < 0
+ || length > buffer.length - offset) {
+ throw new IndexOutOfBoundsException();
+ }
+
+ if (position < 0 || position >= count) {
+ return -1;
+ }
+
+ long avail = count - position;
+ if (length > avail) {
+ length = (int) avail;
+ }
+ if (length <= 0) {
+ return 0;
+ }
+ System.arraycopy(data, (int) position, buffer, offset, length);
+ return length;
+ }
+
+ @Override
+ public void seek(long position) throws IOException {
+ if (pos < 0) {
+ throw new IOException("Negative seek offset");
+ } else if (position >= 0 && position < count) {
+ pos = position;
+ } else {
+ // to the end of file
+ pos = count;
+ }
+ }
+
+ @Override
+ public void close() throws IOException {
+ }
+
+ @Override
+ public int available() throws IOException {
+ return (int) (count - pos);
+ }
}
- }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/test/java/org/apache/commons/crypto/utils/UtilsTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/crypto/utils/UtilsTest.java b/src/test/java/org/apache/commons/crypto/utils/UtilsTest.java
index a0475be..e880898 100644
--- a/src/test/java/org/apache/commons/crypto/utils/UtilsTest.java
+++ b/src/test/java/org/apache/commons/crypto/utils/UtilsTest.java
@@ -25,16 +25,16 @@ import java.util.Collections;
import java.util.List;
public class UtilsTest {
- @Test
- public void testSplitOmitEmptyLine() {
- List<String> clazzNames = Utils.splitClassNames("", ",");
- Assert.assertEquals(Collections.<String>emptyList(), clazzNames);
+ @Test
+ public void testSplitOmitEmptyLine() {
+ List<String> clazzNames = Utils.splitClassNames("", ",");
+ Assert.assertEquals(Collections.<String> emptyList(), clazzNames);
- clazzNames = Utils.splitClassNames("a,b", ",");
- Assert.assertEquals(Arrays.asList("a", "b"), clazzNames);
- clazzNames = Utils.splitClassNames("a,b,", ",");
- Assert.assertEquals(Arrays.asList("a", "b"), clazzNames);
- clazzNames = Utils.splitClassNames("a, b,", ",");
- Assert.assertEquals(Arrays.asList("a", "b"), clazzNames);
- }
+ clazzNames = Utils.splitClassNames("a,b", ",");
+ Assert.assertEquals(Arrays.asList("a", "b"), clazzNames);
+ clazzNames = Utils.splitClassNames("a,b,", ",");
+ Assert.assertEquals(Arrays.asList("a", "b"), clazzNames);
+ clazzNames = Utils.splitClassNames("a, b,", ",");
+ Assert.assertEquals(Arrays.asList("a", "b"), clazzNames);
+ }
}
[3/7] commons-crypto git commit: CRYPTO-37: Change all the 2 spaces
indent to 4 to comply Commons code style
Posted by xu...@apache.org.
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/utils/NativeCodeLoader.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/utils/NativeCodeLoader.java b/src/main/java/org/apache/commons/crypto/utils/NativeCodeLoader.java
index 228cee7..df41b54 100644
--- a/src/main/java/org/apache/commons/crypto/utils/NativeCodeLoader.java
+++ b/src/main/java/org/apache/commons/crypto/utils/NativeCodeLoader.java
@@ -30,259 +30,257 @@ import java.util.UUID;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-
/**
- * A helper to load the native code i.e. libcommons-crypto.so.
- * This handles the fallback to either the bundled libcommons-crypto-Linux-i386-32.so
- * or the default java implementations where appropriate.
+ * A helper to load the native code i.e. libcommons-crypto.so. This handles the
+ * fallback to either the bundled libcommons-crypto-Linux-i386-32.so or the
+ * default java implementations where appropriate.
*/
public class NativeCodeLoader {
- private static final Log LOG =
- LogFactory.getLog(NativeCodeLoader.class);
-
- private final static boolean nativeCodeLoaded;
+ private static final Log LOG = LogFactory.getLog(NativeCodeLoader.class);
- private NativeCodeLoader() {}
+ private final static boolean nativeCodeLoaded;
- static {
- // Try to load native library and set fallback flag appropriately
- if(LOG.isDebugEnabled()) {
- LOG.debug("Trying to load the custom-built native-commons-crypto library...");
+ private NativeCodeLoader() {
}
- boolean nativeLoaded = false;
- try {
- File nativeLibFile = findNativeLibrary();
- if (nativeLibFile != null) {
- // Load extracted or specified native library.
- System.load(nativeLibFile.getAbsolutePath());
- } else {
- // Load preinstalled library (in the path -Djava.library.path)
- System.loadLibrary("commons-crypto");
- }
- LOG.debug("Loaded the native library");
- nativeLoaded = true;
- } catch (Throwable t) {
- // Ignore failure to load
- if (LOG.isDebugEnabled()) {
- LOG.debug("Failed to load native library with error: " + t);
- LOG.debug("java.library.path=" + System.getProperty("java.library.path"));
- }
- }
+ static {
+ // Try to load native library and set fallback flag appropriately
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Trying to load the custom-built native-commons-crypto library...");
+ }
- nativeCodeLoaded = nativeLoaded;
- if (!nativeCodeLoaded) {
- LOG.warn("Unable to load native library for the platform... "
- + "using builtin-java classes where applicable");
+ boolean nativeLoaded = false;
+ try {
+ File nativeLibFile = findNativeLibrary();
+ if (nativeLibFile != null) {
+ // Load extracted or specified native library.
+ System.load(nativeLibFile.getAbsolutePath());
+ } else {
+ // Load preinstalled library (in the path -Djava.library.path)
+ System.loadLibrary("commons-crypto");
+ }
+ LOG.debug("Loaded the native library");
+ nativeLoaded = true;
+ } catch (Throwable t) {
+ // Ignore failure to load
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Failed to load native library with error: " + t);
+ LOG.debug("java.library.path="
+ + System.getProperty("java.library.path"));
+ }
+ }
+
+ nativeCodeLoaded = nativeLoaded;
+ if (!nativeCodeLoaded) {
+ LOG.warn("Unable to load native library for the platform... "
+ + "using builtin-java classes where applicable");
+ }
}
- }
- static File findNativeLibrary() {
- // Try to load the library in commons-crypto.lib.path */
- String nativeLibraryPath = Utils
- .getLibPath();
- String nativeLibraryName = Utils
- .getLibName();
+ static File findNativeLibrary() {
+ // Try to load the library in commons-crypto.lib.path */
+ String nativeLibraryPath = Utils.getLibPath();
+ String nativeLibraryName = Utils.getLibName();
- // Resolve the library file name with a suffix (e.g., dll, .so, etc.)
- if (nativeLibraryName == null) {
- nativeLibraryName = System.mapLibraryName("commons-crypto");
- }
- if (nativeLibraryPath != null) {
- File nativeLib = new File(nativeLibraryPath,
- nativeLibraryName);
- if (nativeLib.exists()) {
- return nativeLib;
- }
- }
+ // Resolve the library file name with a suffix (e.g., dll, .so, etc.)
+ if (nativeLibraryName == null) {
+ nativeLibraryName = System.mapLibraryName("commons-crypto");
+ }
+ if (nativeLibraryPath != null) {
+ File nativeLib = new File(nativeLibraryPath, nativeLibraryName);
+ if (nativeLib.exists()) {
+ return nativeLib;
+ }
+ }
- // Load an OS-dependent native library inside a jar file
- nativeLibraryPath = "/org/apache/commons/crypto/native/"
- + OSInfo.getNativeLibFolderPathForCurrentOS();
- boolean hasNativeLib = hasResource(nativeLibraryPath + "/"
- + nativeLibraryName);
- if(!hasNativeLib) {
- if (OSInfo.getOSName().equals("Mac")) {
- // Fix for openjdk7 for Mac
- String altName = "libcommons-crypto.jnilib";
- if (hasResource(nativeLibraryPath + "/" + altName)) {
- nativeLibraryName = altName;
- hasNativeLib = true;
+ // Load an OS-dependent native library inside a jar file
+ nativeLibraryPath = "/org/apache/commons/crypto/native/"
+ + OSInfo.getNativeLibFolderPathForCurrentOS();
+ boolean hasNativeLib = hasResource(nativeLibraryPath + "/"
+ + nativeLibraryName);
+ if (!hasNativeLib) {
+ if (OSInfo.getOSName().equals("Mac")) {
+ // Fix for openjdk7 for Mac
+ String altName = "libcommons-crypto.jnilib";
+ if (hasResource(nativeLibraryPath + "/" + altName)) {
+ nativeLibraryName = altName;
+ hasNativeLib = true;
+ }
+ }
}
- }
- }
- if (!hasNativeLib) {
- String errorMessage = String.format(
- "no native library is found for os.name=%s and os.arch=%s",
- OSInfo.getOSName(), OSInfo.getArchName());
- throw new RuntimeException(errorMessage);
- }
+ if (!hasNativeLib) {
+ String errorMessage = String.format(
+ "no native library is found for os.name=%s and os.arch=%s",
+ OSInfo.getOSName(), OSInfo.getArchName());
+ throw new RuntimeException(errorMessage);
+ }
+
+ // Temporary folder for the native lib. Use the value of
+ // commons-crypto.tempdir or java.io.tmpdir
+ String tempFolder = new File(Utils.getTmpDir()).getAbsolutePath();
- // Temporary folder for the native lib. Use the value of
- // commons-crypto.tempdir or java.io.tmpdir
- String tempFolder = new File(Utils.getTmpDir())
- .getAbsolutePath();
+ // Extract and load a native library inside the jar file
+ return extractLibraryFile(nativeLibraryPath, nativeLibraryName,
+ tempFolder);
+ }
- // Extract and load a native library inside the jar file
- return extractLibraryFile(nativeLibraryPath,
- nativeLibraryName, tempFolder);
- }
+ /**
+ * Extracts the specified library file to the target folder.
+ *
+ * @param libFolderForCurrentOS the library in commons-crypto.lib.path.
+ * @param libraryFileName the library name.
+ * @param targetFolder Target folder for the native lib. Use the value of
+ * commons-crypto.tempdir or java.io.tmpdir.
+ * @return the library file.
+ */
+ private static File extractLibraryFile(String libFolderForCurrentOS,
+ String libraryFileName, String targetFolder) {
+ String nativeLibraryFilePath = libFolderForCurrentOS + "/"
+ + libraryFileName;
- /**
- * Extracts the specified library file to the target folder.
- *
- * @param libFolderForCurrentOS the library in commons-crypto.lib.path.
- * @param libraryFileName the library name.
- * @param targetFolder Target folder for the native lib. Use the value of
- * commons-crypto.tempdir or java.io.tmpdir.
- * @return the library file.
- */
- private static File extractLibraryFile(String libFolderForCurrentOS,
- String libraryFileName, String targetFolder) {
- String nativeLibraryFilePath = libFolderForCurrentOS + "/"
- + libraryFileName;
+ // Attach UUID to the native library file to ensure multiple class
+ // loaders
+ // can read the libcommons-crypto multiple times.
+ String uuid = UUID.randomUUID().toString();
+ String extractedLibFileName = String.format("commons-crypto-%s-%s-%s",
+ getVersion(), uuid, libraryFileName);
+ File extractedLibFile = new File(targetFolder, extractedLibFileName);
- // Attach UUID to the native library file to ensure multiple class loaders
- // can read the libcommons-crypto multiple times.
- String uuid = UUID.randomUUID().toString();
- String extractedLibFileName = String.format("commons-crypto-%s-%s-%s", getVersion(), uuid,
- libraryFileName);
- File extractedLibFile = new File(targetFolder, extractedLibFileName);
+ InputStream reader = null;
+ try {
+ // Extract a native library file into the target directory
+ reader = NativeCodeLoader.class
+ .getResourceAsStream(nativeLibraryFilePath);
+ FileOutputStream writer = new FileOutputStream(extractedLibFile);
+ try {
+ byte[] buffer = new byte[8192];
+ int bytesRead;
+ while ((bytesRead = reader.read(buffer)) != -1) {
+ writer.write(buffer, 0, bytesRead);
+ }
+ } finally {
+ // Delete the extracted lib file on JVM exit.
+ extractedLibFile.deleteOnExit();
- InputStream reader = null;
- try {
- // Extract a native library file into the target directory
- reader = NativeCodeLoader.class.getResourceAsStream(nativeLibraryFilePath);
- FileOutputStream writer = new FileOutputStream(extractedLibFile);
- try {
- byte[] buffer = new byte[8192];
- int bytesRead;
- while ((bytesRead = reader.read(buffer)) != -1) {
- writer.write(buffer, 0, bytesRead);
- }
- } finally {
- // Delete the extracted lib file on JVM exit.
- extractedLibFile.deleteOnExit();
+ if (writer != null) {
+ writer.close();
+ }
- if (writer != null){
- writer.close();
- }
+ if (reader != null) {
+ reader.close();
+ reader = null;
+ }
+ }
- if (reader != null) {
- reader.close();
- reader = null;
- }
- }
+ // Set executable (x) flag to enable Java to load the native library
+ if (!extractedLibFile.setReadable(true)
+ || !extractedLibFile.setExecutable(true)
+ || !extractedLibFile.setWritable(true, true)) {
+ throw new RuntimeException("Invalid path for library path");
+ }
- // Set executable (x) flag to enable Java to load the native library
- if (!extractedLibFile.setReadable(true) || !extractedLibFile.setExecutable(true)
- || !extractedLibFile.setWritable(true, true)) {
- throw new RuntimeException("Invalid path for library path");
- }
+ // Check whether the contents are properly copied from the resource
+ // folder
+ {
+ InputStream nativeIn = null;
+ InputStream extractedLibIn = null;
+ try {
+ nativeIn = NativeCodeLoader.class
+ .getResourceAsStream(nativeLibraryFilePath);
+ extractedLibIn = new FileInputStream(extractedLibFile);
+ if (!contentsEquals(nativeIn, extractedLibIn)) {
+ throw new RuntimeException(String.format(
+ "Failed to write a native library file at %s",
+ extractedLibFile));
+ }
+ } finally {
+ if (nativeIn != null) {
+ nativeIn.close();
+ }
+ if (extractedLibIn != null) {
+ extractedLibIn.close();
+ }
+ }
+ }
- // Check whether the contents are properly copied from the resource folder
- {
- InputStream nativeIn = null;
- InputStream extractedLibIn = null;
- try {
- nativeIn =
- NativeCodeLoader.class.getResourceAsStream(nativeLibraryFilePath);
- extractedLibIn = new FileInputStream(extractedLibFile);
- if (!contentsEquals(nativeIn, extractedLibIn)) {
- throw new RuntimeException(String.format(
- "Failed to write a native library file at %s",
- extractedLibFile));
- }
+ return new File(targetFolder, extractedLibFileName);
+ } catch (IOException e) {
+ e.printStackTrace(System.err);
+ return null;
} finally {
- if (nativeIn != null) {
- nativeIn.close();
- }
- if (extractedLibIn != null) {
- extractedLibIn.close();
- }
+ if (reader != null) {
+ try {
+ reader.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
}
- }
+ }
- return new File(targetFolder, extractedLibFileName);
- } catch (IOException e) {
- e.printStackTrace(System.err);
- return null;
- } finally{
- if(reader != null){
+ /**
+ * Gets the version by reading pom.properties embedded in jar. This version
+ * data is used as a suffix of a dll file extracted from the jar.
+ *
+ * @return the version string
+ */
+ public static String getVersion() {
+ URL versionFile = NativeCodeLoader.class
+ .getResource("/META-INF/maven/org.apache.commons.crypto/commons-crypto/pom.properties");
+ if (versionFile == null) {
+ versionFile = NativeCodeLoader.class
+ .getResource("/org/apache/commons/crypto/VERSION");
+ }
+ String version = "unknown";
try {
- reader.close();
+ if (versionFile != null) {
+ Properties versionData = new Properties();
+ versionData.load(versionFile.openStream());
+ version = versionData.getProperty("version", version);
+ if (version.equals("unknown")) {
+ version = versionData.getProperty("VERSION", version);
+ }
+ version = version.trim().replaceAll("[^0-9M\\.]", "");
+ }
} catch (IOException e) {
- e.printStackTrace();
+ System.err.println(e);
}
- }
+ return version;
}
- }
- /**
- * Gets the version by reading pom.properties embedded in jar.
- * This version data is used as a suffix of a dll file extracted from the
- * jar.
- *
- * @return the version string
- */
- public static String getVersion() {
- URL versionFile = NativeCodeLoader.class
- .getResource("/META-INF/maven/org.apache.commons.crypto/commons-crypto/pom.properties");
- if (versionFile == null) {
- versionFile = NativeCodeLoader.class
- .getResource("/org/apache/commons/crypto/VERSION");
- }
- String version = "unknown";
- try {
- if (versionFile != null) {
- Properties versionData = new Properties();
- versionData.load(versionFile.openStream());
- version = versionData.getProperty("version", version);
- if (version.equals("unknown")) {
- version = versionData.getProperty("VERSION", version);
+ private static boolean contentsEquals(InputStream in1, InputStream in2)
+ throws IOException {
+ if (!(in1 instanceof BufferedInputStream)) {
+ in1 = new BufferedInputStream(in1);
+ }
+ if (!(in2 instanceof BufferedInputStream)) {
+ in2 = new BufferedInputStream(in2);
}
- version = version.trim().replaceAll("[^0-9M\\.]", "");
- }
- } catch (IOException e) {
- System.err.println(e);
- }
- return version;
- }
- private static boolean contentsEquals(InputStream in1, InputStream in2)
- throws IOException {
- if (!(in1 instanceof BufferedInputStream)) {
- in1 = new BufferedInputStream(in1);
- }
- if (!(in2 instanceof BufferedInputStream)) {
- in2 = new BufferedInputStream(in2);
+ int ch = in1.read();
+ while (ch != -1) {
+ int ch2 = in2.read();
+ if (ch != ch2) {
+ return false;
+ }
+ ch = in1.read();
+ }
+ int ch2 = in2.read();
+ return ch2 == -1;
}
- int ch = in1.read();
- while (ch != -1) {
- int ch2 = in2.read();
- if (ch != ch2) {
- return false;
- }
- ch = in1.read();
+ private static boolean hasResource(String path) {
+ return NativeCodeLoader.class.getResource(path) != null;
}
- int ch2 = in2.read();
- return ch2 == -1;
- }
- private static boolean hasResource(String path) {
- return NativeCodeLoader.class.getResource(path) != null;
- }
-
- /**
- * Checks whether native code is loaded for this platform.
- *
- * @return <code>true</code> if native is loaded,
- * else <code>false</code>.
- */
- public static boolean isNativeCodeLoaded() {
- return nativeCodeLoaded;
- }
+ /**
+ * Checks whether native code is loaded for this platform.
+ *
+ * @return <code>true</code> if native is loaded, else <code>false</code>.
+ */
+ public static boolean isNativeCodeLoaded() {
+ return nativeCodeLoaded;
+ }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/utils/OSInfo.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/utils/OSInfo.java b/src/main/java/org/apache/commons/crypto/utils/OSInfo.java
index 9d1cb88..21f2fe3 100644
--- a/src/main/java/org/apache/commons/crypto/utils/OSInfo.java
+++ b/src/main/java/org/apache/commons/crypto/utils/OSInfo.java
@@ -25,170 +25,184 @@ import java.util.Locale;
* Provides OS name and architecture name.
*/
public class OSInfo {
- private final static HashMap<String, String> archMapping = new HashMap<String, String>();
-
- /**
- * The constant string represents for X86 architecture, the value is: {@value #X86}.*/
- public static final String X86 = "x86";
-
- /**
- * The constant string represents for X86_64 architecture, the value is:{@value #X86_64}.*/
- public static final String X86_64 = "x86_64";
-
- /**
- * The constant string represents for IA64_32 architecture, the value is:{@value #IA64_32}.*/
- public static final String IA64_32 = "ia64_32";
-
- /**
- * The constant string represents for IA64 architecture, the value is:{@value #IA64}.*/
- public static final String IA64 = "ia64";
-
- /**
- * The constant string represents for PPC architecture, the value is:{@value #PPC}.*/
- public static final String PPC = "ppc";
-
- /**
- * The constant string represents for PPC64 architecture, the value is:{@value #PPC64}.*/
- public static final String PPC64 = "ppc64";
-
- private OSInfo() {}
-
- static {
- // x86 mappings
- archMapping.put(X86, X86);
- archMapping.put("i386", X86);
- archMapping.put("i486", X86);
- archMapping.put("i586", X86);
- archMapping.put("i686", X86);
- archMapping.put("pentium", X86);
-
- // x86_64 mappings
- archMapping.put(X86_64, X86_64);
- archMapping.put("amd64", X86_64);
- archMapping.put("em64t", X86_64);
- archMapping.put("universal", X86_64); // Needed for openjdk7 in Mac
-
- // Itenium 64-bit mappings
- archMapping.put(IA64, IA64);
- archMapping.put("ia64w", IA64);
-
- // Itenium 32-bit mappings, usually an HP-UX construct
- archMapping.put(IA64_32, IA64_32);
- archMapping.put("ia64n", IA64_32);
-
- // PowerPC mappings
- archMapping.put(PPC, PPC);
- archMapping.put("power", PPC);
- archMapping.put("powerpc", PPC);
- archMapping.put("power_pc", PPC);
- archMapping.put("power_rs", PPC);
-
- // TODO: PowerPC 64bit mappings
- archMapping.put(PPC64, PPC64);
- archMapping.put("power64", PPC64);
- archMapping.put("powerpc64", PPC64);
- archMapping.put("power_pc64", PPC64);
- archMapping.put("power_rs64", PPC64);
- }
-
- public static void main(String[] args) {
- if (args.length >= 1) {
- if ("--os".equals(args[0])) {
- System.out.print(getOSName());
- return;
- } else if ("--arch".equals(args[0])) {
- System.out.print(getArchName());
- return;
- }
+ private final static HashMap<String, String> archMapping = new HashMap<String, String>();
+
+ /**
+ * The constant string represents for X86 architecture, the value is:
+ * {@value #X86}.
+ */
+ public static final String X86 = "x86";
+
+ /**
+ * The constant string represents for X86_64 architecture, the value is:
+ * {@value #X86_64}.
+ */
+ public static final String X86_64 = "x86_64";
+
+ /**
+ * The constant string represents for IA64_32 architecture, the value is:
+ * {@value #IA64_32}.
+ */
+ public static final String IA64_32 = "ia64_32";
+
+ /**
+ * The constant string represents for IA64 architecture, the value is:
+ * {@value #IA64}.
+ */
+ public static final String IA64 = "ia64";
+
+ /**
+ * The constant string represents for PPC architecture, the value is:
+ * {@value #PPC}.
+ */
+ public static final String PPC = "ppc";
+
+ /**
+ * The constant string represents for PPC64 architecture, the value is:
+ * {@value #PPC64}.
+ */
+ public static final String PPC64 = "ppc64";
+
+ private OSInfo() {
}
- System.out.print(getNativeLibFolderPathForCurrentOS());
- }
-
- /**
- * Gets the native lib folder.
- *
- * @return the current OS's native lib folder.
- */
- public static String getNativeLibFolderPathForCurrentOS() {
- return getOSName() + "/" + getArchName();
- }
-
- /**
- * Gets the OS name.
- *
- * @return the OS name.
- */
- public static String getOSName() {
- return translateOSNameToFolderName(System.getProperty("os.name"));
- }
-
- /**
- * Gets the architecture name.
- *
- * @return the architecture name.
- */
- public static String getArchName() {
- // if running Linux on ARM, need to determine ABI of JVM
- String osArch = System.getProperty("os.arch");
- if (osArch.startsWith("arm")
- && System.getProperty("os.name").contains("Linux")) {
- String javaHome = System.getProperty("java.home");
- try {
- // determine if first JVM found uses ARM hard-float ABI
- String[] cmdarray = {
- "/bin/sh",
- "-c",
- "find '" + javaHome
- + "' -name 'libjvm.so' | head -1 | xargs readelf -A | "
- + "grep 'Tag_ABI_VFP_args: VFP registers'" };
- int exitCode = Runtime.getRuntime().exec(cmdarray).waitFor();
- if (exitCode == 0) {
- return "armhf";
+ static {
+ // x86 mappings
+ archMapping.put(X86, X86);
+ archMapping.put("i386", X86);
+ archMapping.put("i486", X86);
+ archMapping.put("i586", X86);
+ archMapping.put("i686", X86);
+ archMapping.put("pentium", X86);
+
+ // x86_64 mappings
+ archMapping.put(X86_64, X86_64);
+ archMapping.put("amd64", X86_64);
+ archMapping.put("em64t", X86_64);
+ archMapping.put("universal", X86_64); // Needed for openjdk7 in Mac
+
+ // Itenium 64-bit mappings
+ archMapping.put(IA64, IA64);
+ archMapping.put("ia64w", IA64);
+
+ // Itenium 32-bit mappings, usually an HP-UX construct
+ archMapping.put(IA64_32, IA64_32);
+ archMapping.put("ia64n", IA64_32);
+
+ // PowerPC mappings
+ archMapping.put(PPC, PPC);
+ archMapping.put("power", PPC);
+ archMapping.put("powerpc", PPC);
+ archMapping.put("power_pc", PPC);
+ archMapping.put("power_rs", PPC);
+
+ // TODO: PowerPC 64bit mappings
+ archMapping.put(PPC64, PPC64);
+ archMapping.put("power64", PPC64);
+ archMapping.put("powerpc64", PPC64);
+ archMapping.put("power_pc64", PPC64);
+ archMapping.put("power_rs64", PPC64);
+ }
+
+ public static void main(String[] args) {
+ if (args.length >= 1) {
+ if ("--os".equals(args[0])) {
+ System.out.print(getOSName());
+ return;
+ } else if ("--arch".equals(args[0])) {
+ System.out.print(getArchName());
+ return;
+ }
+ }
+
+ System.out.print(getNativeLibFolderPathForCurrentOS());
+ }
+
+ /**
+ * Gets the native lib folder.
+ *
+ * @return the current OS's native lib folder.
+ */
+ public static String getNativeLibFolderPathForCurrentOS() {
+ return getOSName() + "/" + getArchName();
+ }
+
+ /**
+ * Gets the OS name.
+ *
+ * @return the OS name.
+ */
+ public static String getOSName() {
+ return translateOSNameToFolderName(System.getProperty("os.name"));
+ }
+
+ /**
+ * Gets the architecture name.
+ *
+ * @return the architecture name.
+ */
+ public static String getArchName() {
+ // if running Linux on ARM, need to determine ABI of JVM
+ String osArch = System.getProperty("os.arch");
+ if (osArch.startsWith("arm")
+ && System.getProperty("os.name").contains("Linux")) {
+ String javaHome = System.getProperty("java.home");
+ try {
+ // determine if first JVM found uses ARM hard-float ABI
+ String[] cmdarray = {
+ "/bin/sh",
+ "-c",
+ "find '"
+ + javaHome
+ + "' -name 'libjvm.so' | head -1 | xargs readelf -A | "
+ + "grep 'Tag_ABI_VFP_args: VFP registers'" };
+ int exitCode = Runtime.getRuntime().exec(cmdarray).waitFor();
+ if (exitCode == 0) {
+ return "armhf";
+ }
+ } catch (IOException e) {
+ // ignored: fall back to "arm" arch (soft-float ABI)
+ } catch (InterruptedException e) {
+ // ignored: fall back to "arm" arch (soft-float ABI)
+ }
+ } else {
+ String lc = osArch.toLowerCase(Locale.US);
+ if (archMapping.containsKey(lc)) {
+ return archMapping.get(lc);
+ }
}
- } catch (IOException e) {
- // ignored: fall back to "arm" arch (soft-float ABI)
- } catch (InterruptedException e) {
- // ignored: fall back to "arm" arch (soft-float ABI)
- }
- } else {
- String lc = osArch.toLowerCase(Locale.US);
- if (archMapping.containsKey(lc)) {
- return archMapping.get(lc);
- }
+ return translateArchNameToFolderName(osArch);
}
- return translateArchNameToFolderName(osArch);
- }
-
- /**
- * Translates the OS name to folder name.
- *
- * @param osName the OS name.
- * @return the folder name.
- */
- static String translateOSNameToFolderName(String osName) {
- if (osName.contains("Windows")) {
- return "Windows";
- } else if (osName.contains("Mac")) {
- return "Mac";
- } else if (osName.contains("Linux")) {
- return "Linux";
- } else if (osName.contains("AIX")) {
- return "AIX";
+
+ /**
+ * Translates the OS name to folder name.
+ *
+ * @param osName the OS name.
+ * @return the folder name.
+ */
+ static String translateOSNameToFolderName(String osName) {
+ if (osName.contains("Windows")) {
+ return "Windows";
+ } else if (osName.contains("Mac")) {
+ return "Mac";
+ } else if (osName.contains("Linux")) {
+ return "Linux";
+ } else if (osName.contains("AIX")) {
+ return "AIX";
+ }
+
+ else {
+ return osName.replaceAll("\\W", "");
+ }
}
- else {
- return osName.replaceAll("\\W", "");
+ /**
+ * Translates the architecture name to folder name.
+ *
+ * @param archName the architecture name.
+ * @return the folder name.
+ */
+ static String translateArchNameToFolderName(String archName) {
+ return archName.replaceAll("\\W", "");
}
- }
-
- /**
- * Translates the architecture name to folder name.
- *
- * @param archName the architecture name.
- * @return the folder name.
- */
- static String translateArchNameToFolderName(String archName) {
- return archName.replaceAll("\\W", "");
- }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/utils/ReflectionUtils.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/utils/ReflectionUtils.java b/src/main/java/org/apache/commons/crypto/utils/ReflectionUtils.java
index ce077d7..aab3196 100644
--- a/src/main/java/org/apache/commons/crypto/utils/ReflectionUtils.java
+++ b/src/main/java/org/apache/commons/crypto/utils/ReflectionUtils.java
@@ -30,180 +30,182 @@ import org.apache.commons.crypto.cipher.CryptoCipher;
*/
public class ReflectionUtils {
- private static final Map<ClassLoader, Map<String, WeakReference<Class<?>>>>
- CACHE_CLASSES = new WeakHashMap<ClassLoader, Map<String, WeakReference<Class<?>>>>();
-
- private final static ClassLoader classLoader;
-
- static {
- ClassLoader threadClassLoader = Thread.currentThread().getContextClassLoader();
- classLoader = (threadClassLoader != null) ? threadClassLoader : CryptoCipher.class.getClassLoader();
- }
-
- /**
- * Sentinel value to store negative cache results in {@link #CACHE_CLASSES}.
- */
- private static final Class<?> NEGATIVE_CACHE_SENTINEL =
- NegativeCacheSentinel.class;
-
- private ReflectionUtils() {}
-
- /**
- * A unique class which is used as a sentinel value in the caching
- * for getClassByName. {@link CryptoCipher#getClassByNameOrNull(String)}.
- */
- private static abstract class NegativeCacheSentinel {}
-
- /**
- * Uses the constructor represented by this {@code Constructor} object to
- * create and initialize a new instance of the constructor's
- * declaring class, with the specified initialization parameters.
- *
- * @param <T> type for the new instance
- * @param klass the Class object.
- * @param args array of objects to be passed as arguments to
- * the constructor call.
- * @return a new object created by calling the constructor
- * this object represents.
- */
- @SuppressWarnings("rawtypes")
- public static <T> T newInstance(Class<T> klass, Object ... args) {
- try {
- Constructor<T> ctor = null;
-
- if (args.length == 0) {
- ctor = klass.getDeclaredConstructor(new Class[] {});
- } else {
- Class[] argClses = new Class[args.length];
- for (int i = 0; i < args.length; i++) {
- argClses[i] = args[i].getClass();
- }
- ctor = klass.getDeclaredConstructor(argClses);
- }
- ctor.setAccessible(true);
- return ctor.newInstance(args);
- } catch (Exception e) {
- throw new RuntimeException(e);
+ private static final Map<ClassLoader, Map<String, WeakReference<Class<?>>>> CACHE_CLASSES = new WeakHashMap<ClassLoader, Map<String, WeakReference<Class<?>>>>();
+
+ private final static ClassLoader classLoader;
+
+ static {
+ ClassLoader threadClassLoader = Thread.currentThread()
+ .getContextClassLoader();
+ classLoader = (threadClassLoader != null) ? threadClassLoader
+ : CryptoCipher.class.getClassLoader();
}
- }
-
- /**
- * Gets the value of the <code>name</code> property as a <code>Class</code>
- * implementing the interface specified by <code>xface</code>.
- * If no such property is specified, then <code>defaultValue</code> is
- * returned.An exception is thrown if the returned class does not
- * implement the named interface.
- *
- * @param <U> type for the class.
- * @param name the class name of default implementation.
- * @param defaultValue default value.
- * @param xface the interface implemented by the named class.
- * @return property value as a <code>Class</code>,
- * or <code>defaultValue</code>.
- */
- public static <U> Class<? extends U> getClass(String name,
- Class<? extends U> defaultValue,
- Class<U> xface) {
- try {
- Class<?> theClass = null;
- if (name != null && !name.isEmpty()) {
- theClass = getClassByName(name);
- }
- if (theClass == null) {
- theClass = defaultValue;
- }
- if (theClass != null && !xface.isAssignableFrom(theClass)) {
- throw new RuntimeException(theClass+" not "+xface.getName());
- } else if (theClass != null) {
- return theClass.asSubclass(xface);
- } else {
- return null;
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
+
+ /**
+ * Sentinel value to store negative cache results in {@link #CACHE_CLASSES}.
+ */
+ private static final Class<?> NEGATIVE_CACHE_SENTINEL = NegativeCacheSentinel.class;
+
+ private ReflectionUtils() {
}
- }
-
- /**
- * Gets the value of the <code>name</code> property as a <code>Class</code>.
- * If no such property is specified, then <code>defaultValue</code> is
- * returned.
- *
- * @param name the class name.
- * @param defaultValue default value.
- * @return property value as a <code>Class</code>,
- * or <code>defaultValue</code>.
- */
- public static Class<?> getClass(String name, Class<?> defaultValue) {
- String valueString = System.getProperty(name);
- if (valueString == null) {
- return defaultValue;
+
+ /**
+ * A unique class which is used as a sentinel value in the caching for
+ * getClassByName. {@link CryptoCipher#getClassByNameOrNull(String)}.
+ */
+ private static abstract class NegativeCacheSentinel {
}
- try {
- return getClassByName(valueString);
- } catch (ClassNotFoundException e) {
- throw new RuntimeException(e);
+
+ /**
+ * Uses the constructor represented by this {@code Constructor} object to
+ * create and initialize a new instance of the constructor's declaring
+ * class, with the specified initialization parameters.
+ *
+ * @param <T> type for the new instance
+ * @param klass the Class object.
+ * @param args array of objects to be passed as arguments to the constructor
+ * call.
+ * @return a new object created by calling the constructor this object
+ * represents.
+ */
+ @SuppressWarnings("rawtypes")
+ public static <T> T newInstance(Class<T> klass, Object... args) {
+ try {
+ Constructor<T> ctor = null;
+
+ if (args.length == 0) {
+ ctor = klass.getDeclaredConstructor(new Class[] {});
+ } else {
+ Class[] argClses = new Class[args.length];
+ for (int i = 0; i < args.length; i++) {
+ argClses[i] = args[i].getClass();
+ }
+ ctor = klass.getDeclaredConstructor(argClses);
+ }
+ ctor.setAccessible(true);
+ return ctor.newInstance(args);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
}
- }
-
- /**
- * Loads a class by name.
- *
- * @param name the class name.
- * @return the class object.
- * @throws ClassNotFoundException if the class is not found.
- */
- public static Class<?> getClassByName(String name)
- throws ClassNotFoundException {
- Class<?> ret = getClassByNameOrNull(name);
- if (ret == null) {
- throw new ClassNotFoundException("Class " + name + " not found");
+
+ /**
+ * Gets the value of the <code>name</code> property as a <code>Class</code>
+ * implementing the interface specified by <code>xface</code>. If no such
+ * property is specified, then <code>defaultValue</code> is returned.An
+ * exception is thrown if the returned class does not implement the named
+ * interface.
+ *
+ * @param <U> type for the class.
+ * @param name the class name of default implementation.
+ * @param defaultValue default value.
+ * @param xface the interface implemented by the named class.
+ * @return property value as a <code>Class</code>, or
+ * <code>defaultValue</code>.
+ */
+ public static <U> Class<? extends U> getClass(String name,
+ Class<? extends U> defaultValue, Class<U> xface) {
+ try {
+ Class<?> theClass = null;
+ if (name != null && !name.isEmpty()) {
+ theClass = getClassByName(name);
+ }
+ if (theClass == null) {
+ theClass = defaultValue;
+ }
+ if (theClass != null && !xface.isAssignableFrom(theClass)) {
+ throw new RuntimeException(theClass + " not " + xface.getName());
+ } else if (theClass != null) {
+ return theClass.asSubclass(xface);
+ } else {
+ return null;
+ }
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
}
- return ret;
- }
-
- /**
- * Loads a class by name, returning null rather than throwing an exception
- * if it couldn't be loaded. This is to avoid the overhead of creating
- * an exception.
- *
- * @param name the class name.
- * @return the class object, or null if it could not be found.
- */
- private static Class<?> getClassByNameOrNull(String name) {
- Map<String, WeakReference<Class<?>>> map;
-
- synchronized (CACHE_CLASSES) {
- map = CACHE_CLASSES.get(classLoader);
- if (map == null) {
- map = Collections.synchronizedMap(
- new WeakHashMap<String, WeakReference<Class<?>>>());
- CACHE_CLASSES.put(classLoader, map);
- }
+
+ /**
+ * Gets the value of the <code>name</code> property as a <code>Class</code>.
+ * If no such property is specified, then <code>defaultValue</code> is
+ * returned.
+ *
+ * @param name the class name.
+ * @param defaultValue default value.
+ * @return property value as a <code>Class</code>, or
+ * <code>defaultValue</code>.
+ */
+ public static Class<?> getClass(String name, Class<?> defaultValue) {
+ String valueString = System.getProperty(name);
+ if (valueString == null) {
+ return defaultValue;
+ }
+ try {
+ return getClassByName(valueString);
+ } catch (ClassNotFoundException e) {
+ throw new RuntimeException(e);
+ }
}
- Class<?> clazz = null;
- WeakReference<Class<?>> ref = map.get(name);
- if (ref != null) {
- clazz = ref.get();
+ /**
+ * Loads a class by name.
+ *
+ * @param name the class name.
+ * @return the class object.
+ * @throws ClassNotFoundException if the class is not found.
+ */
+ public static Class<?> getClassByName(String name)
+ throws ClassNotFoundException {
+ Class<?> ret = getClassByNameOrNull(name);
+ if (ret == null) {
+ throw new ClassNotFoundException("Class " + name + " not found");
+ }
+ return ret;
}
- if (clazz == null) {
- try {
- clazz = Class.forName(name, true, classLoader);
- } catch (ClassNotFoundException e) {
- // Leave a marker that the class isn't found
- map.put(name, new WeakReference<Class<?>>(NEGATIVE_CACHE_SENTINEL));
- return null;
- }
- // two putters can race here, but they'll put the same class
- map.put(name, new WeakReference<Class<?>>(clazz));
- return clazz;
- } else if (clazz == NEGATIVE_CACHE_SENTINEL) {
- return null; // not found
- } else {
- // cache hit
- return clazz;
+ /**
+ * Loads a class by name, returning null rather than throwing an exception
+ * if it couldn't be loaded. This is to avoid the overhead of creating an
+ * exception.
+ *
+ * @param name the class name.
+ * @return the class object, or null if it could not be found.
+ */
+ private static Class<?> getClassByNameOrNull(String name) {
+ Map<String, WeakReference<Class<?>>> map;
+
+ synchronized (CACHE_CLASSES) {
+ map = CACHE_CLASSES.get(classLoader);
+ if (map == null) {
+ map = Collections
+ .synchronizedMap(new WeakHashMap<String, WeakReference<Class<?>>>());
+ CACHE_CLASSES.put(classLoader, map);
+ }
+ }
+
+ Class<?> clazz = null;
+ WeakReference<Class<?>> ref = map.get(name);
+ if (ref != null) {
+ clazz = ref.get();
+ }
+
+ if (clazz == null) {
+ try {
+ clazz = Class.forName(name, true, classLoader);
+ } catch (ClassNotFoundException e) {
+ // Leave a marker that the class isn't found
+ map.put(name, new WeakReference<Class<?>>(
+ NEGATIVE_CACHE_SENTINEL));
+ return null;
+ }
+ // two putters can race here, but they'll put the same class
+ map.put(name, new WeakReference<Class<?>>(clazz));
+ return clazz;
+ } else if (clazz == NEGATIVE_CACHE_SENTINEL) {
+ return null; // not found
+ } else {
+ // cache hit
+ return clazz;
+ }
}
- }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/utils/Utils.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/utils/Utils.java b/src/main/java/org/apache/commons/crypto/utils/Utils.java
index 16ce270..17c98c2 100644
--- a/src/main/java/org/apache/commons/crypto/utils/Utils.java
+++ b/src/main/java/org/apache/commons/crypto/utils/Utils.java
@@ -47,330 +47,338 @@ import static org.apache.commons.crypto.conf.ConfigurationKeys.COMMONS_CRYPTO_LI
* General utility methods.
*/
public class Utils {
- private static final int MIN_BUFFER_SIZE = 512;
+ private static final int MIN_BUFFER_SIZE = 512;
- protected static final CipherTransformation AES_CTR_NOPADDING = CipherTransformation.AES_CTR_NOPADDING;
+ protected static final CipherTransformation AES_CTR_NOPADDING = CipherTransformation.AES_CTR_NOPADDING;
- /**
- * For AES, the algorithm block is fixed size of 128 bits.
- * @see <a href="http://en.wikipedia.org/wiki/Advanced_Encryption_Standard">
- * http://en.wikipedia.org/wiki/Advanced_Encryption_Standard</a>
- */
- private static final int AES_BLOCK_SIZE = AES_CTR_NOPADDING.getAlgorithmBlockSize();
+ /**
+ * For AES, the algorithm block is fixed size of 128 bits.
+ *
+ * @see <a href="http://en.wikipedia.org/wiki/Advanced_Encryption_Standard">
+ * http://en.wikipedia.org/wiki/Advanced_Encryption_Standard</a>
+ */
+ private static final int AES_BLOCK_SIZE = AES_CTR_NOPADDING
+ .getAlgorithmBlockSize();
- private Utils() {}
+ private Utils() {
+ }
- static {
- loadSystemProperties();
- }
+ static {
+ loadSystemProperties();
+ }
- /**
- * loads system properties when configuration file of the name
- * {@link #COMMONS_CRYPTO_SYSTEM_PROPERTIES_FILE} is found.
- */
- private static void loadSystemProperties() {
- try {
- InputStream is = Thread.currentThread().getContextClassLoader()
- .getResourceAsStream(COMMONS_CRYPTO_SYSTEM_PROPERTIES_FILE);
+ /**
+ * loads system properties when configuration file of the name
+ * {@link #COMMONS_CRYPTO_SYSTEM_PROPERTIES_FILE} is found.
+ */
+ private static void loadSystemProperties() {
+ try {
+ InputStream is = Thread.currentThread().getContextClassLoader()
+ .getResourceAsStream(COMMONS_CRYPTO_SYSTEM_PROPERTIES_FILE);
- if (is == null) {
- return; // no configuration file is found
- }
- // Load property file
- Properties props = new Properties();
- props.load(is);
- is.close();
- Enumeration<?> names = props.propertyNames();
- while (names.hasMoreElements()) {
- String name = (String) names.nextElement();
- if (name.startsWith(ConfigurationKeys.CONF_PREFIX)) {
- if (System.getProperty(name) == null) {
- System.setProperty(name, props.getProperty(name));
- }
+ if (is == null) {
+ return; // no configuration file is found
+ }
+ // Load property file
+ Properties props = new Properties();
+ props.load(is);
+ is.close();
+ Enumeration<?> names = props.propertyNames();
+ while (names.hasMoreElements()) {
+ String name = (String) names.nextElement();
+ if (name.startsWith(ConfigurationKeys.CONF_PREFIX)) {
+ if (System.getProperty(name) == null) {
+ System.setProperty(name, props.getProperty(name));
+ }
+ }
+ }
+ } catch (Throwable ex) {
+ System.err.println("Could not load '"
+ + COMMONS_CRYPTO_SYSTEM_PROPERTIES_FILE
+ + "' from classpath: " + ex.toString());
}
- }
- } catch (Throwable ex) {
- System.err.println("Could not load '"
- + COMMONS_CRYPTO_SYSTEM_PROPERTIES_FILE + "' from classpath: "
- + ex.toString());
}
- }
- /**
- * Forcibly free the direct buffer.
- *
- * @param buffer the bytebuffer to be freed.
- */
- public static void freeDirectBuffer(ByteBuffer buffer) {
- if (buffer instanceof sun.nio.ch.DirectBuffer) {
- final sun.misc.Cleaner bufferCleaner =
- ((sun.nio.ch.DirectBuffer) buffer).cleaner();
- bufferCleaner.clean();
+ /**
+ * Forcibly free the direct buffer.
+ *
+ * @param buffer the bytebuffer to be freed.
+ */
+ public static void freeDirectBuffer(ByteBuffer buffer) {
+ if (buffer instanceof sun.nio.ch.DirectBuffer) {
+ final sun.misc.Cleaner bufferCleaner = ((sun.nio.ch.DirectBuffer) buffer)
+ .cleaner();
+ bufferCleaner.clean();
+ }
}
- }
- /**
- * Reads crypto buffer size.
- *
- * @param props The <code>Properties</code> class represents a set of
- * properties.
- * @return the buffer size.
- * */
- public static int getBufferSize(Properties props) {
- String bufferSizeStr = props.getProperty(
- COMMONS_CRYPTO_STREAM_BUFFER_SIZE_KEY);
- if (bufferSizeStr == null || bufferSizeStr.isEmpty()) {
- bufferSizeStr = System
- .getProperty(COMMONS_CRYPTO_STREAM_BUFFER_SIZE_KEY);
- }
- if (bufferSizeStr == null || bufferSizeStr.isEmpty()) {
- return COMMONS_CRYPTO_STREAM_BUFFER_SIZE_DEFAULT;
- } else {
- return Integer.parseInt(bufferSizeStr);
+ /**
+ * Reads crypto buffer size.
+ *
+ * @param props The <code>Properties</code> class represents a set of
+ * properties.
+ * @return the buffer size.
+ * */
+ public static int getBufferSize(Properties props) {
+ String bufferSizeStr = props
+ .getProperty(COMMONS_CRYPTO_STREAM_BUFFER_SIZE_KEY);
+ if (bufferSizeStr == null || bufferSizeStr.isEmpty()) {
+ bufferSizeStr = System
+ .getProperty(COMMONS_CRYPTO_STREAM_BUFFER_SIZE_KEY);
+ }
+ if (bufferSizeStr == null || bufferSizeStr.isEmpty()) {
+ return COMMONS_CRYPTO_STREAM_BUFFER_SIZE_DEFAULT;
+ } else {
+ return Integer.parseInt(bufferSizeStr);
+ }
}
- }
- /**
- * Gets the cipher class.
- *
- * @param props The <code>Properties</code> class represents a set of
- * properties.
- * @return the cipher class based on the props.
- */
- public static String getCipherClassString(Properties props) {
- final String configName = COMMONS_CRYPTO_CIPHER_CLASSES_KEY;
- String cipherClassString = props.getProperty(configName) != null ? props
- .getProperty(configName, COMMONS_CRYPTO_CIPHER_CLASSES_DEFAULT) : System
- .getProperty(configName, COMMONS_CRYPTO_CIPHER_CLASSES_DEFAULT);
- if (cipherClassString.isEmpty()) {
- cipherClassString = COMMONS_CRYPTO_CIPHER_CLASSES_DEFAULT;
+ /**
+ * Gets the cipher class.
+ *
+ * @param props The <code>Properties</code> class represents a set of
+ * properties.
+ * @return the cipher class based on the props.
+ */
+ public static String getCipherClassString(Properties props) {
+ final String configName = COMMONS_CRYPTO_CIPHER_CLASSES_KEY;
+ String cipherClassString = props.getProperty(configName) != null ? props
+ .getProperty(configName, COMMONS_CRYPTO_CIPHER_CLASSES_DEFAULT)
+ : System.getProperty(configName,
+ COMMONS_CRYPTO_CIPHER_CLASSES_DEFAULT);
+ if (cipherClassString.isEmpty()) {
+ cipherClassString = COMMONS_CRYPTO_CIPHER_CLASSES_DEFAULT;
+ }
+ return cipherClassString;
}
- return cipherClassString;
- }
- /**
- * Gets the Jce provider.
- *
- * @param props The <code>Properties</code> class represents a set of
- * properties.
- * @return the jce provider based on the props.
- */
- public static String getJCEProvider(Properties props) {
- return props.getProperty(COMMONS_CRYPTO_CIPHER_JCE_PROVIDER_KEY) != null ?
- props.getProperty(COMMONS_CRYPTO_CIPHER_JCE_PROVIDER_KEY) :
- System.getProperty(COMMONS_CRYPTO_CIPHER_JCE_PROVIDER_KEY);
- }
+ /**
+ * Gets the Jce provider.
+ *
+ * @param props The <code>Properties</code> class represents a set of
+ * properties.
+ * @return the jce provider based on the props.
+ */
+ public static String getJCEProvider(Properties props) {
+ return props.getProperty(COMMONS_CRYPTO_CIPHER_JCE_PROVIDER_KEY) != null ? props
+ .getProperty(COMMONS_CRYPTO_CIPHER_JCE_PROVIDER_KEY) : System
+ .getProperty(COMMONS_CRYPTO_CIPHER_JCE_PROVIDER_KEY);
+ }
- /**
- * Gets the random device path.
- *
- * @param props The <code>Properties</code> class represents a set of
- * properties.
- * @return the random device path based on the props.
- */
- public static String getRandomDevPath(Properties props) {
- String devPath = props.getProperty(
- COMMONS_CRYPTO_SECURE_RANDOM_DEVICE_FILE_PATH_KEY);
- if (devPath == null) {
- devPath = System.getProperty(
- COMMONS_CRYPTO_SECURE_RANDOM_DEVICE_FILE_PATH_KEY,
- COMMONS_CRYPTO_SECURE_RANDOM_DEVICE_FILE_PATH_DEFAULT);
+ /**
+ * Gets the random device path.
+ *
+ * @param props The <code>Properties</code> class represents a set of
+ * properties.
+ * @return the random device path based on the props.
+ */
+ public static String getRandomDevPath(Properties props) {
+ String devPath = props
+ .getProperty(COMMONS_CRYPTO_SECURE_RANDOM_DEVICE_FILE_PATH_KEY);
+ if (devPath == null) {
+ devPath = System.getProperty(
+ COMMONS_CRYPTO_SECURE_RANDOM_DEVICE_FILE_PATH_KEY,
+ COMMONS_CRYPTO_SECURE_RANDOM_DEVICE_FILE_PATH_DEFAULT);
+ }
+ return devPath;
}
- return devPath;
- }
- /**
- * Gets path of native library.
- *
- * @return the path of native library.
- */
- public static String getLibPath() {
- return System.getProperty(COMMONS_CRYPTO_LIB_PATH_KEY);
- }
+ /**
+ * Gets path of native library.
+ *
+ * @return the path of native library.
+ */
+ public static String getLibPath() {
+ return System.getProperty(COMMONS_CRYPTO_LIB_PATH_KEY);
+ }
- /**
- * Gets the file name of native library.
- *
- * @return the file name of native library.
- */
- public static String getLibName() {
- return System.getProperty(COMMONS_CRYPTO_LIB_NAME_KEY);
- }
+ /**
+ * Gets the file name of native library.
+ *
+ * @return the file name of native library.
+ */
+ public static String getLibName() {
+ return System.getProperty(COMMONS_CRYPTO_LIB_NAME_KEY);
+ }
- /**
- * Gets the temp directory for extracting crypto library.
- *
- * @return the temp directory.
- */
- public static String getTmpDir() {
- return System.getProperty(COMMONS_CRYPTO_LIB_TEMPDIR_KEY,
- System.getProperty("java.io.tmpdir"));
- }
+ /**
+ * Gets the temp directory for extracting crypto library.
+ *
+ * @return the temp directory.
+ */
+ public static String getTmpDir() {
+ return System.getProperty(COMMONS_CRYPTO_LIB_TEMPDIR_KEY,
+ System.getProperty("java.io.tmpdir"));
+ }
- /**
- * Checks whether the cipher is supported streaming.
- *
- * @param cipher the {@link CryptoCipher} instance.
- * @throws IOException if an I/O error occurs.
- */
- public static void checkStreamCipher(CryptoCipher cipher) throws IOException {
- if (cipher.getTransformation() != CipherTransformation.AES_CTR_NOPADDING) {
- throw new IOException("AES/CTR/NoPadding is required");
+ /**
+ * Checks whether the cipher is supported streaming.
+ *
+ * @param cipher the {@link CryptoCipher} instance.
+ * @throws IOException if an I/O error occurs.
+ */
+ public static void checkStreamCipher(CryptoCipher cipher)
+ throws IOException {
+ if (cipher.getTransformation() != CipherTransformation.AES_CTR_NOPADDING) {
+ throw new IOException("AES/CTR/NoPadding is required");
+ }
}
- }
- /**
- * Checks and floors buffer size.
- *
- * @param cipher the {@link CryptoCipher} instance.
- * @param bufferSize the buffer size.
- * @return the remaining buffer size.
- */
- public static int checkBufferSize(CryptoCipher cipher, int bufferSize) {
- checkArgument(bufferSize >= MIN_BUFFER_SIZE,
- "Minimum value of buffer size is " + MIN_BUFFER_SIZE + ".");
- return bufferSize - bufferSize % cipher.getTransformation()
- .getAlgorithmBlockSize();
- }
+ /**
+ * Checks and floors buffer size.
+ *
+ * @param cipher the {@link CryptoCipher} instance.
+ * @param bufferSize the buffer size.
+ * @return the remaining buffer size.
+ */
+ public static int checkBufferSize(CryptoCipher cipher, int bufferSize) {
+ checkArgument(bufferSize >= MIN_BUFFER_SIZE,
+ "Minimum value of buffer size is " + MIN_BUFFER_SIZE + ".");
+ return bufferSize - bufferSize
+ % cipher.getTransformation().getAlgorithmBlockSize();
+ }
- /**
- * <p>
- * This method is only for Counter (CTR) mode. Generally the CryptoCipher calculates the
- * IV and maintain encryption context internally.For example a Cipher will maintain its
- * encryption context internally when we do encryption/decryption using the
- * CryptoCipher#update interface.
- * </p>
- * <p>
- * Encryption/Decryption is not always on the entire file. For example,
- * in Hadoop, a node may only decrypt a portion of a file (i.e. a split).
- * In these situations, the counter is derived from the file position.
- * </p>
- * The IV can be calculated by combining the initial IV and the counter with
- * a lossless operation (concatenation, addition, or XOR).
- *
- * @see <a href="http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Counter_.28CTR.29">
- * http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Counter_.28CTR.29</a>
- *
- * @param initIV initial IV
- * @param counter counter for input stream position
- * @param IV the IV for input stream position
- */
- public static void calculateIV(byte[] initIV, long counter, byte[] IV) {
- checkArgument(initIV.length == AES_BLOCK_SIZE);
- checkArgument(IV.length == AES_BLOCK_SIZE);
+ /**
+ * <p>
+ * This method is only for Counter (CTR) mode. Generally the CryptoCipher
+ * calculates the IV and maintain encryption context internally.For example
+ * a Cipher will maintain its encryption context internally when we do
+ * encryption/decryption using the CryptoCipher#update interface.
+ * </p>
+ * <p>
+ * Encryption/Decryption is not always on the entire file. For example, in
+ * Hadoop, a node may only decrypt a portion of a file (i.e. a split). In
+ * these situations, the counter is derived from the file position.
+ * </p>
+ * The IV can be calculated by combining the initial IV and the counter with
+ * a lossless operation (concatenation, addition, or XOR).
+ *
+ * @see <a
+ * href="http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Counter_.28CTR.29">
+ * http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Counter_.28CTR.29</a>
+ *
+ * @param initIV initial IV
+ * @param counter counter for input stream position
+ * @param IV the IV for input stream position
+ */
+ public static void calculateIV(byte[] initIV, long counter, byte[] IV) {
+ checkArgument(initIV.length == AES_BLOCK_SIZE);
+ checkArgument(IV.length == AES_BLOCK_SIZE);
- int i = IV.length; // IV length
- int j = 0; // counter bytes index
- int sum = 0;
- while (i-- > 0) {
- // (sum >>> Byte.SIZE) is the carry for addition
- sum = (initIV[i] & 0xff) + (sum >>> Byte.SIZE);
- if (j++ < 8) { // Big-endian, and long is 8 bytes length
- sum += (byte) counter & 0xff;
- counter >>>= 8;
- }
- IV[i] = (byte) sum;
+ int i = IV.length; // IV length
+ int j = 0; // counter bytes index
+ int sum = 0;
+ while (i-- > 0) {
+ // (sum >>> Byte.SIZE) is the carry for addition
+ sum = (initIV[i] & 0xff) + (sum >>> Byte.SIZE);
+ if (j++ < 8) { // Big-endian, and long is 8 bytes length
+ sum += (byte) counter & 0xff;
+ counter >>>= 8;
+ }
+ IV[i] = (byte) sum;
+ }
}
- }
- /**
- * Helper method to create a CryptoCipher instance and throws only IOException.
- *
- * @param props The <code>Properties</code> class represents a set of
- * properties.
- * @param transformation the CipherTransformation instance.
- * @return the CryptoCipher instance.
- * @throws IOException if an I/O error occurs.
- */
- public static CryptoCipher getCipherInstance(CipherTransformation transformation,
- Properties props) throws IOException {
- try {
- return CryptoCipherFactory.getInstance(transformation, props);
- } catch (GeneralSecurityException e) {
- throw new IOException(e);
+ /**
+ * Helper method to create a CryptoCipher instance and throws only
+ * IOException.
+ *
+ * @param props The <code>Properties</code> class represents a set of
+ * properties.
+ * @param transformation the CipherTransformation instance.
+ * @return the CryptoCipher instance.
+ * @throws IOException if an I/O error occurs.
+ */
+ public static CryptoCipher getCipherInstance(
+ CipherTransformation transformation, Properties props)
+ throws IOException {
+ try {
+ return CryptoCipherFactory.getInstance(transformation, props);
+ } catch (GeneralSecurityException e) {
+ throw new IOException(e);
+ }
}
- }
- /**
- * Ensures the truth of an expression involving one or more parameters to
- * the calling method.
- *
- * @param expression a boolean expression.
- * @throws IllegalArgumentException if expression is false.
- */
- public static void checkArgument(boolean expression) {
- if(!expression) {
- throw new IllegalArgumentException();
+ /**
+ * Ensures the truth of an expression involving one or more parameters to
+ * the calling method.
+ *
+ * @param expression a boolean expression.
+ * @throws IllegalArgumentException if expression is false.
+ */
+ public static void checkArgument(boolean expression) {
+ if (!expression) {
+ throw new IllegalArgumentException();
+ }
}
- }
- /**
- * Checks the truth of an expression.
- *
- * @param expression a boolean expression.
- * @param errorMessage the exception message to use if the check fails;
- * will be converted to a string using <code>String
- * .valueOf(Object)</code>.
- * @throws IllegalArgumentException if expression is false.
- */
- public static void checkArgument(boolean expression, Object errorMessage) {
- if (!expression) {
- throw new IllegalArgumentException(String.valueOf(errorMessage));
+ /**
+ * Checks the truth of an expression.
+ *
+ * @param expression a boolean expression.
+ * @param errorMessage the exception message to use if the check fails; will
+ * be converted to a string using <code>String
+ * .valueOf(Object)</code>.
+ * @throws IllegalArgumentException if expression is false.
+ */
+ public static void checkArgument(boolean expression, Object errorMessage) {
+ if (!expression) {
+ throw new IllegalArgumentException(String.valueOf(errorMessage));
+ }
}
- }
- /**
- * Ensures that an object reference passed as a parameter to the calling
- * method is not null.
- *
- * @param <T> the type of the object reference to be checked.
- * @param reference an object reference.
- * @return the non-null reference that was validated.
- * @throws NullPointerException if reference is null.
- */
- public static <T> T checkNotNull(T reference) {
- if(reference == null) {
- throw new NullPointerException();
- } else {
- return reference;
+ /**
+ * Ensures that an object reference passed as a parameter to the calling
+ * method is not null.
+ *
+ * @param <T> the type of the object reference to be checked.
+ * @param reference an object reference.
+ * @return the non-null reference that was validated.
+ * @throws NullPointerException if reference is null.
+ */
+ public static <T> T checkNotNull(T reference) {
+ if (reference == null) {
+ throw new NullPointerException();
+ } else {
+ return reference;
+ }
}
- }
- /**
- * Ensures the truth of an expression involving the state of the calling
- * instance, but not involving any parameters to the calling method.
- *
- * @param expression a boolean expression.
- * @throws IllegalStateException if expression is false.
- */
- public static void checkState(boolean expression) {
- if(!expression) {
- throw new IllegalStateException();
+ /**
+ * Ensures the truth of an expression involving the state of the calling
+ * instance, but not involving any parameters to the calling method.
+ *
+ * @param expression a boolean expression.
+ * @throws IllegalStateException if expression is false.
+ */
+ public static void checkState(boolean expression) {
+ if (!expression) {
+ throw new IllegalStateException();
+ }
}
- }
- /**
- * Splits class names sequence into substrings, Trim each substring into an
- * entry,and returns an list of the entries.
- *
- * @param clazzNames a string consist of a list of the entries joined by a
- * delimiter.
- * @param separator a delimiter for the input string.
- * @return a list of class entries.
- */
- public static List<String> splitClassNames(String clazzNames,
- String separator) {
- List<String> res = new ArrayList<String>();
- if (clazzNames == null || clazzNames.isEmpty()) {
- return res;
- }
+ /**
+ * Splits class names sequence into substrings, Trim each substring into an
+ * entry,and returns an list of the entries.
+ *
+ * @param clazzNames a string consist of a list of the entries joined by a
+ * delimiter.
+ * @param separator a delimiter for the input string.
+ * @return a list of class entries.
+ */
+ public static List<String> splitClassNames(String clazzNames,
+ String separator) {
+ List<String> res = new ArrayList<String>();
+ if (clazzNames == null || clazzNames.isEmpty()) {
+ return res;
+ }
- for (String clazzName : clazzNames.split(separator)) {
- clazzName = clazzName.trim();
- if (!clazzName.isEmpty()) {
- res.add(clazzName);
- }
+ for (String clazzName : clazzNames.split(separator)) {
+ clazzName = clazzName.trim();
+ if (!clazzName.isEmpty()) {
+ res.add(clazzName);
+ }
+ }
+ return res;
}
- return res;
- }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/utils/package-info.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/utils/package-info.java b/src/main/java/org/apache/commons/crypto/utils/package-info.java
index 7a3c334..20785f2 100644
--- a/src/main/java/org/apache/commons/crypto/utils/package-info.java
+++ b/src/main/java/org/apache/commons/crypto/utils/package-info.java
@@ -19,3 +19,4 @@
* Utils classes
*/
package org.apache.commons.crypto.utils;
+
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/test/java/org/apache/commons/crypto/cipher/AbstractCipherTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/crypto/cipher/AbstractCipherTest.java b/src/test/java/org/apache/commons/crypto/cipher/AbstractCipherTest.java
index f60f29c..00d1505 100644
--- a/src/test/java/org/apache/commons/crypto/cipher/AbstractCipherTest.java
+++ b/src/test/java/org/apache/commons/crypto/cipher/AbstractCipherTest.java
@@ -36,209 +36,229 @@ import org.junit.Test;
public abstract class AbstractCipherTest {
- // data
- public static final int BYTEBUFFER_SIZE = 1000;
- public String[] cipherTests = null;
- Properties props = null;
- String cipherClass = null;
- CipherTransformation[] transformations = null;
-
- // cipher
- static final byte[] KEY = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
- 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16};
- static final byte[] IV = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
- 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};
- CryptoCipher enc, dec;
-
- @Before
- public void setup() {
- init();
- Utils.checkNotNull(cipherClass);
- Utils.checkNotNull(transformations);
- props = new Properties();
- props.setProperty(ConfigurationKeys.COMMONS_CRYPTO_CIPHER_CLASSES_KEY,
- cipherClass);
- }
-
- protected abstract void init() ;
-
- @Test
- public void cryptoTest() throws GeneralSecurityException, IOException {
- for (CipherTransformation tran : transformations) {
- /** uses the small data set in {@link TestData} */
- cipherTests = TestData.getTestData(tran);
- for (int i = 0; i != cipherTests.length; i += 5) {
- byte[] key = DatatypeConverter.parseHexBinary(cipherTests[i + 1]);
- byte[] iv = DatatypeConverter.parseHexBinary(cipherTests[i + 2]);
-
- byte[] inputBytes = DatatypeConverter.parseHexBinary(cipherTests[i + 3]);
- byte[] outputBytes = DatatypeConverter.parseHexBinary(cipherTests[i + 4]);
-
- ByteBuffer inputBuffer = ByteBuffer.allocateDirect(inputBytes.length);
- ByteBuffer outputBuffer = ByteBuffer.allocateDirect(outputBytes.length);
- inputBuffer.put(inputBytes);
- inputBuffer.flip();
- outputBuffer.put(outputBytes);
- outputBuffer.flip();
-
- byteBufferTest(tran,key, iv, inputBuffer, outputBuffer);
- byteArrayTest(tran, key, iv, inputBytes, outputBytes);
- }
-
- /** uses randomly generated big data set */
- byteArrayTest(tran, KEY, IV);
- }
- }
-
- private void byteBufferTest(CipherTransformation transformation, byte[] key,
- byte[] iv,
- ByteBuffer input, ByteBuffer output) throws
- GeneralSecurityException, IOException {
- ByteBuffer decResult = ByteBuffer.allocateDirect(BYTEBUFFER_SIZE);
- ByteBuffer encResult = ByteBuffer.allocateDirect(BYTEBUFFER_SIZE);
+ // data
+ public static final int BYTEBUFFER_SIZE = 1000;
+ public String[] cipherTests = null;
+ Properties props = null;
+ String cipherClass = null;
+ CipherTransformation[] transformations = null;
+
+ // cipher
+ static final byte[] KEY = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
+ 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
+ static final byte[] IV = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
+ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 };
CryptoCipher enc, dec;
- enc = getCipher(transformation);
- dec = getCipher(transformation);
-
- try {
- enc.init(CryptoCipher.ENCRYPT_MODE, new SecretKeySpec(key,"AES"), new IvParameterSpec(iv));
- } catch (Exception e) {
- Assert.fail("AES failed initialisation - " + e.toString());
+ @Before
+ public void setup() {
+ init();
+ Utils.checkNotNull(cipherClass);
+ Utils.checkNotNull(transformations);
+ props = new Properties();
+ props.setProperty(ConfigurationKeys.COMMONS_CRYPTO_CIPHER_CLASSES_KEY,
+ cipherClass);
}
- try {
- dec.init(CryptoCipher.DECRYPT_MODE, new SecretKeySpec(key,"AES"), new IvParameterSpec(iv));
- } catch (Exception e) {
- Assert.fail("AES failed initialisation - " + e.toString());
+ protected abstract void init();
+
+ @Test
+ public void cryptoTest() throws GeneralSecurityException, IOException {
+ for (CipherTransformation tran : transformations) {
+ /** uses the small data set in {@link TestData} */
+ cipherTests = TestData.getTestData(tran);
+ for (int i = 0; i != cipherTests.length; i += 5) {
+ byte[] key = DatatypeConverter
+ .parseHexBinary(cipherTests[i + 1]);
+ byte[] iv = DatatypeConverter
+ .parseHexBinary(cipherTests[i + 2]);
+
+ byte[] inputBytes = DatatypeConverter
+ .parseHexBinary(cipherTests[i + 3]);
+ byte[] outputBytes = DatatypeConverter
+ .parseHexBinary(cipherTests[i + 4]);
+
+ ByteBuffer inputBuffer = ByteBuffer
+ .allocateDirect(inputBytes.length);
+ ByteBuffer outputBuffer = ByteBuffer
+ .allocateDirect(outputBytes.length);
+ inputBuffer.put(inputBytes);
+ inputBuffer.flip();
+ outputBuffer.put(outputBytes);
+ outputBuffer.flip();
+
+ byteBufferTest(tran, key, iv, inputBuffer, outputBuffer);
+ byteArrayTest(tran, key, iv, inputBytes, outputBytes);
+ }
+
+ /** uses randomly generated big data set */
+ byteArrayTest(tran, KEY, IV);
+ }
}
- //
- // encryption pass
- //
- enc.doFinal(input, encResult);
- input.flip();
- encResult.flip();
- if (!output.equals(encResult)) {
- byte[] b = new byte[output.remaining()];
- output.get(b);
- byte[] c = new byte[encResult.remaining()];
- encResult.get(c);
- Assert.fail("AES failed encryption - expected " + new String(
- DatatypeConverter
- .printHexBinary(b)) + " got " + new String(
- DatatypeConverter.printHexBinary(c)));
- }
+ private void byteBufferTest(CipherTransformation transformation,
+ byte[] key, byte[] iv, ByteBuffer input, ByteBuffer output)
+ throws GeneralSecurityException, IOException {
+ ByteBuffer decResult = ByteBuffer.allocateDirect(BYTEBUFFER_SIZE);
+ ByteBuffer encResult = ByteBuffer.allocateDirect(BYTEBUFFER_SIZE);
+ CryptoCipher enc, dec;
+
+ enc = getCipher(transformation);
+ dec = getCipher(transformation);
+
+ try {
+ enc.init(CryptoCipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"),
+ new IvParameterSpec(iv));
+ } catch (Exception e) {
+ Assert.fail("AES failed initialisation - " + e.toString());
+ }
- //
- // decryption pass
- //
- dec.doFinal(encResult, decResult);
- decResult.flip();
-
- if (!input.equals(decResult)) {
- byte[] inArray = new byte[input.remaining()];
- byte[] decResultArray = new byte[decResult.remaining()];
- input.get(inArray);
- decResult.get(decResultArray);
- Assert.fail();
- }
- }
-
- /** test byte array whose data is planned in {@link TestData} */
- private void byteArrayTest(CipherTransformation transformation, byte[] key,
- byte[] iv, byte[] input, byte[] output) throws GeneralSecurityException {
- resetCipher(transformation, key, iv);
- int blockSize = transformation.getAlgorithmBlockSize();
-
- byte[] temp = new byte[input.length + blockSize];
- int n = enc.doFinal(input, 0, input.length, temp, 0);
- byte[] cipherText = new byte[n];
- System.arraycopy(temp, 0, cipherText, 0, n);
- Assert.assertArrayEquals("byte array encryption error.", output, cipherText);
-
- temp = new byte[cipherText.length + blockSize];
- int m = dec.doFinal(cipherText, 0, cipherText.length, temp, 0);
- byte[] plainText = new byte[m];
- System.arraycopy(temp, 0, plainText, 0, m);
- Assert.assertArrayEquals("byte array decryption error.", input, plainText);
- }
-
- /** test byte array whose data is randomly generated */
- private void byteArrayTest(CipherTransformation transformation, byte[] key,
- byte[] iv) throws GeneralSecurityException {
- int blockSize = transformation.getAlgorithmBlockSize();
-
- // AES_CBC_NOPADDING only accepts data whose size is the multiple of block size
- int[] dataLenList = (transformation == CipherTransformation.AES_CBC_NOPADDING)
- ? new int[] {10 * 1024} : new int[] {10 * 1024, 10 * 1024 - 3};
- for (int dataLen : dataLenList) {
- byte[] plainText = new byte[dataLen];
- Random random = new SecureRandom();
- random.nextBytes(plainText);
- byte[] cipherText = new byte[dataLen + blockSize];
-
- // check update method with inputs whose sizes are the multiple of block size or not
- int[] bufferLenList = new int[] {2 * 1024 - 128, 2 * 1024 - 125};
- for (int bufferLen : bufferLenList) {
- resetCipher(transformation, key, iv);
+ try {
+ dec.init(CryptoCipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"),
+ new IvParameterSpec(iv));
+ } catch (Exception e) {
+ Assert.fail("AES failed initialisation - " + e.toString());
+ }
- int offset = 0;
- // encrypt (update + doFinal) the data
- int cipherPos = 0;
- for (int i = 0; i < dataLen / bufferLen; i ++) {
- cipherPos += enc.update(plainText, offset, bufferLen, cipherText, cipherPos);
- offset += bufferLen;
+ //
+ // encryption pass
+ //
+ enc.doFinal(input, encResult);
+ input.flip();
+ encResult.flip();
+ if (!output.equals(encResult)) {
+ byte[] b = new byte[output.remaining()];
+ output.get(b);
+ byte[] c = new byte[encResult.remaining()];
+ encResult.get(c);
+ Assert.fail("AES failed encryption - expected "
+ + new String(DatatypeConverter.printHexBinary(b)) + " got "
+ + new String(DatatypeConverter.printHexBinary(c)));
}
- cipherPos += enc.doFinal(plainText, offset, dataLen % bufferLen, cipherText, cipherPos);
-
- offset = 0;
- // decrypt (update + doFinal) the data
- byte[] realPlainText = new byte[cipherPos + blockSize];
- int plainPos = 0;
- for (int i = 0; i < cipherPos / bufferLen; i ++) {
- plainPos += dec.update(cipherText, offset, bufferLen, realPlainText, plainPos);
- offset += bufferLen;
+
+ //
+ // decryption pass
+ //
+ dec.doFinal(encResult, decResult);
+ decResult.flip();
+
+ if (!input.equals(decResult)) {
+ byte[] inArray = new byte[input.remaining()];
+ byte[] decResultArray = new byte[decResult.remaining()];
+ input.get(inArray);
+ decResult.get(decResultArray);
+ Assert.fail();
}
- plainPos += dec.doFinal(cipherText, offset, cipherPos % bufferLen, realPlainText, plainPos);
+ }
- // verify
- Assert.assertEquals("random byte array length changes after transformation",
- dataLen, plainPos);
+ /** test byte array whose data is planned in {@link TestData} */
+ private void byteArrayTest(CipherTransformation transformation, byte[] key,
+ byte[] iv, byte[] input, byte[] output)
+ throws GeneralSecurityException {
+ resetCipher(transformation, key, iv);
+ int blockSize = transformation.getAlgorithmBlockSize();
+
+ byte[] temp = new byte[input.length + blockSize];
+ int n = enc.doFinal(input, 0, input.length, temp, 0);
+ byte[] cipherText = new byte[n];
+ System.arraycopy(temp, 0, cipherText, 0, n);
+ Assert.assertArrayEquals("byte array encryption error.", output,
+ cipherText);
+
+ temp = new byte[cipherText.length + blockSize];
+ int m = dec.doFinal(cipherText, 0, cipherText.length, temp, 0);
+ byte[] plainText = new byte[m];
+ System.arraycopy(temp, 0, plainText, 0, m);
+ Assert.assertArrayEquals("byte array decryption error.", input,
+ plainText);
+ }
- byte[] shrinkPlainText = new byte[plainPos];
- System.arraycopy(realPlainText, 0, shrinkPlainText, 0, plainPos);
- Assert.assertArrayEquals("random byte array contents changes after transformation",
- plainText, shrinkPlainText);
- }
+ /** test byte array whose data is randomly generated */
+ private void byteArrayTest(CipherTransformation transformation, byte[] key,
+ byte[] iv) throws GeneralSecurityException {
+ int blockSize = transformation.getAlgorithmBlockSize();
+
+ // AES_CBC_NOPADDING only accepts data whose size is the multiple of
+ // block size
+ int[] dataLenList = (transformation == CipherTransformation.AES_CBC_NOPADDING) ? new int[] { 10 * 1024 }
+ : new int[] { 10 * 1024, 10 * 1024 - 3 };
+ for (int dataLen : dataLenList) {
+ byte[] plainText = new byte[dataLen];
+ Random random = new SecureRandom();
+ random.nextBytes(plainText);
+ byte[] cipherText = new byte[dataLen + blockSize];
+
+ // check update method with inputs whose sizes are the multiple of
+ // block size or not
+ int[] bufferLenList = new int[] { 2 * 1024 - 128, 2 * 1024 - 125 };
+ for (int bufferLen : bufferLenList) {
+ resetCipher(transformation, key, iv);
+
+ int offset = 0;
+ // encrypt (update + doFinal) the data
+ int cipherPos = 0;
+ for (int i = 0; i < dataLen / bufferLen; i++) {
+ cipherPos += enc.update(plainText, offset, bufferLen,
+ cipherText, cipherPos);
+ offset += bufferLen;
+ }
+ cipherPos += enc.doFinal(plainText, offset,
+ dataLen % bufferLen, cipherText, cipherPos);
+
+ offset = 0;
+ // decrypt (update + doFinal) the data
+ byte[] realPlainText = new byte[cipherPos + blockSize];
+ int plainPos = 0;
+ for (int i = 0; i < cipherPos / bufferLen; i++) {
+ plainPos += dec.update(cipherText, offset, bufferLen,
+ realPlainText, plainPos);
+ offset += bufferLen;
+ }
+ plainPos += dec.doFinal(cipherText, offset, cipherPos
+ % bufferLen, realPlainText, plainPos);
+
+ // verify
+ Assert.assertEquals(
+ "random byte array length changes after transformation",
+ dataLen, plainPos);
+
+ byte[] shrinkPlainText = new byte[plainPos];
+ System.arraycopy(realPlainText, 0, shrinkPlainText, 0, plainPos);
+ Assert.assertArrayEquals(
+ "random byte array contents changes after transformation",
+ plainText, shrinkPlainText);
+ }
+ }
}
- }
- private void resetCipher(CipherTransformation transformation, byte[] key, byte[] iv) {
- enc = getCipher(transformation);
- dec = getCipher(transformation);
+ private void resetCipher(CipherTransformation transformation, byte[] key,
+ byte[] iv) {
+ enc = getCipher(transformation);
+ dec = getCipher(transformation);
- try {
- enc.init(CryptoCipher.ENCRYPT_MODE, new SecretKeySpec(key,"AES"), new IvParameterSpec(iv));
- } catch (Exception e) {
- Assert.fail("AES failed initialisation - " + e.toString());
- }
+ try {
+ enc.init(CryptoCipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"),
+ new IvParameterSpec(iv));
+ } catch (Exception e) {
+ Assert.fail("AES failed initialisation - " + e.toString());
+ }
- try {
- dec.init(CryptoCipher.DECRYPT_MODE, new SecretKeySpec(key,"AES"), new IvParameterSpec(iv));
- } catch (Exception e) {
- Assert.fail("AES failed initialisation - " + e.toString());
- }
- }
-
- private CryptoCipher getCipher(CipherTransformation transformation) {
- try {
- return (CryptoCipher) ReflectionUtils
- .newInstance(ReflectionUtils.getClassByName(cipherClass), props,
- transformation);
- } catch (ClassNotFoundException e) {
- throw new RuntimeException(e);
+ try {
+ dec.init(CryptoCipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"),
+ new IvParameterSpec(iv));
+ } catch (Exception e) {
+ Assert.fail("AES failed initialisation - " + e.toString());
+ }
}
- }
+ private CryptoCipher getCipher(CipherTransformation transformation) {
+ try {
+ return (CryptoCipher) ReflectionUtils.newInstance(
+ ReflectionUtils.getClassByName(cipherClass), props,
+ transformation);
+ } catch (ClassNotFoundException e) {
+ throw new RuntimeException(e);
+ }
+
+ }
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/test/java/org/apache/commons/crypto/cipher/CryptoCipherFactoryTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/crypto/cipher/CryptoCipherFactoryTest.java b/src/test/java/org/apache/commons/crypto/cipher/CryptoCipherFactoryTest.java
index 3653cf9..bc1f6bd 100644
--- a/src/test/java/org/apache/commons/crypto/cipher/CryptoCipherFactoryTest.java
+++ b/src/test/java/org/apache/commons/crypto/cipher/CryptoCipherFactoryTest.java
@@ -26,32 +26,32 @@ import junit.framework.Assert;
import org.junit.Test;
public class CryptoCipherFactoryTest {
- @Test
- public void testDefaultCipher() throws GeneralSecurityException {
- CryptoCipher defaultCipher = CryptoCipherFactory.getInstance(
- CipherTransformation.AES_CBC_NOPADDING);
- Assert.assertEquals(OpensslCipher.class.getName(),
- defaultCipher.getClass().getName());
- }
+ @Test
+ public void testDefaultCipher() throws GeneralSecurityException {
+ CryptoCipher defaultCipher = CryptoCipherFactory
+ .getInstance(CipherTransformation.AES_CBC_NOPADDING);
+ Assert.assertEquals(OpensslCipher.class.getName(), defaultCipher
+ .getClass().getName());
+ }
- @Test
- public void testEmptyCipher() throws GeneralSecurityException {
- Properties properties = new Properties();
- properties.put(ConfigurationKeys.COMMONS_CRYPTO_CIPHER_CLASSES_KEY, "");
- CryptoCipher defaultCipher = CryptoCipherFactory.getInstance(
- CipherTransformation.AES_CBC_NOPADDING, properties);
- Assert.assertEquals(OpensslCipher.class.getName(),
- defaultCipher.getClass().getName());
- }
+ @Test
+ public void testEmptyCipher() throws GeneralSecurityException {
+ Properties properties = new Properties();
+ properties.put(ConfigurationKeys.COMMONS_CRYPTO_CIPHER_CLASSES_KEY, "");
+ CryptoCipher defaultCipher = CryptoCipherFactory.getInstance(
+ CipherTransformation.AES_CBC_NOPADDING, properties);
+ Assert.assertEquals(OpensslCipher.class.getName(), defaultCipher
+ .getClass().getName());
+ }
- @Test
- public void testInvalidCipher() throws GeneralSecurityException {
- Properties properties = new Properties();
- properties.put(ConfigurationKeys.COMMONS_CRYPTO_CIPHER_CLASSES_KEY,
- "InvalidCipherName");
- CryptoCipher defaultCipher = CryptoCipherFactory.getInstance(
- CipherTransformation.AES_CBC_NOPADDING, properties);
- Assert.assertEquals(JceCipher.class.getName(),
- defaultCipher.getClass().getName());
- }
+ @Test
+ public void testInvalidCipher() throws GeneralSecurityException {
+ Properties properties = new Properties();
+ properties.put(ConfigurationKeys.COMMONS_CRYPTO_CIPHER_CLASSES_KEY,
+ "InvalidCipherName");
+ CryptoCipher defaultCipher = CryptoCipherFactory.getInstance(
+ CipherTransformation.AES_CBC_NOPADDING, properties);
+ Assert.assertEquals(JceCipher.class.getName(), defaultCipher.getClass()
+ .getName());
+ }
}
[5/7] commons-crypto git commit: CRYPTO-37: Change all the 2 spaces
indent to 4 to comply Commons code style
Posted by xu...@apache.org.
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/stream/CTRCryptoOutputStream.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/stream/CTRCryptoOutputStream.java b/src/main/java/org/apache/commons/crypto/stream/CTRCryptoOutputStream.java
index 1b76db2..2b86c6d 100644
--- a/src/main/java/org/apache/commons/crypto/stream/CTRCryptoOutputStream.java
+++ b/src/main/java/org/apache/commons/crypto/stream/CTRCryptoOutputStream.java
@@ -46,342 +46,341 @@ import org.apache.commons.crypto.utils.Utils;
* (1) calculating counter and (2) padding through stream position.
* </p>
* <p>
- * counter = base + pos/(algorithm blocksize);
- * padding = pos%(algorithm blocksize);
+ * counter = base + pos/(algorithm blocksize); padding = pos%(algorithm
+ * blocksize);
* </p>
* The underlying stream offset is maintained as state.
*/
public class CTRCryptoOutputStream extends CryptoOutputStream {
- /**
- * Underlying stream offset.
- */
- long streamOffset = 0;
+ /**
+ * Underlying stream offset.
+ */
+ long streamOffset = 0;
- /**
- * The initial IV.
- */
- protected final byte[] initIV;
+ /**
+ * The initial IV.
+ */
+ protected final byte[] initIV;
- /**
- * Initialization vector for the cipher.
- */
- protected byte[] iv;
+ /**
+ * Initialization vector for the cipher.
+ */
+ protected byte[] iv;
- /**
- * Padding = pos%(algorithm blocksize); Padding is put into {@link #inBuffer}
- * before any other data goes in. The purpose of padding is to put input data
- * at proper position.
- */
- private byte padding;
+ /**
+ * Padding = pos%(algorithm blocksize); Padding is put into
+ * {@link #inBuffer} before any other data goes in. The purpose of padding
+ * is to put input data at proper position.
+ */
+ private byte padding;
- /**
- * Flag to mark whether the cipher has been reset
- */
- private boolean cipherReset = false;
+ /**
+ * Flag to mark whether the cipher has been reset
+ */
+ private boolean cipherReset = false;
- /**
- * Constructs a {@link CTRCryptoOutputStream}.
- *
- * @param props The <code>Properties</code> class represents a set of
- * properties.
- * @param out the output stream.
- * @param key crypto key for the cipher.
- * @param iv Initialization vector for the cipher.
- * @throws IOException if an I/O error occurs.
- */
- public CTRCryptoOutputStream(Properties props, OutputStream out, byte[] key,
- byte[] iv)
- throws IOException {
- this(props, out, key, iv, 0);
- }
-
- /**
- * Constructs a {@link CTRCryptoOutputStream}.
- *
- * @param props The <code>Properties</code> class represents a set of
- * properties.
- * @param out the WritableByteChannel instance.
- * @param key crypto key for the cipher.
- * @param iv Initialization vector for the cipher.
- * @throws IOException if an I/O error occurs.
- */
- public CTRCryptoOutputStream(Properties props, WritableByteChannel out,
- byte[] key, byte[] iv)
- throws IOException {
- this(props, out, key, iv, 0);
- }
+ /**
+ * Constructs a {@link CTRCryptoOutputStream}.
+ *
+ * @param props The <code>Properties</code> class represents a set of
+ * properties.
+ * @param out the output stream.
+ * @param key crypto key for the cipher.
+ * @param iv Initialization vector for the cipher.
+ * @throws IOException if an I/O error occurs.
+ */
+ public CTRCryptoOutputStream(Properties props, OutputStream out,
+ byte[] key, byte[] iv) throws IOException {
+ this(props, out, key, iv, 0);
+ }
- /**
- * Constructs a {@link CTRCryptoOutputStream}.
- *
- * @param out the output stream.
- * @param cipher the CryptoCipher instance.
- * @param bufferSize the bufferSize.
- * @param key crypto key for the cipher.
- * @param iv Initialization vector for the cipher.
- * @throws IOException if an I/O error occurs.
- */
- public CTRCryptoOutputStream(OutputStream out, CryptoCipher cipher, int bufferSize,
- byte[] key, byte[] iv) throws IOException {
- this(out, cipher, bufferSize, key, iv, 0);
- }
+ /**
+ * Constructs a {@link CTRCryptoOutputStream}.
+ *
+ * @param props The <code>Properties</code> class represents a set of
+ * properties.
+ * @param out the WritableByteChannel instance.
+ * @param key crypto key for the cipher.
+ * @param iv Initialization vector for the cipher.
+ * @throws IOException if an I/O error occurs.
+ */
+ public CTRCryptoOutputStream(Properties props, WritableByteChannel out,
+ byte[] key, byte[] iv) throws IOException {
+ this(props, out, key, iv, 0);
+ }
- /**
- * Constructs a {@link CTRCryptoOutputStream}.
- *
- * @param channel the WritableByteChannel instance.
- * @param cipher the CryptoCipher instance.
- * @param bufferSize the bufferSize.
- * @param key crypto key for the cipher.
- * @param iv Initialization vector for the cipher.
- * @throws IOException if an I/O error occurs.
- */
- public CTRCryptoOutputStream(WritableByteChannel channel, CryptoCipher cipher,
- int bufferSize, byte[] key, byte[] iv) throws IOException {
- this(channel, cipher, bufferSize, key, iv, 0);
- }
+ /**
+ * Constructs a {@link CTRCryptoOutputStream}.
+ *
+ * @param out the output stream.
+ * @param cipher the CryptoCipher instance.
+ * @param bufferSize the bufferSize.
+ * @param key crypto key for the cipher.
+ * @param iv Initialization vector for the cipher.
+ * @throws IOException if an I/O error occurs.
+ */
+ public CTRCryptoOutputStream(OutputStream out, CryptoCipher cipher,
+ int bufferSize, byte[] key, byte[] iv) throws IOException {
+ this(out, cipher, bufferSize, key, iv, 0);
+ }
- /**
- * Constructs a {@link CTRCryptoOutputStream}.
- *
- * @param output the Output instance.
- * @param cipher the CryptoCipher instance.
- * @param bufferSize the bufferSize.
- * @param key crypto key for the cipher.
- * @param iv Initialization vector for the cipher.
- * @throws IOException if an I/O error occurs.
- */
- public CTRCryptoOutputStream(Output output, CryptoCipher cipher, int bufferSize,
- byte[] key, byte[] iv)
- throws IOException {
- this(output, cipher, bufferSize, key, iv, 0);
- }
+ /**
+ * Constructs a {@link CTRCryptoOutputStream}.
+ *
+ * @param channel the WritableByteChannel instance.
+ * @param cipher the CryptoCipher instance.
+ * @param bufferSize the bufferSize.
+ * @param key crypto key for the cipher.
+ * @param iv Initialization vector for the cipher.
+ * @throws IOException if an I/O error occurs.
+ */
+ public CTRCryptoOutputStream(WritableByteChannel channel,
+ CryptoCipher cipher, int bufferSize, byte[] key, byte[] iv)
+ throws IOException {
+ this(channel, cipher, bufferSize, key, iv, 0);
+ }
- /**
- * Constructs a {@link CTRCryptoOutputStream}.
- *
- * @param props The <code>Properties</code> class represents a set of
- * properties.
- * @param out the output stream.
- * @param key crypto key for the cipher.
- * @param iv Initialization vector for the cipher.
- * @param streamOffset the start offset in the data.
- * @throws IOException if an I/O error occurs.
- */
- public CTRCryptoOutputStream(Properties props, OutputStream out, byte[] key,
- byte[] iv, long streamOffset)
- throws IOException {
- this(out, Utils.getCipherInstance(CipherTransformation.AES_CTR_NOPADDING, props),
- Utils.getBufferSize(props), key, iv, streamOffset);
- }
+ /**
+ * Constructs a {@link CTRCryptoOutputStream}.
+ *
+ * @param output the Output instance.
+ * @param cipher the CryptoCipher instance.
+ * @param bufferSize the bufferSize.
+ * @param key crypto key for the cipher.
+ * @param iv Initialization vector for the cipher.
+ * @throws IOException if an I/O error occurs.
+ */
+ public CTRCryptoOutputStream(Output output, CryptoCipher cipher,
+ int bufferSize, byte[] key, byte[] iv) throws IOException {
+ this(output, cipher, bufferSize, key, iv, 0);
+ }
- /**
- * Constructs a {@link CTRCryptoOutputStream}.
- *
- * @param props The <code>Properties</code> class represents a set of
- * properties.
- * @param out the WritableByteChannel instance.
- * @param key crypto key for the cipher.
- * @param iv Initialization vector for the cipher.
- * @param streamOffset the start offset in the data.
- * @throws IOException if an I/O error occurs.
- */
- public CTRCryptoOutputStream(Properties props, WritableByteChannel out,
- byte[] key, byte[] iv, long streamOffset)
- throws IOException {
- this(out, Utils.getCipherInstance(CipherTransformation.AES_CTR_NOPADDING, props),
- Utils.getBufferSize(props), key, iv, streamOffset);
- }
+ /**
+ * Constructs a {@link CTRCryptoOutputStream}.
+ *
+ * @param props The <code>Properties</code> class represents a set of
+ * properties.
+ * @param out the output stream.
+ * @param key crypto key for the cipher.
+ * @param iv Initialization vector for the cipher.
+ * @param streamOffset the start offset in the data.
+ * @throws IOException if an I/O error occurs.
+ */
+ public CTRCryptoOutputStream(Properties props, OutputStream out,
+ byte[] key, byte[] iv, long streamOffset) throws IOException {
+ this(out, Utils.getCipherInstance(
+ CipherTransformation.AES_CTR_NOPADDING, props), Utils
+ .getBufferSize(props), key, iv, streamOffset);
+ }
- /**
- * Constructs a {@link CTRCryptoOutputStream}.
- *
- * @param out the output stream.
- * @param cipher the CryptoCipher instance.
- * @param bufferSize the bufferSize.
- * @param key crypto key for the cipher.
- * @param iv Initialization vector for the cipher.
- * @param streamOffset the start offset in the data.
- * @throws IOException if an I/O error occurs.
- */
- public CTRCryptoOutputStream(OutputStream out, CryptoCipher cipher, int bufferSize,
- byte[] key, byte[] iv, long streamOffset) throws IOException {
- this(new StreamOutput(out, bufferSize), cipher,
- bufferSize, key, iv, streamOffset);
- }
+ /**
+ * Constructs a {@link CTRCryptoOutputStream}.
+ *
+ * @param props The <code>Properties</code> class represents a set of
+ * properties.
+ * @param out the WritableByteChannel instance.
+ * @param key crypto key for the cipher.
+ * @param iv Initialization vector for the cipher.
+ * @param streamOffset the start offset in the data.
+ * @throws IOException if an I/O error occurs.
+ */
+ public CTRCryptoOutputStream(Properties props, WritableByteChannel out,
+ byte[] key, byte[] iv, long streamOffset) throws IOException {
+ this(out, Utils.getCipherInstance(
+ CipherTransformation.AES_CTR_NOPADDING, props), Utils
+ .getBufferSize(props), key, iv, streamOffset);
+ }
- /**
- * Constructs a {@link CTRCryptoOutputStream}.
- *
- * @param channel the WritableByteChannel instance.
- * @param cipher the CryptoCipher instance.
- * @param bufferSize the bufferSize.
- * @param key crypto key for the cipher.
- * @param iv Initialization vector for the cipher.
- * @param streamOffset the start offset in the data.
- * @throws IOException if an I/O error occurs.
- */
- public CTRCryptoOutputStream(WritableByteChannel channel, CryptoCipher cipher,
- int bufferSize, byte[] key, byte[] iv,
- long streamOffset) throws IOException {
- this(new ChannelOutput(channel), cipher,
- bufferSize, key, iv, streamOffset);
- }
+ /**
+ * Constructs a {@link CTRCryptoOutputStream}.
+ *
+ * @param out the output stream.
+ * @param cipher the CryptoCipher instance.
+ * @param bufferSize the bufferSize.
+ * @param key crypto key for the cipher.
+ * @param iv Initialization vector for the cipher.
+ * @param streamOffset the start offset in the data.
+ * @throws IOException if an I/O error occurs.
+ */
+ public CTRCryptoOutputStream(OutputStream out, CryptoCipher cipher,
+ int bufferSize, byte[] key, byte[] iv, long streamOffset)
+ throws IOException {
+ this(new StreamOutput(out, bufferSize), cipher, bufferSize, key, iv,
+ streamOffset);
+ }
- /**
- * Constructs a {@link CTRCryptoOutputStream}.
- *
- * @param output the output stream.
- * @param cipher the CryptoCipher instance.
- * @param bufferSize the bufferSize.
- * @param key crypto key for the cipher.
- * @param iv Initialization vector for the cipher.
- * @param streamOffset the start offset in the data.
- * @throws IOException if an I/O error occurs.
- */
- public CTRCryptoOutputStream(Output output, CryptoCipher cipher, int bufferSize,
- byte[] key, byte[] iv, long streamOffset)
- throws IOException {
- super(output, cipher, bufferSize, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));
+ /**
+ * Constructs a {@link CTRCryptoOutputStream}.
+ *
+ * @param channel the WritableByteChannel instance.
+ * @param cipher the CryptoCipher instance.
+ * @param bufferSize the bufferSize.
+ * @param key crypto key for the cipher.
+ * @param iv Initialization vector for the cipher.
+ * @param streamOffset the start offset in the data.
+ * @throws IOException if an I/O error occurs.
+ */
+ public CTRCryptoOutputStream(WritableByteChannel channel,
+ CryptoCipher cipher, int bufferSize, byte[] key, byte[] iv,
+ long streamOffset) throws IOException {
+ this(new ChannelOutput(channel), cipher, bufferSize, key, iv,
+ streamOffset);
+ }
- Utils.checkStreamCipher(cipher);
- this.streamOffset = streamOffset;
- this.initIV = iv.clone();
- this.iv = iv.clone();
+ /**
+ * Constructs a {@link CTRCryptoOutputStream}.
+ *
+ * @param output the output stream.
+ * @param cipher the CryptoCipher instance.
+ * @param bufferSize the bufferSize.
+ * @param key crypto key for the cipher.
+ * @param iv Initialization vector for the cipher.
+ * @param streamOffset the start offset in the data.
+ * @throws IOException if an I/O error occurs.
+ */
+ public CTRCryptoOutputStream(Output output, CryptoCipher cipher,
+ int bufferSize, byte[] key, byte[] iv, long streamOffset)
+ throws IOException {
+ super(output, cipher, bufferSize, new SecretKeySpec(key, "AES"),
+ new IvParameterSpec(iv));
- resetCipher();
- }
+ Utils.checkStreamCipher(cipher);
+ this.streamOffset = streamOffset;
+ this.initIV = iv.clone();
+ this.iv = iv.clone();
- /**
- * Does the encryption, input is {@link #inBuffer} and output is
- * {@link #outBuffer}.
- *
- * @throws IOException if an I/O error occurs.
- */
- @Override
- protected void encrypt() throws IOException {
- Utils.checkState(inBuffer.position() >= padding);
- if (inBuffer.position() == padding) {
- // There is no real data in the inBuffer.
- return;
+ resetCipher();
}
- inBuffer.flip();
- outBuffer.clear();
- encryptBuffer(outBuffer);
- inBuffer.clear();
- outBuffer.flip();
+ /**
+ * Does the encryption, input is {@link #inBuffer} and output is
+ * {@link #outBuffer}.
+ *
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ protected void encrypt() throws IOException {
+ Utils.checkState(inBuffer.position() >= padding);
+ if (inBuffer.position() == padding) {
+ // There is no real data in the inBuffer.
+ return;
+ }
- if (padding > 0) {
- /*
- * The plain text and cipher text have a 1:1 mapping, they start at the
- * same position.
- */
- outBuffer.position(padding);
- padding = 0;
- }
+ inBuffer.flip();
+ outBuffer.clear();
+ encryptBuffer(outBuffer);
+ inBuffer.clear();
+ outBuffer.flip();
+
+ if (padding > 0) {
+ /*
+ * The plain text and cipher text have a 1:1 mapping, they start at
+ * the same position.
+ */
+ outBuffer.position(padding);
+ padding = 0;
+ }
- final int len = output.write(outBuffer);
- streamOffset += len;
- if (cipherReset) {
- /*
- * This code is generally not executed since the encryptor usually
- * maintains encryption context (e.g. the counter) internally. However,
- * some implementations can't maintain context so a re-init is necessary
- * after each encryption call.
- */
- resetCipher();
+ final int len = output.write(outBuffer);
+ streamOffset += len;
+ if (cipherReset) {
+ /*
+ * This code is generally not executed since the encryptor usually
+ * maintains encryption context (e.g. the counter) internally.
+ * However, some implementations can't maintain context so a re-init
+ * is necessary after each encryption call.
+ */
+ resetCipher();
+ }
}
- }
- /**
- * Does final encryption of the last data.
- *
- * @throws IOException if an I/O error occurs.
- */
- @Override
- protected void encryptFinal() throws IOException {
- // The same as the normal encryption for Counter mode
- encrypt();
- }
+ /**
+ * Does final encryption of the last data.
+ *
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ protected void encryptFinal() throws IOException {
+ // The same as the normal encryption for Counter mode
+ encrypt();
+ }
- /**
- * Overrides the {@link CryptoOutputStream#initCipher()}.
- * Initializes the cipher.
- */
- @Override
- protected void initCipher() {
- // Do nothing for initCipher
- // Will reset the cipher considering the stream offset
- }
+ /**
+ * Overrides the {@link CryptoOutputStream#initCipher()}. Initializes the
+ * cipher.
+ */
+ @Override
+ protected void initCipher() {
+ // Do nothing for initCipher
+ // Will reset the cipher considering the stream offset
+ }
- /**
- * Resets the {@link #cipher}: calculate counter and {@link #padding}.
- *
- * @throws IOException if an I/O error occurs.
- */
- private void resetCipher() throws IOException {
- final long counter =
- streamOffset / cipher.getTransformation().getAlgorithmBlockSize();
- padding =
- (byte)(streamOffset % cipher.getTransformation().getAlgorithmBlockSize());
- inBuffer.position(padding); // Set proper position for input data.
+ /**
+ * Resets the {@link #cipher}: calculate counter and {@link #padding}.
+ *
+ * @throws IOException if an I/O error occurs.
+ */
+ private void resetCipher() throws IOException {
+ final long counter = streamOffset
+ / cipher.getTransformation().getAlgorithmBlockSize();
+ padding = (byte) (streamOffset % cipher.getTransformation()
+ .getAlgorithmBlockSize());
+ inBuffer.position(padding); // Set proper position for input data.
- Utils.calculateIV(initIV, counter, iv);
- try {
- cipher.init(CryptoCipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
- } catch (InvalidKeyException e) {
- throw new IOException(e);
- }catch (InvalidAlgorithmParameterException e) {
- throw new IOException(e);
+ Utils.calculateIV(initIV, counter, iv);
+ try {
+ cipher.init(CryptoCipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
+ } catch (InvalidKeyException e) {
+ throw new IOException(e);
+ } catch (InvalidAlgorithmParameterException e) {
+ throw new IOException(e);
+ }
+ cipherReset = false;
}
- cipherReset = false;
- }
- /**
- * Does the encryption if the ByteBuffer data.
- *
- * @param out the output ByteBuffer.
- * @throws IOException if an I/O error occurs.
- */
- private void encryptBuffer(ByteBuffer out)
- throws IOException {
- int inputSize = inBuffer.remaining();
- try {
- int n = cipher.update(inBuffer, out);
- if (n < inputSize) {
- /**
- * Typically code will not get here. CryptoCipher#update will consume all
- * input data and put result in outBuffer.
- * CryptoCipher#doFinal will reset the cipher context.
- */
- cipher.doFinal(inBuffer, out);
- cipherReset = true;
- }
- } catch (ShortBufferException e) {
- throw new IOException(e);
- } catch (BadPaddingException e) {
- throw new IOException(e);
- } catch (IllegalBlockSizeException e) {
- throw new IOException(e);
+ /**
+ * Does the encryption if the ByteBuffer data.
+ *
+ * @param out the output ByteBuffer.
+ * @throws IOException if an I/O error occurs.
+ */
+ private void encryptBuffer(ByteBuffer out) throws IOException {
+ int inputSize = inBuffer.remaining();
+ try {
+ int n = cipher.update(inBuffer, out);
+ if (n < inputSize) {
+ /**
+ * Typically code will not get here. CryptoCipher#update will
+ * consume all input data and put result in outBuffer.
+ * CryptoCipher#doFinal will reset the cipher context.
+ */
+ cipher.doFinal(inBuffer, out);
+ cipherReset = true;
+ }
+ } catch (ShortBufferException e) {
+ throw new IOException(e);
+ } catch (BadPaddingException e) {
+ throw new IOException(e);
+ } catch (IllegalBlockSizeException e) {
+ throw new IOException(e);
+ }
}
- }
- /**
- * Get the underlying stream offset
- *
- * @return the underlying stream offset
- */
- protected long getStreamOffset() {
- return streamOffset;
- }
+ /**
+ * Get the underlying stream offset
+ *
+ * @return the underlying stream offset
+ */
+ protected long getStreamOffset() {
+ return streamOffset;
+ }
- /**
- * Set the underlying stream offset
- *
- * @param streamOffset the underlying stream offset
- */
- protected void setStreamOffset(long streamOffset) {
- this.streamOffset = streamOffset;
- }
+ /**
+ * Set the underlying stream offset
+ *
+ * @param streamOffset the underlying stream offset
+ */
+ protected void setStreamOffset(long streamOffset) {
+ this.streamOffset = streamOffset;
+ }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/stream/CryptoInputStream.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/stream/CryptoInputStream.java b/src/main/java/org/apache/commons/crypto/stream/CryptoInputStream.java
index 7b4313b..edf3e7f 100644
--- a/src/main/java/org/apache/commons/crypto/stream/CryptoInputStream.java
+++ b/src/main/java/org/apache/commons/crypto/stream/CryptoInputStream.java
@@ -40,521 +40,526 @@ import org.apache.commons.crypto.stream.input.StreamInput;
import org.apache.commons.crypto.utils.Utils;
/**
- * CryptoInputStream reads input data and decrypts data in stream manner. It supports
- * any mode of operations such as AES CBC/CTR/GCM mode in concept.It is not thread-safe.
+ * CryptoInputStream reads input data and decrypts data in stream manner. It
+ * supports any mode of operations such as AES CBC/CTR/GCM mode in concept.It is
+ * not thread-safe.
*
*/
public class CryptoInputStream extends InputStream implements
- ReadableByteChannel {
- private final byte[] oneByteBuf = new byte[1];
-
- /**The CryptoCipher instance.*/
- final CryptoCipher cipher;
-
- /**The buffer size.*/
- final int bufferSize;
-
- /**Crypto key for the cipher.*/
- final Key key;
-
- /** the algorithm parameters */
- final AlgorithmParameterSpec params;
-
- /** Flag to mark whether the input stream is closed.*/
- private boolean closed;
-
- /** Flag to mark whether do final of the cipher to end the decrypting stream.*/
- private boolean finalDone = false;
-
- /**The input data.*/
- Input input;
-
- /**
- * Input data buffer. The data starts at inBuffer.position() and ends at
- * to inBuffer.limit().
- */
- protected ByteBuffer inBuffer;
-
- /**
- * The decrypted data buffer. The data starts at outBuffer.position() and
- * ends at outBuffer.limit().
- */
- protected ByteBuffer outBuffer;
-
- /**
- * Constructs a {@link CryptoInputStream}.
- *
- * @param transformation the CipherTransformation instance.
- * @param props The <code>Properties</code> class represents a set of
- * properties.
- * @param in the input stream.
- * @param key crypto key for the cipher.
- * @param params the algorithm parameters.
- * @throws IOException if an I/O error occurs.
- */
- public CryptoInputStream(CipherTransformation transformation,
- Properties props, InputStream in, Key key, AlgorithmParameterSpec params)
- throws IOException {
- this(in, Utils.getCipherInstance(transformation, props), Utils.getBufferSize(props), key,
- params);
- }
-
- /**
- * Constructs a {@link CryptoInputStream}.
- *
- * @param transformation the CipherTransformation instance.
- * @param props The <code>Properties</code> class represents a set of
- * properties.
- * @param in the ReadableByteChannel object.
- * @param key crypto key for the cipher.
- * @param params the algorithm parameters.
- * @throws IOException if an I/O error occurs.
- */
- public CryptoInputStream(CipherTransformation transformation,
- Properties props, ReadableByteChannel in, Key key, AlgorithmParameterSpec params)
- throws IOException {
- this(in, Utils.getCipherInstance(transformation, props),
- Utils.getBufferSize(props), key, params);
- }
-
- /**
- * Constructs a {@link CryptoInputStream}.
- *
- * @param cipher the cipher instance.
- * @param in the input stream.
- * @param bufferSize the bufferSize.
- * @param key crypto key for the cipher.
- * @param params the algorithm parameters.
- * @throws IOException if an I/O error occurs.
- */
- public CryptoInputStream(InputStream in, CryptoCipher cipher, int bufferSize,
- Key key, AlgorithmParameterSpec params) throws IOException {
- this(new StreamInput(in, bufferSize), cipher, bufferSize, key, params);
- }
-
- /**
- * Constructs a {@link CryptoInputStream}.
- *
- * @param in the ReadableByteChannel instance.
- * @param cipher the cipher instance.
- * @param bufferSize the bufferSize.
- * @param key crypto key for the cipher.
- * @param params the algorithm parameters.
- * @throws IOException if an I/O error occurs.
- */
- public CryptoInputStream(ReadableByteChannel in, CryptoCipher cipher,
- int bufferSize, Key key, AlgorithmParameterSpec params) throws IOException {
- this(new ChannelInput(in), cipher, bufferSize, key, params);
- }
-
- /**
- * Constructs a {@link CryptoInputStream}.
- *
- * @param input the input data.
- * @param cipher the cipher instance.
- * @param bufferSize the bufferSize.
- * @param key crypto key for the cipher.
- * @param params the algorithm parameters.
- * @throws IOException if an I/O error occurs.
- */
- public CryptoInputStream(Input input, CryptoCipher cipher, int bufferSize,
- Key key, AlgorithmParameterSpec params) throws IOException {
- this.input = input;
- this.cipher = cipher;
- this.bufferSize = Utils.checkBufferSize(cipher, bufferSize);
-
- this.key = key;
- this.params = params;
- if (!(params instanceof IvParameterSpec)) {
- //other AlgorithmParameterSpec such as GCMParameterSpec is not supported now.
- throw new IOException("Illegal parameters");
+ ReadableByteChannel {
+ private final byte[] oneByteBuf = new byte[1];
+
+ /** The CryptoCipher instance. */
+ final CryptoCipher cipher;
+
+ /** The buffer size. */
+ final int bufferSize;
+
+ /** Crypto key for the cipher. */
+ final Key key;
+
+ /** the algorithm parameters */
+ final AlgorithmParameterSpec params;
+
+ /** Flag to mark whether the input stream is closed. */
+ private boolean closed;
+
+ /**
+ * Flag to mark whether do final of the cipher to end the decrypting stream.
+ */
+ private boolean finalDone = false;
+
+ /** The input data. */
+ Input input;
+
+ /**
+ * Input data buffer. The data starts at inBuffer.position() and ends at to
+ * inBuffer.limit().
+ */
+ protected ByteBuffer inBuffer;
+
+ /**
+ * The decrypted data buffer. The data starts at outBuffer.position() and
+ * ends at outBuffer.limit().
+ */
+ protected ByteBuffer outBuffer;
+
+ /**
+ * Constructs a {@link CryptoInputStream}.
+ *
+ * @param transformation the CipherTransformation instance.
+ * @param props The <code>Properties</code> class represents a set of
+ * properties.
+ * @param in the input stream.
+ * @param key crypto key for the cipher.
+ * @param params the algorithm parameters.
+ * @throws IOException if an I/O error occurs.
+ */
+ public CryptoInputStream(CipherTransformation transformation,
+ Properties props, InputStream in, Key key,
+ AlgorithmParameterSpec params) throws IOException {
+ this(in, Utils.getCipherInstance(transformation, props), Utils
+ .getBufferSize(props), key, params);
}
- inBuffer = ByteBuffer.allocateDirect(this.bufferSize);
- outBuffer = ByteBuffer.allocateDirect(this.bufferSize +
- cipher.getTransformation().getAlgorithmBlockSize());
- outBuffer.limit(0);
-
- initCipher();
- }
-
- /**
- * Overrides the {@link java.io.InputStream#read()}.
- * Reads the next byte of data from the input stream.
- *
- * @return the next byte of data, or <code>-1</code> if the end of the
- * stream is reached.
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public int read() throws IOException {
- int n;
- while ((n = read(oneByteBuf, 0, 1)) == 0) ;
- return (n == -1) ? -1 : oneByteBuf[0] & 0xff;
- }
-
- /**
- * Overrides the {@link java.io.InputStream#read(byte[], int, int)}.
- * Decryption is buffer based.
- * If there is data in {@link #outBuffer}, then read it out of this buffer.
- * If there is no data in {@link #outBuffer}, then read more from the
- * underlying stream and do the decryption.
- *
- * @param b the buffer into which the decrypted data is read.
- * @param off the buffer offset.
- * @param len the maximum number of decrypted data bytes to read.
- * @return int the total number of decrypted data bytes read into the buffer.
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public int read(byte[] b, int off, int len) throws IOException {
- checkStream();
- if (b == null) {
- throw new NullPointerException();
- } else if (off < 0 || len < 0 || len > b.length - off) {
- throw new IndexOutOfBoundsException();
- } else if (len == 0) {
- return 0;
+ /**
+ * Constructs a {@link CryptoInputStream}.
+ *
+ * @param transformation the CipherTransformation instance.
+ * @param props The <code>Properties</code> class represents a set of
+ * properties.
+ * @param in the ReadableByteChannel object.
+ * @param key crypto key for the cipher.
+ * @param params the algorithm parameters.
+ * @throws IOException if an I/O error occurs.
+ */
+ public CryptoInputStream(CipherTransformation transformation,
+ Properties props, ReadableByteChannel in, Key key,
+ AlgorithmParameterSpec params) throws IOException {
+ this(in, Utils.getCipherInstance(transformation, props), Utils
+ .getBufferSize(props), key, params);
}
- int remaining = outBuffer.remaining();
- if (remaining > 0) {
- // Satisfy the read with the existing data
- int n = Math.min(len, remaining);
- outBuffer.get(b, off, n);
- return n;
- } else {
- // No data in the out buffer, try read new data and decrypt it
- int nd = decryptMore();
- if(nd <= 0)
- return nd;
-
- int n = Math.min(len, outBuffer.remaining());
- outBuffer.get(b, off, n);
- return n;
+ /**
+ * Constructs a {@link CryptoInputStream}.
+ *
+ * @param cipher the cipher instance.
+ * @param in the input stream.
+ * @param bufferSize the bufferSize.
+ * @param key crypto key for the cipher.
+ * @param params the algorithm parameters.
+ * @throws IOException if an I/O error occurs.
+ */
+ public CryptoInputStream(InputStream in, CryptoCipher cipher,
+ int bufferSize, Key key, AlgorithmParameterSpec params)
+ throws IOException {
+ this(new StreamInput(in, bufferSize), cipher, bufferSize, key, params);
}
- }
-
- /**
- * Overrides the {@link java.io.InputStream#skip(long)}.
- * Skips over and discards <code>n</code> bytes of data from this input
- * stream.
- *
- * @param n the number of bytes to be skipped.
- * @return the actual number of bytes skipped.
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public long skip(long n) throws IOException {
- Utils.checkArgument(n >= 0, "Negative skip length.");
- checkStream();
-
- if (n == 0) {
- return 0;
+
+ /**
+ * Constructs a {@link CryptoInputStream}.
+ *
+ * @param in the ReadableByteChannel instance.
+ * @param cipher the cipher instance.
+ * @param bufferSize the bufferSize.
+ * @param key crypto key for the cipher.
+ * @param params the algorithm parameters.
+ * @throws IOException if an I/O error occurs.
+ */
+ public CryptoInputStream(ReadableByteChannel in, CryptoCipher cipher,
+ int bufferSize, Key key, AlgorithmParameterSpec params)
+ throws IOException {
+ this(new ChannelInput(in), cipher, bufferSize, key, params);
}
- long remaining = n;
- int nd;
+ /**
+ * Constructs a {@link CryptoInputStream}.
+ *
+ * @param input the input data.
+ * @param cipher the cipher instance.
+ * @param bufferSize the bufferSize.
+ * @param key crypto key for the cipher.
+ * @param params the algorithm parameters.
+ * @throws IOException if an I/O error occurs.
+ */
+ public CryptoInputStream(Input input, CryptoCipher cipher, int bufferSize,
+ Key key, AlgorithmParameterSpec params) throws IOException {
+ this.input = input;
+ this.cipher = cipher;
+ this.bufferSize = Utils.checkBufferSize(cipher, bufferSize);
+
+ this.key = key;
+ this.params = params;
+ if (!(params instanceof IvParameterSpec)) {
+ // other AlgorithmParameterSpec such as GCMParameterSpec is not
+ // supported now.
+ throw new IOException("Illegal parameters");
+ }
+
+ inBuffer = ByteBuffer.allocateDirect(this.bufferSize);
+ outBuffer = ByteBuffer.allocateDirect(this.bufferSize
+ + cipher.getTransformation().getAlgorithmBlockSize());
+ outBuffer.limit(0);
+
+ initCipher();
+ }
- while (remaining > 0) {
- if(remaining <= outBuffer.remaining()) {
- // Skip in the remaining buffer
- int pos = outBuffer.position() + (int) remaining;
- outBuffer.position(pos);
+ /**
+ * Overrides the {@link java.io.InputStream#read()}. Reads the next byte of
+ * data from the input stream.
+ *
+ * @return the next byte of data, or <code>-1</code> if the end of the
+ * stream is reached.
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public int read() throws IOException {
+ int n;
+ while ((n = read(oneByteBuf, 0, 1)) == 0)
+ ;
+ return (n == -1) ? -1 : oneByteBuf[0] & 0xff;
+ }
- remaining = 0;
- break;
- } else {
- remaining -= outBuffer.remaining();
- outBuffer.clear();
- }
+ /**
+ * Overrides the {@link java.io.InputStream#read(byte[], int, int)}.
+ * Decryption is buffer based. If there is data in {@link #outBuffer}, then
+ * read it out of this buffer. If there is no data in {@link #outBuffer},
+ * then read more from the underlying stream and do the decryption.
+ *
+ * @param b the buffer into which the decrypted data is read.
+ * @param off the buffer offset.
+ * @param len the maximum number of decrypted data bytes to read.
+ * @return int the total number of decrypted data bytes read into the
+ * buffer.
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public int read(byte[] b, int off, int len) throws IOException {
+ checkStream();
+ if (b == null) {
+ throw new NullPointerException();
+ } else if (off < 0 || len < 0 || len > b.length - off) {
+ throw new IndexOutOfBoundsException();
+ } else if (len == 0) {
+ return 0;
+ }
+
+ int remaining = outBuffer.remaining();
+ if (remaining > 0) {
+ // Satisfy the read with the existing data
+ int n = Math.min(len, remaining);
+ outBuffer.get(b, off, n);
+ return n;
+ } else {
+ // No data in the out buffer, try read new data and decrypt it
+ int nd = decryptMore();
+ if (nd <= 0)
+ return nd;
+
+ int n = Math.min(len, outBuffer.remaining());
+ outBuffer.get(b, off, n);
+ return n;
+ }
+ }
+
+ /**
+ * Overrides the {@link java.io.InputStream#skip(long)}. Skips over and
+ * discards <code>n</code> bytes of data from this input stream.
+ *
+ * @param n the number of bytes to be skipped.
+ * @return the actual number of bytes skipped.
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public long skip(long n) throws IOException {
+ Utils.checkArgument(n >= 0, "Negative skip length.");
+ checkStream();
+
+ if (n == 0) {
+ return 0;
+ }
+
+ long remaining = n;
+ int nd;
+
+ while (remaining > 0) {
+ if (remaining <= outBuffer.remaining()) {
+ // Skip in the remaining buffer
+ int pos = outBuffer.position() + (int) remaining;
+ outBuffer.position(pos);
+
+ remaining = 0;
+ break;
+ } else {
+ remaining -= outBuffer.remaining();
+ outBuffer.clear();
+ }
+
+ nd = decryptMore();
+ if (nd < 0) {
+ break;
+ }
+ }
+
+ return n - remaining;
+ }
+
+ /**
+ * Overrides the {@link InputStream#available()}. Returns an estimate of the
+ * number of bytes that can be read (or skipped over) from this input stream
+ * without blocking by the next invocation of a method for this input
+ * stream.
+ *
+ * @return an estimate of the number of bytes that can be read (or skipped
+ * over) from this input stream without blocking or {@code 0} when
+ * it reaches the end of the input stream.
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public int available() throws IOException {
+ checkStream();
+
+ return input.available() + outBuffer.remaining();
+ }
+
+ /**
+ * Overrides the {@link InputStream#close()}. Closes this input stream and
+ * releases any system resources associated with the stream.
+ *
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public void close() throws IOException {
+ if (closed) {
+ return;
+ }
+
+ input.close();
+ freeBuffers();
+ cipher.close();
+ super.close();
+ closed = true;
+ }
+
+ /**
+ * Overrides the {@link java.io.InputStream#mark(int)}. For
+ * {@link CryptoInputStream},we don't support the mark method.
+ *
+ * @param readlimit the maximum limit of bytes that can be read before the
+ * mark position becomes invalid.
+ */
+ @Override
+ public void mark(int readlimit) {
+ }
+
+ /**
+ * Overrides the {@link InputStream#reset()}. For {@link CryptoInputStream}
+ * ,we don't support the reset method.
+ *
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public void reset() throws IOException {
+ throw new IOException("Mark/reset not supported");
+ }
- nd = decryptMore();
- if (nd < 0) {
- break;
- }
+ /**
+ * Overrides the {@link InputStream#markSupported()}.
+ *
+ * @return false,the {@link CTRCryptoInputStream} don't support the mark
+ * method.
+ */
+ @Override
+ public boolean markSupported() {
+ return false;
}
- return n - remaining;
- }
-
- /**
- * Overrides the {@link InputStream#available()}.
- * Returns an estimate of the number of bytes that can be read (or
- * skipped over) from this input stream without blocking by the next
- * invocation of a method for this input stream.
- *
- * @return an estimate of the number of bytes that can be read (or skipped
- * over) from this input stream without blocking or {@code 0} when
- * it reaches the end of the input stream.
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public int available() throws IOException {
- checkStream();
-
- return input.available() + outBuffer.remaining();
- }
-
- /**
- * Overrides the {@link InputStream#close()}.
- * Closes this input stream and releases any system resources associated
- * with the stream.
- *
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public void close() throws IOException {
- if (closed) {
- return;
+ /**
+ * Overrides the {@link Channel#isOpen()}.
+ *
+ * @return <tt>true</tt> if, and only if, this channel is open.
+ */
+ @Override
+ public boolean isOpen() {
+ return !closed;
}
- input.close();
- freeBuffers();
- cipher.close();
- super.close();
- closed = true;
- }
-
- /**
- * Overrides the {@link java.io.InputStream#mark(int)}.
- * For {@link CryptoInputStream},we don't support the mark method.
- *
- * @param readlimit the maximum limit of bytes that can be read before
- * the mark position becomes invalid.
- */
- @Override
- public void mark(int readlimit) {
- }
-
- /**
- * Overrides the {@link InputStream#reset()}.
- * For {@link CryptoInputStream},we don't support the reset method.
- *
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public void reset() throws IOException {
- throw new IOException("Mark/reset not supported");
- }
-
- /**
- * Overrides the {@link InputStream#markSupported()}.
- *
- * @return false,the {@link CTRCryptoInputStream} don't support the mark method.
- */
- @Override
- public boolean markSupported() {
- return false;
- }
-
- /**
- * Overrides the {@link Channel#isOpen()}.
- *
- * @return <tt>true</tt> if, and only if, this channel is open.
- */
- @Override
- public boolean isOpen() {
- return !closed;
- }
-
- /**
- * Overrides the {@link java.nio.channels.ReadableByteChannel#read(ByteBuffer)}.
- * Reads a sequence of bytes from this channel into the given buffer.
- *
- * @param dst The buffer into which bytes are to be transferred.
- * @return The number of bytes read, possibly zero, or <tt>-1</tt> if the
- * channel has reached end-of-stream.
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public int read(ByteBuffer dst) throws IOException {
- checkStream();
- int remaining = outBuffer.remaining();
- if (remaining <= 0) {
- // Decrypt more data
- int nd = decryptMore();
- if(nd < 0) {
- return -1;
- }
+ /**
+ * Overrides the
+ * {@link java.nio.channels.ReadableByteChannel#read(ByteBuffer)}. Reads a
+ * sequence of bytes from this channel into the given buffer.
+ *
+ * @param dst The buffer into which bytes are to be transferred.
+ * @return The number of bytes read, possibly zero, or <tt>-1</tt> if the
+ * channel has reached end-of-stream.
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public int read(ByteBuffer dst) throws IOException {
+ checkStream();
+ int remaining = outBuffer.remaining();
+ if (remaining <= 0) {
+ // Decrypt more data
+ int nd = decryptMore();
+ if (nd < 0) {
+ return -1;
+ }
+ }
+
+ // Copy decrypted data from outBuffer to dst
+ remaining = outBuffer.remaining();
+ final int toRead = dst.remaining();
+ if (toRead <= remaining) {
+ final int limit = outBuffer.limit();
+ outBuffer.limit(outBuffer.position() + toRead);
+ dst.put(outBuffer);
+ outBuffer.limit(limit);
+ return toRead;
+ } else {
+ dst.put(outBuffer);
+ return remaining;
+ }
}
- // Copy decrypted data from outBuffer to dst
- remaining = outBuffer.remaining();
- final int toRead = dst.remaining();
- if (toRead <= remaining) {
- final int limit = outBuffer.limit();
- outBuffer.limit(outBuffer.position() + toRead);
- dst.put(outBuffer);
- outBuffer.limit(limit);
- return toRead;
- } else {
- dst.put(outBuffer);
- return remaining;
+ /**
+ * Gets the buffer size.
+ *
+ * @return the bufferSize.
+ */
+ protected int getBufferSize() {
+ return bufferSize;
}
- }
-
- /**
- * Gets the buffer size.
- *
- * @return the bufferSize.
- */
- protected int getBufferSize() {
- return bufferSize;
- }
-
- /**
- * Gets the key.
- *
- * @return the key.
- */
- protected Key getKey() {
- return key;
- }
-
-
- /**
- * Gets the internal CryptoCipher.
- *
- * @return the cipher instance.
- */
- protected CryptoCipher getCipher() {
- return cipher;
- }
-
- /**
- * Gets the specification of cryptographic parameters.
- *
- * @return the params.
- */
- protected AlgorithmParameterSpec getParams() {
- return params;
- }
-
- /**
- * Gets the input.
- *
- * @return the input.
- */
- protected Input getInput() {
- return input;
- }
-
- /**
- * Initializes the cipher.
- *
- * @throws IOException if an I/O error occurs.
- */
- protected void initCipher()
- throws IOException {
- try {
- cipher.init(CryptoCipher.DECRYPT_MODE, key, params);
- } catch (InvalidKeyException e) {
- throw new IOException(e);
- } catch(InvalidAlgorithmParameterException e) {
- throw new IOException(e);
+
+ /**
+ * Gets the key.
+ *
+ * @return the key.
+ */
+ protected Key getKey() {
+ return key;
+ }
+
+ /**
+ * Gets the internal CryptoCipher.
+ *
+ * @return the cipher instance.
+ */
+ protected CryptoCipher getCipher() {
+ return cipher;
}
- }
-
- /**
- * Decrypts more data by reading the under layer stream. The decrypted data will
- * be put in the output buffer. If the end of the under stream reached, we will
- * do final of the cipher to finish all the decrypting of data.
- *
- * @return The number of decrypted data. -1 if end of the decrypted stream.
- * @throws IOException if an I/O error occurs.
- */
- protected int decryptMore() throws IOException {
- if(finalDone) {
- return -1;
+
+ /**
+ * Gets the specification of cryptographic parameters.
+ *
+ * @return the params.
+ */
+ protected AlgorithmParameterSpec getParams() {
+ return params;
}
- int n = input.read(inBuffer);
- if (n < 0) {
- // The stream is end, finalize the cipher stream
- decryptFinal();
-
- // Satisfy the read with the remaining
- int remaining = outBuffer.remaining();
- if (remaining > 0) {
- return remaining;
- }
-
- // End of the stream
- return -1;
- } else if(n == 0) {
- // No data is read, but the stream is not end yet
- return 0;
- } else {
- decrypt();
- return outBuffer.remaining();
+ /**
+ * Gets the input.
+ *
+ * @return the input.
+ */
+ protected Input getInput() {
+ return input;
}
- }
-
- /**
- * Does the decryption using inBuffer as input and outBuffer as output.
- * Upon return, inBuffer is cleared; the decrypted data starts at
- * outBuffer.position() and ends at outBuffer.limit().
- *
- * @throws IOException if an I/O error occurs.
- */
- protected void decrypt() throws IOException {
- // Prepare the input buffer and clear the out buffer
- inBuffer.flip();
- outBuffer.clear();
-
- try {
- cipher.update(inBuffer, outBuffer);
- } catch (ShortBufferException e) {
- throw new IOException(e);
+
+ /**
+ * Initializes the cipher.
+ *
+ * @throws IOException if an I/O error occurs.
+ */
+ protected void initCipher() throws IOException {
+ try {
+ cipher.init(CryptoCipher.DECRYPT_MODE, key, params);
+ } catch (InvalidKeyException e) {
+ throw new IOException(e);
+ } catch (InvalidAlgorithmParameterException e) {
+ throw new IOException(e);
+ }
}
- // Clear the input buffer and prepare out buffer
- inBuffer.clear();
- outBuffer.flip();
- }
-
- /**
- * Does final of the cipher to end the decrypting stream.
- *
- *@throws IOException if an I/O error occurs.
- */
- protected void decryptFinal() throws IOException {
- // Prepare the input buffer and clear the out buffer
- inBuffer.flip();
- outBuffer.clear();
-
- try {
- cipher.doFinal(inBuffer, outBuffer);
- finalDone = true;
- } catch (ShortBufferException e) {
- throw new IOException(e);
- } catch (IllegalBlockSizeException e) {
- throw new IOException(e);
- } catch( BadPaddingException e) {
- throw new IOException(e);
+ /**
+ * Decrypts more data by reading the under layer stream. The decrypted data
+ * will be put in the output buffer. If the end of the under stream reached,
+ * we will do final of the cipher to finish all the decrypting of data.
+ *
+ * @return The number of decrypted data. -1 if end of the decrypted stream.
+ * @throws IOException if an I/O error occurs.
+ */
+ protected int decryptMore() throws IOException {
+ if (finalDone) {
+ return -1;
+ }
+
+ int n = input.read(inBuffer);
+ if (n < 0) {
+ // The stream is end, finalize the cipher stream
+ decryptFinal();
+
+ // Satisfy the read with the remaining
+ int remaining = outBuffer.remaining();
+ if (remaining > 0) {
+ return remaining;
+ }
+
+ // End of the stream
+ return -1;
+ } else if (n == 0) {
+ // No data is read, but the stream is not end yet
+ return 0;
+ } else {
+ decrypt();
+ return outBuffer.remaining();
+ }
}
- // Clear the input buffer and prepare out buffer
- inBuffer.clear();
- outBuffer.flip();
- }
-
- /**
- * Checks whether the stream is closed.
- *
- * @throws IOException if an I/O error occurs.
- */
- protected void checkStream() throws IOException {
- if (closed) {
- throw new IOException("Stream closed");
+ /**
+ * Does the decryption using inBuffer as input and outBuffer as output. Upon
+ * return, inBuffer is cleared; the decrypted data starts at
+ * outBuffer.position() and ends at outBuffer.limit().
+ *
+ * @throws IOException if an I/O error occurs.
+ */
+ protected void decrypt() throws IOException {
+ // Prepare the input buffer and clear the out buffer
+ inBuffer.flip();
+ outBuffer.clear();
+
+ try {
+ cipher.update(inBuffer, outBuffer);
+ } catch (ShortBufferException e) {
+ throw new IOException(e);
+ }
+
+ // Clear the input buffer and prepare out buffer
+ inBuffer.clear();
+ outBuffer.flip();
}
- }
- /** Forcibly free the direct buffers. */
- protected void freeBuffers() {
- Utils.freeDirectBuffer(inBuffer);
- Utils.freeDirectBuffer(outBuffer);
- }
+ /**
+ * Does final of the cipher to end the decrypting stream.
+ *
+ * @throws IOException if an I/O error occurs.
+ */
+ protected void decryptFinal() throws IOException {
+ // Prepare the input buffer and clear the out buffer
+ inBuffer.flip();
+ outBuffer.clear();
+
+ try {
+ cipher.doFinal(inBuffer, outBuffer);
+ finalDone = true;
+ } catch (ShortBufferException e) {
+ throw new IOException(e);
+ } catch (IllegalBlockSizeException e) {
+ throw new IOException(e);
+ } catch (BadPaddingException e) {
+ throw new IOException(e);
+ }
+
+ // Clear the input buffer and prepare out buffer
+ inBuffer.clear();
+ outBuffer.flip();
+ }
+
+ /**
+ * Checks whether the stream is closed.
+ *
+ * @throws IOException if an I/O error occurs.
+ */
+ protected void checkStream() throws IOException {
+ if (closed) {
+ throw new IOException("Stream closed");
+ }
+ }
+
+ /** Forcibly free the direct buffers. */
+ protected void freeBuffers() {
+ Utils.freeDirectBuffer(inBuffer);
+ Utils.freeDirectBuffer(outBuffer);
+ }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/stream/CryptoOutputStream.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/stream/CryptoOutputStream.java b/src/main/java/org/apache/commons/crypto/stream/CryptoOutputStream.java
index ef91beb..2fd00d2 100644
--- a/src/main/java/org/apache/commons/crypto/stream/CryptoOutputStream.java
+++ b/src/main/java/org/apache/commons/crypto/stream/CryptoOutputStream.java
@@ -43,399 +43,393 @@ import org.apache.commons.crypto.utils.Utils;
/**
* {@link CryptoOutputStream} encrypts data and writes to the under layer
- * output. It supports any mode of operations such as AES CBC/CTR/GCM mode
- * in concept. It is not thread-safe.
+ * output. It supports any mode of operations such as AES CBC/CTR/GCM mode in
+ * concept. It is not thread-safe.
*/
public class CryptoOutputStream extends OutputStream implements
- WritableByteChannel {
- private final byte[] oneByteBuf = new byte[1];
-
- /** The output.*/
- Output output;
-
- /**the CryptoCipher instance*/
- final CryptoCipher cipher;
-
- /**The buffer size.*/
- final int bufferSize;
-
- /**Crypto key for the cipher.*/
- final Key key;
-
- /** the algorithm parameters */
- final AlgorithmParameterSpec params;
-
- /** Flag to mark whether the output stream is closed.*/
- private boolean closed;
-
- /**
- * Input data buffer. The data starts at inBuffer.position() and ends at
- * inBuffer.limit().
- */
- ByteBuffer inBuffer;
-
- /**
- * Encrypted data buffer. The data starts at outBuffer.position() and ends at
- * outBuffer.limit().
- */
- ByteBuffer outBuffer;
-
- /**
- * Constructs a {@link CryptoOutputStream}.
- *
- * @param transformation the CipherTransformation instance.
- * @param props The <code>Properties</code> class represents a set of
- * properties.
- * @param out the output stream.
- * @param key crypto key for the cipher.
- * @param params the algorithm parameters.
- * @throws IOException if an I/O error occurs.
- */
-
-
- public CryptoOutputStream(
- CipherTransformation transformation,
- Properties props,
- OutputStream out,
- Key key,
- AlgorithmParameterSpec params) throws IOException {
- this(out, Utils.getCipherInstance(transformation, props), Utils.getBufferSize(props), key, params);
-
- }
-
- /**
- * Constructs a {@link CryptoOutputStream}.
- *
- * @param transformation the CipherTransformation instance.
- * @param props The <code>Properties</code> class represents a set of
- * properties.
- * @param out the WritableByteChannel instance.
- * @param key crypto key for the cipher.
- * @param params the algorithm parameters.
- * @throws IOException if an I/O error occurs.
- */
- public CryptoOutputStream(
- CipherTransformation transformation,
- Properties props,
- WritableByteChannel out,
- Key key,
- AlgorithmParameterSpec params) throws IOException {
- this(out, Utils.getCipherInstance(transformation, props),
- Utils.getBufferSize(props), key, params);
-
- }
-
- /**
- * Constructs a {@link CryptoOutputStream}.
- *
- * @param out the output stream.
- * @param cipher the CryptoCipher instance.
- * @param bufferSize the bufferSize.
- * @param key crypto key for the cipher.
- * @param params the algorithm parameters.
- * @throws IOException if an I/O error occurs.
- */
- public CryptoOutputStream(OutputStream out, CryptoCipher cipher, int bufferSize,
- Key key, AlgorithmParameterSpec params) throws IOException {
- this(new StreamOutput(out, bufferSize), cipher, bufferSize, key, params);
- }
-
- /**
- * Constructs a {@link CryptoOutputStream}.
- *
- * @param channel the WritableByteChannel instance.
- * @param cipher the cipher instance.
- * @param bufferSize the bufferSize.
- * @param key crypto key for the cipher.
- * @param params the algorithm parameters.
- * @throws IOException if an I/O error occurs.
- */
- public CryptoOutputStream(WritableByteChannel channel, CryptoCipher cipher,
- int bufferSize, Key key, AlgorithmParameterSpec params) throws IOException {
- this(new ChannelOutput(channel), cipher, bufferSize, key, params);
- }
-
- /**
- * Constructs a {@link CryptoOutputStream}.
- *
- * @param output the output stream.
- * @param cipher the CryptoCipher instance.
- * @param bufferSize the bufferSize.
- * @param key crypto key for the cipher.
- * @param params the algorithm parameters.
- * @throws IOException if an I/O error occurs.
- */
- protected CryptoOutputStream(Output output, CryptoCipher cipher, int bufferSize,
- Key key, AlgorithmParameterSpec params)
- throws IOException {
-
- this.output = output;
- this.bufferSize = Utils.checkBufferSize(cipher, bufferSize);
- this.cipher = cipher;
-
- this.key = key;
- this.params = params;
-
- if (!(params instanceof IvParameterSpec)) {
- //other AlgorithmParameterSpec such as GCMParameterSpec is not supported now.
- throw new IOException("Illegal parameters");
+ WritableByteChannel {
+ private final byte[] oneByteBuf = new byte[1];
+
+ /** The output. */
+ Output output;
+
+ /** the CryptoCipher instance */
+ final CryptoCipher cipher;
+
+ /** The buffer size. */
+ final int bufferSize;
+
+ /** Crypto key for the cipher. */
+ final Key key;
+
+ /** the algorithm parameters */
+ final AlgorithmParameterSpec params;
+
+ /** Flag to mark whether the output stream is closed. */
+ private boolean closed;
+
+ /**
+ * Input data buffer. The data starts at inBuffer.position() and ends at
+ * inBuffer.limit().
+ */
+ ByteBuffer inBuffer;
+
+ /**
+ * Encrypted data buffer. The data starts at outBuffer.position() and ends
+ * at outBuffer.limit().
+ */
+ ByteBuffer outBuffer;
+
+ /**
+ * Constructs a {@link CryptoOutputStream}.
+ *
+ * @param transformation the CipherTransformation instance.
+ * @param props The <code>Properties</code> class represents a set of
+ * properties.
+ * @param out the output stream.
+ * @param key crypto key for the cipher.
+ * @param params the algorithm parameters.
+ * @throws IOException if an I/O error occurs.
+ */
+
+ public CryptoOutputStream(CipherTransformation transformation,
+ Properties props, OutputStream out, Key key,
+ AlgorithmParameterSpec params) throws IOException {
+ this(out, Utils.getCipherInstance(transformation, props), Utils
+ .getBufferSize(props), key, params);
+
}
- inBuffer = ByteBuffer.allocateDirect(this.bufferSize);
- outBuffer = ByteBuffer.allocateDirect(this.bufferSize +
- cipher.getTransformation().getAlgorithmBlockSize());
-
- initCipher();
- }
-
- /**
- * Overrides the {@link java.io.OutputStream#write(byte[])}.
- * Writes the specified byte to this output stream.
- *
- * @param b the data.
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public void write(int b) throws IOException {
- oneByteBuf[0] = (byte) (b & 0xff);
- write(oneByteBuf, 0, oneByteBuf.length);
- }
-
- /**
- * Overrides the {@link java.io.OutputStream#write(byte[], int, int)}.
- * Encryption is buffer based.
- * If there is enough room in {@link #inBuffer}, then write to this buffer.
- * If {@link #inBuffer} is full, then do encryption and write data to the
- * underlying stream.
- *
- * @param b the data.
- * @param off the start offset in the data.
- * @param len the number of bytes to write.
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public void write(byte[] b, int off, int len) throws IOException {
- checkStream();
- if (b == null) {
- throw new NullPointerException();
- } else if (off < 0 || len < 0 || off > b.length ||
- len > b.length - off) {
- throw new IndexOutOfBoundsException();
+ /**
+ * Constructs a {@link CryptoOutputStream}.
+ *
+ * @param transformation the CipherTransformation instance.
+ * @param props The <code>Properties</code> class represents a set of
+ * properties.
+ * @param out the WritableByteChannel instance.
+ * @param key crypto key for the cipher.
+ * @param params the algorithm parameters.
+ * @throws IOException if an I/O error occurs.
+ */
+ public CryptoOutputStream(CipherTransformation transformation,
+ Properties props, WritableByteChannel out, Key key,
+ AlgorithmParameterSpec params) throws IOException {
+ this(out, Utils.getCipherInstance(transformation, props), Utils
+ .getBufferSize(props), key, params);
+
}
- while (len > 0) {
- final int remaining = inBuffer.remaining();
- if (len < remaining) {
- inBuffer.put(b, off, len);
- len = 0;
- } else {
- inBuffer.put(b, off, remaining);
- off += remaining;
- len -= remaining;
- encrypt();
- }
+ /**
+ * Constructs a {@link CryptoOutputStream}.
+ *
+ * @param out the output stream.
+ * @param cipher the CryptoCipher instance.
+ * @param bufferSize the bufferSize.
+ * @param key crypto key for the cipher.
+ * @param params the algorithm parameters.
+ * @throws IOException if an I/O error occurs.
+ */
+ public CryptoOutputStream(OutputStream out, CryptoCipher cipher,
+ int bufferSize, Key key, AlgorithmParameterSpec params)
+ throws IOException {
+ this(new StreamOutput(out, bufferSize), cipher, bufferSize, key, params);
+ }
+
+ /**
+ * Constructs a {@link CryptoOutputStream}.
+ *
+ * @param channel the WritableByteChannel instance.
+ * @param cipher the cipher instance.
+ * @param bufferSize the bufferSize.
+ * @param key crypto key for the cipher.
+ * @param params the algorithm parameters.
+ * @throws IOException if an I/O error occurs.
+ */
+ public CryptoOutputStream(WritableByteChannel channel, CryptoCipher cipher,
+ int bufferSize, Key key, AlgorithmParameterSpec params)
+ throws IOException {
+ this(new ChannelOutput(channel), cipher, bufferSize, key, params);
+ }
+
+ /**
+ * Constructs a {@link CryptoOutputStream}.
+ *
+ * @param output the output stream.
+ * @param cipher the CryptoCipher instance.
+ * @param bufferSize the bufferSize.
+ * @param key crypto key for the cipher.
+ * @param params the algorithm parameters.
+ * @throws IOException if an I/O error occurs.
+ */
+ protected CryptoOutputStream(Output output, CryptoCipher cipher,
+ int bufferSize, Key key, AlgorithmParameterSpec params)
+ throws IOException {
+
+ this.output = output;
+ this.bufferSize = Utils.checkBufferSize(cipher, bufferSize);
+ this.cipher = cipher;
+
+ this.key = key;
+ this.params = params;
+
+ if (!(params instanceof IvParameterSpec)) {
+ // other AlgorithmParameterSpec such as GCMParameterSpec is not
+ // supported now.
+ throw new IOException("Illegal parameters");
+ }
+
+ inBuffer = ByteBuffer.allocateDirect(this.bufferSize);
+ outBuffer = ByteBuffer.allocateDirect(this.bufferSize
+ + cipher.getTransformation().getAlgorithmBlockSize());
+
+ initCipher();
}
- }
-
- /**
- * Overrides the {@link OutputStream#flush()}.
- * To flush, we need to encrypt the data in the buffer and write to the
- * underlying stream, then do the flush.
- *
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public void flush() throws IOException {
- checkStream();
- encrypt();
- output.flush();
- super.flush();
- }
-
- /**
- * Overrides the {@link OutputStream#close()}.
- * Closes this output stream and releases any system resources
- * associated with this stream.
- *
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public void close() throws IOException {
- if (closed) {
- return;
+
+ /**
+ * Overrides the {@link java.io.OutputStream#write(byte[])}. Writes the
+ * specified byte to this output stream.
+ *
+ * @param b the data.
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public void write(int b) throws IOException {
+ oneByteBuf[0] = (byte) (b & 0xff);
+ write(oneByteBuf, 0, oneByteBuf.length);
}
- try {
- encryptFinal();
- output.close();
- freeBuffers();
- cipher.close();
- super.close();
- } finally {
- closed = true;
+ /**
+ * Overrides the {@link java.io.OutputStream#write(byte[], int, int)}.
+ * Encryption is buffer based. If there is enough room in {@link #inBuffer},
+ * then write to this buffer. If {@link #inBuffer} is full, then do
+ * encryption and write data to the underlying stream.
+ *
+ * @param b the data.
+ * @param off the start offset in the data.
+ * @param len the number of bytes to write.
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public void write(byte[] b, int off, int len) throws IOException {
+ checkStream();
+ if (b == null) {
+ throw new NullPointerException();
+ } else if (off < 0 || len < 0 || off > b.length || len > b.length - off) {
+ throw new IndexOutOfBoundsException();
+ }
+
+ while (len > 0) {
+ final int remaining = inBuffer.remaining();
+ if (len < remaining) {
+ inBuffer.put(b, off, len);
+ len = 0;
+ } else {
+ inBuffer.put(b, off, remaining);
+ off += remaining;
+ len -= remaining;
+ encrypt();
+ }
+ }
}
- }
-
- /**
- * Overrides the {@link Channel#isOpen()}.
- * Tells whether or not this channel is open.
- *
- * @return <tt>true</tt> if, and only if, this channel is open
- */
- @Override
- public boolean isOpen() {
- return !closed;
- }
-
- /**
- * Overrides the {@link java.nio.channels.WritableByteChannel#write(ByteBuffer)}.
- * Writes a sequence of bytes to this channel from the given buffer.
- *
- * @param src The buffer from which bytes are to be retrieved.
- * @return The number of bytes written, possibly zero.
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public int write(ByteBuffer src) throws IOException {
- checkStream();
- final int len = src.remaining();
- int remaining = len;
- while (remaining > 0) {
- final int space = inBuffer.remaining();
- if (remaining < space) {
- inBuffer.put(src);
- remaining = 0;
- } else {
- // to void copy twice, we set the limit to copy directly
- final int oldLimit = src.limit();
- final int newLimit = src.position() + space;
- src.limit(newLimit);
-
- inBuffer.put(src);
-
- // restore the old limit
- src.limit(oldLimit);
-
- remaining -= space;
+
+ /**
+ * Overrides the {@link OutputStream#flush()}. To flush, we need to encrypt
+ * the data in the buffer and write to the underlying stream, then do the
+ * flush.
+ *
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public void flush() throws IOException {
+ checkStream();
encrypt();
- }
+ output.flush();
+ super.flush();
+ }
+
+ /**
+ * Overrides the {@link OutputStream#close()}. Closes this output stream and
+ * releases any system resources associated with this stream.
+ *
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public void close() throws IOException {
+ if (closed) {
+ return;
+ }
+
+ try {
+ encryptFinal();
+ output.close();
+ freeBuffers();
+ cipher.close();
+ super.close();
+ } finally {
+ closed = true;
+ }
+ }
+
+ /**
+ * Overrides the {@link Channel#isOpen()}. Tells whether or not this channel
+ * is open.
+ *
+ * @return <tt>true</tt> if, and only if, this channel is open
+ */
+ @Override
+ public boolean isOpen() {
+ return !closed;
+ }
+
+ /**
+ * Overrides the
+ * {@link java.nio.channels.WritableByteChannel#write(ByteBuffer)}. Writes a
+ * sequence of bytes to this channel from the given buffer.
+ *
+ * @param src The buffer from which bytes are to be retrieved.
+ * @return The number of bytes written, possibly zero.
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public int write(ByteBuffer src) throws IOException {
+ checkStream();
+ final int len = src.remaining();
+ int remaining = len;
+ while (remaining > 0) {
+ final int space = inBuffer.remaining();
+ if (remaining < space) {
+ inBuffer.put(src);
+ remaining = 0;
+ } else {
+ // to void copy twice, we set the limit to copy directly
+ final int oldLimit = src.limit();
+ final int newLimit = src.position() + space;
+ src.limit(newLimit);
+
+ inBuffer.put(src);
+
+ // restore the old limit
+ src.limit(oldLimit);
+
+ remaining -= space;
+ encrypt();
+ }
+ }
+
+ return len;
+ }
+
+ /**
+ * Initializes the cipher.
+ *
+ * @throws IOException if an I/O error occurs.
+ */
+ protected void initCipher() throws IOException {
+ try {
+ cipher.init(CryptoCipher.ENCRYPT_MODE, key, params);
+ } catch (InvalidKeyException e) {
+ throw new IOException(e);
+ } catch (InvalidAlgorithmParameterException e) {
+ throw new IOException(e);
+ }
+ }
+
+ /**
+ * Does the encryption, input is {@link #inBuffer} and output is
+ * {@link #outBuffer}.
+ *
+ * @throws IOException if an I/O error occurs.
+ */
+ protected void encrypt() throws IOException {
+
+ inBuffer.flip();
+ outBuffer.clear();
+
+ try {
+ cipher.update(inBuffer, outBuffer);
+ } catch (ShortBufferException e) {
+ throw new IOException(e);
+ }
+
+ inBuffer.clear();
+ outBuffer.flip();
+
+ // write to output
+ output.write(outBuffer);
}
- return len;
- }
-
- /**
- * Initializes the cipher.
- *
- * @throws IOException if an I/O error occurs.
- */
- protected void initCipher()
- throws IOException {
- try {
- cipher.init(CryptoCipher.ENCRYPT_MODE, key, params);
- } catch (InvalidKeyException e) {
- throw new IOException(e);
- } catch(InvalidAlgorithmParameterException e) {
- throw new IOException(e);
+ /**
+ * Does final encryption of the last data.
+ *
+ * @throws IOException if an I/O error occurs.
+ */
+ protected void encryptFinal() throws IOException {
+ inBuffer.flip();
+ outBuffer.clear();
+
+ try {
+ cipher.doFinal(inBuffer, outBuffer);
+ } catch (ShortBufferException e) {
+ throw new IOException(e);
+ } catch (IllegalBlockSizeException e) {
+ throw new IOException(e);
+ } catch (BadPaddingException e) {
+ throw new IOException(e);
+ }
+
+ inBuffer.clear();
+ outBuffer.flip();
+
+ // write to output
+ output.write(outBuffer);
}
- }
-
- /**
- * Does the encryption, input is {@link #inBuffer} and output is
- * {@link #outBuffer}.
- *
- *@throws IOException if an I/O error occurs.
- */
- protected void encrypt() throws IOException {
-
- inBuffer.flip();
- outBuffer.clear();
-
- try {
- cipher.update(inBuffer, outBuffer);
- } catch (ShortBufferException e) {
- throw new IOException(e);
+
+ protected void checkStream() throws IOException {
+ if (closed) {
+ throw new IOException("Stream closed");
+ }
}
- inBuffer.clear();
- outBuffer.flip();
-
- // write to output
- output.write(outBuffer);
- }
-
- /**
- * Does final encryption of the last data.
- *
- * @throws IOException if an I/O error occurs.
- */
- protected void encryptFinal() throws IOException {
- inBuffer.flip();
- outBuffer.clear();
-
- try {
- cipher.doFinal(inBuffer, outBuffer);
- } catch (ShortBufferException e) {
- throw new IOException(e);
- } catch (IllegalBlockSizeException e) {
- throw new IOException(e);
- } catch( BadPaddingException e) {
- throw new IOException(e);
+ /** Forcibly free the direct buffers. */
+ protected void freeBuffers() {
+ Utils.freeDirectBuffer(inBuffer);
+ Utils.freeDirectBuffer(outBuffer);
}
- inBuffer.clear();
- outBuffer.flip();
+ /**
+ * Gets the outBuffer.
+ *
+ * @return the outBuffer.
+ */
+ protected ByteBuffer getOutBuffer() {
+ return outBuffer;
+ }
- // write to output
- output.write(outBuffer);
- }
+ /**
+ * Gets the internal Cipher.
+ *
+ * @return the cipher instance.
+ */
+ protected CryptoCipher getCipher() {
+ return cipher;
+ }
+
+ /**
+ * Gets the buffer size.
+ *
+ * @return the buffer size.
+ */
+ protected int getBufferSize() {
+ return bufferSize;
+ }
- protected void checkStream() throws IOException {
- if (closed) {
- throw new IOException("Stream closed");
+ /**
+ * Gets the inBuffer.
+ *
+ * @return the inBuffer.
+ */
+ protected ByteBuffer getInBuffer() {
+ return inBuffer;
}
- }
-
- /** Forcibly free the direct buffers. */
- protected void freeBuffers() {
- Utils.freeDirectBuffer(inBuffer);
- Utils.freeDirectBuffer(outBuffer);
- }
-
- /**
- * Gets the outBuffer.
- *
- * @return the outBuffer.
- */
- protected ByteBuffer getOutBuffer() {
- return outBuffer;
- }
-
- /**
- * Gets the internal Cipher.
- *
- * @return the cipher instance.
- */
- protected CryptoCipher getCipher() {
- return cipher;
- }
-
- /**
- * Gets the buffer size.
- *
- * @return the buffer size.
- */
- protected int getBufferSize() {
- return bufferSize;
- }
-
- /**
- * Gets the inBuffer.
- *
- * @return the inBuffer.
- */
- protected ByteBuffer getInBuffer() {
- return inBuffer;
- }
}
[2/7] commons-crypto git commit: CRYPTO-37: Change all the 2 spaces
indent to 4 to comply Commons code style
Posted by xu...@apache.org.
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/test/java/org/apache/commons/crypto/cipher/JceCipherTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/crypto/cipher/JceCipherTest.java b/src/test/java/org/apache/commons/crypto/cipher/JceCipherTest.java
index c40aaa1..9a0f9cd 100644
--- a/src/test/java/org/apache/commons/crypto/cipher/JceCipherTest.java
+++ b/src/test/java/org/apache/commons/crypto/cipher/JceCipherTest.java
@@ -20,13 +20,13 @@ package org.apache.commons.crypto.cipher;
public class JceCipherTest extends AbstractCipherTest {
- @Override
- public void init() {
- transformations = new CipherTransformation[]{
- CipherTransformation.AES_CBC_NOPADDING,
- CipherTransformation.AES_CBC_PKCS5PADDING,
- CipherTransformation.AES_CTR_NOPADDING};
- cipherClass = JceCipher.class.getName();
- }
+ @Override
+ public void init() {
+ transformations = new CipherTransformation[] {
+ CipherTransformation.AES_CBC_NOPADDING,
+ CipherTransformation.AES_CBC_PKCS5PADDING,
+ CipherTransformation.AES_CTR_NOPADDING };
+ cipherClass = JceCipher.class.getName();
+ }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/test/java/org/apache/commons/crypto/cipher/OpensslCipherTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/crypto/cipher/OpensslCipherTest.java b/src/test/java/org/apache/commons/crypto/cipher/OpensslCipherTest.java
index 9428e2a..c66936a 100644
--- a/src/test/java/org/apache/commons/crypto/cipher/OpensslCipherTest.java
+++ b/src/test/java/org/apache/commons/crypto/cipher/OpensslCipherTest.java
@@ -31,135 +31,145 @@ import org.junit.Test;
public class OpensslCipherTest extends AbstractCipherTest {
- @Override
- public void init() {
- transformations = new CipherTransformation[]{
- CipherTransformation.AES_CBC_NOPADDING,
- CipherTransformation.AES_CBC_PKCS5PADDING,
- CipherTransformation.AES_CTR_NOPADDING};
- cipherClass = OpensslCipher.class.getName();
- }
-
- @Test(expected = NoSuchAlgorithmException.class, timeout=120000)
- public void testInvalidAlgorithm() throws Exception {
- Assume.assumeTrue(Openssl.getLoadingFailureReason() == null);
-
- try {
- Openssl.getInstance("AES2/CTR/NoPadding");
- Assert.fail("Should specify correct algorithm.");
- } catch (NoSuchAlgorithmException e) {
- Assert.assertTrue(e.getMessage().contains("Doesn't support algorithm: AES2 and mode: CTR"));
- throw e;
+ @Override
+ public void init() {
+ transformations = new CipherTransformation[] {
+ CipherTransformation.AES_CBC_NOPADDING,
+ CipherTransformation.AES_CBC_PKCS5PADDING,
+ CipherTransformation.AES_CTR_NOPADDING };
+ cipherClass = OpensslCipher.class.getName();
}
- }
-
- @Test(expected = NoSuchPaddingException.class, timeout=120000)
- public void testInvalidPadding() throws Exception {
- Assume.assumeTrue(Openssl.getLoadingFailureReason() == null);
-
- try {
- Openssl.getInstance("AES/CTR/NoPadding2");
- Assert.fail("Should specify correct padding.");
- } catch (NoSuchPaddingException e) {
- Assert.assertTrue(e.getMessage().contains("Doesn't support padding: NoPadding2"));
- throw e;
- }
- }
-
- @Test(expected = NoSuchAlgorithmException.class, timeout=120000)
- public void testInvalidMode() throws Exception {
- try {
- Assume.assumeTrue(Openssl.getLoadingFailureReason() == null);
- Openssl.getInstance("AES/CTR2/NoPadding");
- Assert.fail("java.security.NoSuchAlgorithmException should be thrown.");
- } catch (NoSuchAlgorithmException e) {
- Assert.assertTrue(e.getMessage().contains("Doesn't support algorithm: AES and mode: CTR2"));
- throw e;
- }
- }
-
- @Test(timeout=120000)
- public void testUpdateArguments() throws Exception {
- Assume.assumeTrue(Openssl.getLoadingFailureReason() == null);
- Openssl cipher = Openssl.getInstance(CipherTransformation.AES_CTR_NOPADDING.getName());
- Assert.assertNotNull(cipher);
-
- cipher.init(Openssl.ENCRYPT_MODE, KEY, IV);
-
- // Require direct buffers
- ByteBuffer input = ByteBuffer.allocate(1024);
- ByteBuffer output = ByteBuffer.allocate(1024);
- try {
- cipher.update(input, output);
- Assert.fail("Input and output buffer should be direct buffer.");
- } catch (IllegalArgumentException e) {
- Assert.assertTrue(e.getMessage().contains("Direct buffers are required"));
+ @Test(expected = NoSuchAlgorithmException.class, timeout = 120000)
+ public void testInvalidAlgorithm() throws Exception {
+ Assume.assumeTrue(Openssl.getLoadingFailureReason() == null);
+
+ try {
+ Openssl.getInstance("AES2/CTR/NoPadding");
+ Assert.fail("Should specify correct algorithm.");
+ } catch (NoSuchAlgorithmException e) {
+ Assert.assertTrue(e.getMessage().contains(
+ "Doesn't support algorithm: AES2 and mode: CTR"));
+ throw e;
+ }
}
- // Output buffer length should be sufficient to store output data
- input = ByteBuffer.allocateDirect(1024);
- output = ByteBuffer.allocateDirect(1000);
- try {
- cipher.update(input, output);
- Assert.fail("Output buffer length should be sufficient " +
- "to store output data");
- } catch (ShortBufferException e) {
- Assert.assertTrue(e.getMessage().contains("Output buffer is not sufficient"));
+ @Test(expected = NoSuchPaddingException.class, timeout = 120000)
+ public void testInvalidPadding() throws Exception {
+ Assume.assumeTrue(Openssl.getLoadingFailureReason() == null);
+
+ try {
+ Openssl.getInstance("AES/CTR/NoPadding2");
+ Assert.fail("Should specify correct padding.");
+ } catch (NoSuchPaddingException e) {
+ Assert.assertTrue(e.getMessage().contains(
+ "Doesn't support padding: NoPadding2"));
+ throw e;
+ }
}
- }
- @Test(timeout=120000)
- public void testDoFinalArguments() throws Exception {
- Assume.assumeTrue(Openssl.getLoadingFailureReason() == null);
- Openssl cipher = Openssl.getInstance(CipherTransformation.AES_CTR_NOPADDING.getName());
- Assert.assertNotNull(cipher);
-
- cipher.init(Openssl.ENCRYPT_MODE, KEY, IV);
+ @Test(expected = NoSuchAlgorithmException.class, timeout = 120000)
+ public void testInvalidMode() throws Exception {
+ try {
+ Assume.assumeTrue(Openssl.getLoadingFailureReason() == null);
+ Openssl.getInstance("AES/CTR2/NoPadding");
+ Assert.fail("java.security.NoSuchAlgorithmException should be thrown.");
+ } catch (NoSuchAlgorithmException e) {
+ Assert.assertTrue(e.getMessage().contains(
+ "Doesn't support algorithm: AES and mode: CTR2"));
+ throw e;
+ }
+ }
- // Require direct buffer
- ByteBuffer output = ByteBuffer.allocate(1024);
+ @Test(timeout = 120000)
+ public void testUpdateArguments() throws Exception {
+ Assume.assumeTrue(Openssl.getLoadingFailureReason() == null);
+ Openssl cipher = Openssl
+ .getInstance(CipherTransformation.AES_CTR_NOPADDING.getName());
+ Assert.assertNotNull(cipher);
+
+ cipher.init(Openssl.ENCRYPT_MODE, KEY, IV);
+
+ // Require direct buffers
+ ByteBuffer input = ByteBuffer.allocate(1024);
+ ByteBuffer output = ByteBuffer.allocate(1024);
+
+ try {
+ cipher.update(input, output);
+ Assert.fail("Input and output buffer should be direct buffer.");
+ } catch (IllegalArgumentException e) {
+ Assert.assertTrue(e.getMessage().contains(
+ "Direct buffers are required"));
+ }
+
+ // Output buffer length should be sufficient to store output data
+ input = ByteBuffer.allocateDirect(1024);
+ output = ByteBuffer.allocateDirect(1000);
+ try {
+ cipher.update(input, output);
+ Assert.fail("Output buffer length should be sufficient "
+ + "to store output data");
+ } catch (ShortBufferException e) {
+ Assert.assertTrue(e.getMessage().contains(
+ "Output buffer is not sufficient"));
+ }
+ }
- try {
- cipher.doFinal(output);
- Assert.fail("Output buffer should be direct buffer.");
- } catch (IllegalArgumentException e) {
- Assert.assertTrue(e.getMessage().contains("Direct buffer is required"));
+ @Test(timeout = 120000)
+ public void testDoFinalArguments() throws Exception {
+ Assume.assumeTrue(Openssl.getLoadingFailureReason() == null);
+ Openssl cipher = Openssl
+ .getInstance(CipherTransformation.AES_CTR_NOPADDING.getName());
+ Assert.assertNotNull(cipher);
+
+ cipher.init(Openssl.ENCRYPT_MODE, KEY, IV);
+
+ // Require direct buffer
+ ByteBuffer output = ByteBuffer.allocate(1024);
+
+ try {
+ cipher.doFinal(output);
+ Assert.fail("Output buffer should be direct buffer.");
+ } catch (IllegalArgumentException e) {
+ Assert.assertTrue(e.getMessage().contains(
+ "Direct buffer is required"));
+ }
}
- }
-
- @Test(expected = InvalidKeyException.class, timeout=120000)
- public void testInvalidKey() throws Exception {
- Assume.assumeTrue(Openssl.getLoadingFailureReason() == null);
- Openssl cipher = Openssl.getInstance(CipherTransformation.AES_CTR_NOPADDING.getName());
- Assert.assertNotNull(cipher);
-
- final byte[] invalidKey = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
- 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x11};
- try {
- cipher.init(Openssl.ENCRYPT_MODE, invalidKey, IV);
- Assert.fail("java.security.InvalidKeyException should be thrown.");
- } catch (Exception e) {
- Assert.assertTrue(e.getMessage().contains("Invalid key length."));
- throw e;
+
+ @Test(expected = InvalidKeyException.class, timeout = 120000)
+ public void testInvalidKey() throws Exception {
+ Assume.assumeTrue(Openssl.getLoadingFailureReason() == null);
+ Openssl cipher = Openssl
+ .getInstance(CipherTransformation.AES_CTR_NOPADDING.getName());
+ Assert.assertNotNull(cipher);
+
+ final byte[] invalidKey = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
+ 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x11 };
+ try {
+ cipher.init(Openssl.ENCRYPT_MODE, invalidKey, IV);
+ Assert.fail("java.security.InvalidKeyException should be thrown.");
+ } catch (Exception e) {
+ Assert.assertTrue(e.getMessage().contains("Invalid key length."));
+ throw e;
+ }
}
- }
-
- @Test(expected = InvalidAlgorithmParameterException.class, timeout=120000)
- public void testInvalidIV() throws Exception {
- Assume.assumeTrue(Openssl.getLoadingFailureReason() == null);
- Openssl cipher = Openssl.getInstance(CipherTransformation.AES_CTR_NOPADDING.getName());
- Assert.assertNotNull(cipher);
-
- final byte[] invalidIV = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
- 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x11};
- try {
- cipher.init(Openssl.ENCRYPT_MODE, KEY, invalidIV);
- Assert.fail("java.security.InvalidAlgorithmParameterException should be thrown.");
- } catch (Exception e) {
- Assert.assertTrue(e.getMessage().contains("Wrong IV length."));
- throw e;
+
+ @Test(expected = InvalidAlgorithmParameterException.class, timeout = 120000)
+ public void testInvalidIV() throws Exception {
+ Assume.assumeTrue(Openssl.getLoadingFailureReason() == null);
+ Openssl cipher = Openssl
+ .getInstance(CipherTransformation.AES_CTR_NOPADDING.getName());
+ Assert.assertNotNull(cipher);
+
+ final byte[] invalidIV = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
+ 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x11 };
+ try {
+ cipher.init(Openssl.ENCRYPT_MODE, KEY, invalidIV);
+ Assert.fail("java.security.InvalidAlgorithmParameterException should be thrown.");
+ } catch (Exception e) {
+ Assert.assertTrue(e.getMessage().contains("Wrong IV length."));
+ throw e;
+ }
}
- }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/test/java/org/apache/commons/crypto/cipher/TestData.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/crypto/cipher/TestData.java b/src/test/java/org/apache/commons/crypto/cipher/TestData.java
index 2f8da8f..d67414e 100644
--- a/src/test/java/org/apache/commons/crypto/cipher/TestData.java
+++ b/src/test/java/org/apache/commons/crypto/cipher/TestData.java
@@ -22,135 +22,126 @@ import java.util.Map;
public class TestData {
- private static String[] CBCNoPaddingTests = {
- /*
- * key_len,key,iv,plainText,cipherText
- */
- "128",
- "2b7e151628aed2a6abf7158809cf4f3c",
- "000102030405060708090a0b0c0d0e0f",
- "6bc1bee22e409f96e93d7e117393172a",
- "7649abac8119b246cee98e9b12e9197d",
-
- "128",
- "2b7e151628aed2a6abf7158809cf4f3c",
- "7649ABAC8119B246CEE98E9B12E9197D",
- "ae2d8a571e03ac9c9eb76fac45af8e51",
- "5086cb9b507219ee95db113a917678b2",
-
- "192",
- "603deb1015ca71be2b73aef0857d77811f352c073b6108d7",
- "9CFC4E967EDB808D679F777BC6702C7D",
- "30c81c46a35ce411e5fbc1191a0a52ef",
- "78C57E3F543A18F472756DAC2F018523",
-
- "192",
- "603deb1015ca71be2b73aef0857d77811f352c073b6108d7",
- "39F23369A9D9BACFA530E26304231461",
- "f69f2445df4f9b17ad2b417be66c3710",
- "79ECA9610F0B9AAFB8C7C2D655047A41",
-
- "256",
- "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
- "000102030405060708090a0b0c0d0e0f",
- "6bc1bee22e409f96e93d7e117393172a",
- "f58c4c04d6e5f1ba779eabfb5f7bfbd6",
-
- "256",
- "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
- "F58C4C04D6E5F1BA779EABFB5F7BFBD6",
- "ae2d8a571e03ac9c9eb76fac45af8e51",
- "9cfc4e967edb808d679f777bc6702c7d"
- };
-
- private static String[] CBCPKCS5PaddingTests = {
- /*
- * key_len,key,iv,plainText,cipherText
- */
- //Test#0 for input of 6 bytes
- "128",
- "ac5800ac3cb59c7c14f36019e43b44fe",
- "f013ce1ec901b5b60a85a986b3b72eba",
- "f6cee5ff28fd",
- "e8a846fd9718507371604504d4ca1ac7",
-
- //Test#0 for input of 15 bytes
- "128",
- "0784fa652e733cb699f250b0df2c4b41",
- "106519760fb3ef97e1ccea073b27122d",
- "6842455a2992c2e5193056a5524075",
- "56a8e0c3ee3315f913693c0ca781e917",
-
- //Test#0 for input of 16 bytes
- "128",
- "04952c3fcf497a4d449c41e8730c5d9a",
- "53549bf7d5553b727458c1abaf0ba167",
- "c9a44f6f75e98ddbca7332167f5c45e3",
- "7fa290322ca7a1a04b61a1147ff20fe66fde58510a1d0289d11c0ddf6f4decfd",
-
- //Test#0 for input of 32 bytes
- "128",
- "2ae7081caebe54909820620a44a60a0f",
- "fc5e783fbe7be12f58b1f025d82ada50",
- "1ba93ee6f83752df47909585b3f28e56693f89e169d3093eee85175ea3a46cd3",
- "7944957a99e473e2c07eb496a83ec4e55db2fb44ebdd42bb611e0def29b23a73ac37eb0f4f5d86f090f3ddce3980425a",
-
- //Test#0 for input of 33 bytes
- "128",
- "898be9cc5004ed0fa6e117c9a3099d31",
- "9dea7621945988f96491083849b068df",
- "0397f4f6820b1f9386f14403be5ac16e50213bd473b4874b9bcbf5f318ee686b1d",
- "e232cd6ef50047801ee681ec30f61d53cfd6b0bca02fd03c1b234baa10ea82ac9dab8b960926433a19ce6dea08677e34"};
-
- private static String[] cipherCTRTests = {
- /*
- * key_len,key,iv,plainText,cipherText
- */
- "128",
- "2b7e151628aed2a6abf7158809cf4f3c",
- "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
- "6bc1bee22e409f96e93d7e117393172a",
- "874d6191b620e3261bef6864990db6ce",
-
- "128",
- "2b7e151628aed2a6abf7158809cf4f3c",
- "f0f1f2f3f4f5f6f7f8f9fafbfcfdff00",
- "ae2d8a571e03ac9c9eb76fac45af8e51",
- "9806f66b7970fdff8617187bb9fffdff",
-
- //Test for input of 15 bytes
- "128",
- "2b7e151628aed2a6abf7158809cf4f3c",
- "f0f1f2f3f4f5f6f7f8f9fafbfcfdff01",
- "30c81c46a35ce411e5fbc1191a0a52",
- "5ae4df3edbd5d35e5b4f09020db03e",
-
- "256",
- "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
- "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
- "6bc1bee22e409f96e93d7e117393172a",
- "601ec313775789a5b7a7f504bbf3d228",
-
- "256",
- "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
- "f0f1f2f3f4f5f6f7f8f9fafbfcfdff00",
- "ae2d8a571e03ac9c9eb76fac45af8e51",
- "f443e3ca4d62b59aca84e990cacaf5c5",
-
- //Test for input of 15 bytes
- "256",
- "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
- "f0f1f2f3f4f5f6f7f8f9fafbfcfdff01",
- "30c81c46a35ce411e5fbc1191a0a52",
- "2b0930daa23de94ce87017ba2d8498" };
-
- private static Map<CipherTransformation, String[]> testData =
- new HashMap<CipherTransformation, String[]>();
+ private static String[] CBCNoPaddingTests = {
+ /*
+ * key_len,key,iv,plainText,cipherText
+ */
+ "128", "2b7e151628aed2a6abf7158809cf4f3c",
+ "000102030405060708090a0b0c0d0e0f",
+ "6bc1bee22e409f96e93d7e117393172a",
+ "7649abac8119b246cee98e9b12e9197d",
+
+ "128", "2b7e151628aed2a6abf7158809cf4f3c",
+ "7649ABAC8119B246CEE98E9B12E9197D",
+ "ae2d8a571e03ac9c9eb76fac45af8e51",
+ "5086cb9b507219ee95db113a917678b2",
+
+ "192", "603deb1015ca71be2b73aef0857d77811f352c073b6108d7",
+ "9CFC4E967EDB808D679F777BC6702C7D",
+ "30c81c46a35ce411e5fbc1191a0a52ef",
+ "78C57E3F543A18F472756DAC2F018523",
+
+ "192", "603deb1015ca71be2b73aef0857d77811f352c073b6108d7",
+ "39F23369A9D9BACFA530E26304231461",
+ "f69f2445df4f9b17ad2b417be66c3710",
+ "79ECA9610F0B9AAFB8C7C2D655047A41",
+
+ "256",
+ "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
+ "000102030405060708090a0b0c0d0e0f",
+ "6bc1bee22e409f96e93d7e117393172a",
+ "f58c4c04d6e5f1ba779eabfb5f7bfbd6",
+
+ "256",
+ "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
+ "F58C4C04D6E5F1BA779EABFB5F7BFBD6",
+ "ae2d8a571e03ac9c9eb76fac45af8e51",
+ "9cfc4e967edb808d679f777bc6702c7d" };
+
+ private static String[] CBCPKCS5PaddingTests = {
+ /*
+ * key_len,key,iv,plainText,cipherText
+ */
+ // Test#0 for input of 6 bytes
+ "128",
+ "ac5800ac3cb59c7c14f36019e43b44fe",
+ "f013ce1ec901b5b60a85a986b3b72eba",
+ "f6cee5ff28fd",
+ "e8a846fd9718507371604504d4ca1ac7",
+
+ // Test#0 for input of 15 bytes
+ "128",
+ "0784fa652e733cb699f250b0df2c4b41",
+ "106519760fb3ef97e1ccea073b27122d",
+ "6842455a2992c2e5193056a5524075",
+ "56a8e0c3ee3315f913693c0ca781e917",
+
+ // Test#0 for input of 16 bytes
+ "128",
+ "04952c3fcf497a4d449c41e8730c5d9a",
+ "53549bf7d5553b727458c1abaf0ba167",
+ "c9a44f6f75e98ddbca7332167f5c45e3",
+ "7fa290322ca7a1a04b61a1147ff20fe66fde58510a1d0289d11c0ddf6f4decfd",
+
+ // Test#0 for input of 32 bytes
+ "128",
+ "2ae7081caebe54909820620a44a60a0f",
+ "fc5e783fbe7be12f58b1f025d82ada50",
+ "1ba93ee6f83752df47909585b3f28e56693f89e169d3093eee85175ea3a46cd3",
+ "7944957a99e473e2c07eb496a83ec4e55db2fb44ebdd42bb611e0def29b23a73ac37eb0f4f5d86f090f3ddce3980425a",
+
+ // Test#0 for input of 33 bytes
+ "128",
+ "898be9cc5004ed0fa6e117c9a3099d31",
+ "9dea7621945988f96491083849b068df",
+ "0397f4f6820b1f9386f14403be5ac16e50213bd473b4874b9bcbf5f318ee686b1d",
+ "e232cd6ef50047801ee681ec30f61d53cfd6b0bca02fd03c1b234baa10ea82ac9dab8b960926433a19ce6dea08677e34" };
+
+ private static String[] cipherCTRTests = {
+ /*
+ * key_len,key,iv,plainText,cipherText
+ */
+ "128",
+ "2b7e151628aed2a6abf7158809cf4f3c",
+ "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
+ "6bc1bee22e409f96e93d7e117393172a",
+ "874d6191b620e3261bef6864990db6ce",
+
+ "128",
+ "2b7e151628aed2a6abf7158809cf4f3c",
+ "f0f1f2f3f4f5f6f7f8f9fafbfcfdff00",
+ "ae2d8a571e03ac9c9eb76fac45af8e51",
+ "9806f66b7970fdff8617187bb9fffdff",
+
+ // Test for input of 15 bytes
+ "128", "2b7e151628aed2a6abf7158809cf4f3c",
+ "f0f1f2f3f4f5f6f7f8f9fafbfcfdff01",
+ "30c81c46a35ce411e5fbc1191a0a52", "5ae4df3edbd5d35e5b4f09020db03e",
+
+ "256",
+ "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
+ "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
+ "6bc1bee22e409f96e93d7e117393172a",
+ "601ec313775789a5b7a7f504bbf3d228",
+
+ "256",
+ "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
+ "f0f1f2f3f4f5f6f7f8f9fafbfcfdff00",
+ "ae2d8a571e03ac9c9eb76fac45af8e51",
+ "f443e3ca4d62b59aca84e990cacaf5c5",
+
+ // Test for input of 15 bytes
+ "256",
+ "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
+ "f0f1f2f3f4f5f6f7f8f9fafbfcfdff01",
+ "30c81c46a35ce411e5fbc1191a0a52", "2b0930daa23de94ce87017ba2d8498" };
+
+ private static Map<CipherTransformation, String[]> testData = new HashMap<CipherTransformation, String[]>();
static {
testData.put(CipherTransformation.AES_CBC_NOPADDING, CBCNoPaddingTests);
testData.put(CipherTransformation.AES_CBC_PKCS5PADDING,
- CBCPKCS5PaddingTests);
+ CBCPKCS5PaddingTests);
testData.put(CipherTransformation.AES_CTR_NOPADDING, cipherCTRTests);
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/test/java/org/apache/commons/crypto/random/AbstractRandomTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/crypto/random/AbstractRandomTest.java b/src/test/java/org/apache/commons/crypto/random/AbstractRandomTest.java
index 1d1db88..2ccd163 100644
--- a/src/test/java/org/apache/commons/crypto/random/AbstractRandomTest.java
+++ b/src/test/java/org/apache/commons/crypto/random/AbstractRandomTest.java
@@ -24,34 +24,35 @@ import org.junit.Test;
public abstract class AbstractRandomTest {
- public abstract CryptoRandom getCryptoRandom() throws GeneralSecurityException;
+ public abstract CryptoRandom getCryptoRandom()
+ throws GeneralSecurityException;
- @Test(timeout=120000)
- public void testRandomBytes() throws Exception {
- CryptoRandom random = getCryptoRandom();
- // len = 16
- checkRandomBytes(random, 16);
- // len = 32
- checkRandomBytes(random, 32);
- // len = 128
- checkRandomBytes(random, 128);
- // len = 256
- checkRandomBytes(random, 256);
- random.close();
- }
+ @Test(timeout = 120000)
+ public void testRandomBytes() throws Exception {
+ CryptoRandom random = getCryptoRandom();
+ // len = 16
+ checkRandomBytes(random, 16);
+ // len = 32
+ checkRandomBytes(random, 32);
+ // len = 128
+ checkRandomBytes(random, 128);
+ // len = 256
+ checkRandomBytes(random, 256);
+ random.close();
+ }
- /**
- * Test will timeout if secure random implementation always returns a
- * constant value.
- */
- private void checkRandomBytes(CryptoRandom random, int len) {
- byte[] bytes = new byte[len];
- byte[] bytes1 = new byte[len];
- random.nextBytes(bytes);
- random.nextBytes(bytes1);
+ /**
+ * Test will timeout if secure random implementation always returns a
+ * constant value.
+ */
+ private void checkRandomBytes(CryptoRandom random, int len) {
+ byte[] bytes = new byte[len];
+ byte[] bytes1 = new byte[len];
+ random.nextBytes(bytes);
+ random.nextBytes(bytes1);
- while (Arrays.equals(bytes, bytes1)) {
- random.nextBytes(bytes1);
+ while (Arrays.equals(bytes, bytes1)) {
+ random.nextBytes(bytes1);
+ }
}
- }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/test/java/org/apache/commons/crypto/random/TestJavaCryptoRandom.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/crypto/random/TestJavaCryptoRandom.java b/src/test/java/org/apache/commons/crypto/random/TestJavaCryptoRandom.java
index bb84bc7..b9642ab 100644
--- a/src/test/java/org/apache/commons/crypto/random/TestJavaCryptoRandom.java
+++ b/src/test/java/org/apache/commons/crypto/random/TestJavaCryptoRandom.java
@@ -25,16 +25,18 @@ import static junit.framework.Assert.fail;
public class TestJavaCryptoRandom extends AbstractRandomTest {
- @Override
- public CryptoRandom getCryptoRandom() throws GeneralSecurityException {
- Properties props = new Properties();
- props.setProperty(ConfigurationKeys.COMMONS_CRYPTO_SECURE_RANDOM_CLASSES_KEY,
- JavaCryptoRandom.class.getName());
- CryptoRandom random = CryptoRandomFactory.getCryptoRandom(props);
- if ( !(random instanceof JavaCryptoRandom)) {
- fail("The CryptoRandom should be: " + JavaCryptoRandom.class.getName());
+ @Override
+ public CryptoRandom getCryptoRandom() throws GeneralSecurityException {
+ Properties props = new Properties();
+ props.setProperty(
+ ConfigurationKeys.COMMONS_CRYPTO_SECURE_RANDOM_CLASSES_KEY,
+ JavaCryptoRandom.class.getName());
+ CryptoRandom random = CryptoRandomFactory.getCryptoRandom(props);
+ if (!(random instanceof JavaCryptoRandom)) {
+ fail("The CryptoRandom should be: "
+ + JavaCryptoRandom.class.getName());
+ }
+ return random;
}
- return random;
- }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/test/java/org/apache/commons/crypto/random/TestOpensslCryptoRandom.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/crypto/random/TestOpensslCryptoRandom.java b/src/test/java/org/apache/commons/crypto/random/TestOpensslCryptoRandom.java
index fede249..0a6600a 100644
--- a/src/test/java/org/apache/commons/crypto/random/TestOpensslCryptoRandom.java
+++ b/src/test/java/org/apache/commons/crypto/random/TestOpensslCryptoRandom.java
@@ -25,16 +25,18 @@ import static junit.framework.Assert.fail;
public class TestOpensslCryptoRandom extends AbstractRandomTest {
- @Override
- public CryptoRandom getCryptoRandom() throws GeneralSecurityException {
- Properties props = new Properties();
- props.setProperty(ConfigurationKeys.COMMONS_CRYPTO_SECURE_RANDOM_CLASSES_KEY,
- OpensslCryptoRandom.class.getName());
- CryptoRandom random = CryptoRandomFactory.getCryptoRandom(props);
- if ( !(random instanceof OpensslCryptoRandom)) {
- fail("The CryptoRandom should be: " + OpensslCryptoRandom.class.getName());
+ @Override
+ public CryptoRandom getCryptoRandom() throws GeneralSecurityException {
+ Properties props = new Properties();
+ props.setProperty(
+ ConfigurationKeys.COMMONS_CRYPTO_SECURE_RANDOM_CLASSES_KEY,
+ OpensslCryptoRandom.class.getName());
+ CryptoRandom random = CryptoRandomFactory.getCryptoRandom(props);
+ if (!(random instanceof OpensslCryptoRandom)) {
+ fail("The CryptoRandom should be: "
+ + OpensslCryptoRandom.class.getName());
+ }
+ return random;
}
- return random;
- }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/test/java/org/apache/commons/crypto/random/TestOsCryptoRandom.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/crypto/random/TestOsCryptoRandom.java b/src/test/java/org/apache/commons/crypto/random/TestOsCryptoRandom.java
index 9968c34..9f0b149 100644
--- a/src/test/java/org/apache/commons/crypto/random/TestOsCryptoRandom.java
+++ b/src/test/java/org/apache/commons/crypto/random/TestOsCryptoRandom.java
@@ -19,10 +19,10 @@ package org.apache.commons.crypto.random;
import java.util.Properties;
-public class TestOsCryptoRandom extends AbstractRandomTest{
+public class TestOsCryptoRandom extends AbstractRandomTest {
- @Override
- public CryptoRandom getCryptoRandom() {
- return new OsCryptoRandom(new Properties());
- }
+ @Override
+ public CryptoRandom getCryptoRandom() {
+ return new OsCryptoRandom(new Properties());
+ }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/test/java/org/apache/commons/crypto/stream/AbstractCipherStreamTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/crypto/stream/AbstractCipherStreamTest.java b/src/test/java/org/apache/commons/crypto/stream/AbstractCipherStreamTest.java
index a89e4d1..feb318d 100644
--- a/src/test/java/org/apache/commons/crypto/stream/AbstractCipherStreamTest.java
+++ b/src/test/java/org/apache/commons/crypto/stream/AbstractCipherStreamTest.java
@@ -44,416 +44,424 @@ import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public abstract class AbstractCipherStreamTest {
- private static final Log LOG= LogFactory.getLog(AbstractCipherStreamTest.class);
-
- private final int dataLen = 20000;
- private byte[] data = new byte[dataLen];
- private byte[] encData;
- private Properties props = new Properties();
- protected byte[] key = new byte[16];
- private byte[] iv = new byte[16];
- private int count = 10000;
- protected static int defaultBufferSize = 8192;
- protected static int smallBufferSize = 1024;
-
- private final String jceCipherClass = JceCipher.class.getName();
- private final String opensslCipherClass = OpensslCipher.class.getName();
- protected CipherTransformation transformation;
-
- public abstract void setUp() throws IOException;
-
- @Before
- public void before() throws IOException {
- Random random = new SecureRandom();
- random.nextBytes(data);
- random.nextBytes(key);
- random.nextBytes(iv);
- setUp();
- prepareData();
- }
-
- /** Test skip. */
- @Test(timeout=120000)
- public void testSkip() throws Exception {
- doSkipTest(jceCipherClass, false);
- doSkipTest(opensslCipherClass, false);
-
- doSkipTest(jceCipherClass, true);
- doSkipTest(opensslCipherClass, true);
- }
-
- /** Test byte buffer read with different buffer size. */
- @Test(timeout=120000)
- public void testByteBufferRead() throws Exception {
- doByteBufferRead(jceCipherClass, false);
- doByteBufferRead(opensslCipherClass, false);
-
- doByteBufferRead(jceCipherClass, true);
- doByteBufferRead(opensslCipherClass, true);
- }
-
- /** Test byte buffer write. */
- @Test(timeout=120000)
- public void testByteBufferWrite() throws Exception {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- doByteBufferWrite(jceCipherClass, baos, false);
- doByteBufferWrite(opensslCipherClass, baos, false);
-
- doByteBufferWrite(jceCipherClass, baos, true);
- doByteBufferWrite(opensslCipherClass, baos, true);
- }
-
- private void doSkipTest(String cipherClass, boolean withChannel) throws IOException {
- InputStream in = getCryptoInputStream(new ByteArrayInputStream(encData),
- getCipher(cipherClass), defaultBufferSize, iv, withChannel);
- byte[] result = new byte[dataLen];
- int n1 = readAll(in, result, 0, dataLen / 3);
-
- long skipped = in.skip(dataLen / 3);
- int n2 = readAll(in, result, 0, dataLen);
-
- Assert.assertEquals(dataLen, n1 + skipped + n2);
- byte[] readData = new byte[n2];
- System.arraycopy(result, 0, readData, 0, n2);
- byte[] expectedData = new byte[n2];
- System.arraycopy(data, dataLen - n2, expectedData, 0, n2);
- Assert.assertArrayEquals(readData, expectedData);
-
- try {
- skipped = in.skip(-3);
- Assert.fail("Skip Negative length should fail.");
- } catch (IllegalArgumentException e) {
- Assert.assertTrue(e.getMessage().contains("Negative skip length"));
+ private static final Log LOG = LogFactory
+ .getLog(AbstractCipherStreamTest.class);
+
+ private final int dataLen = 20000;
+ private byte[] data = new byte[dataLen];
+ private byte[] encData;
+ private Properties props = new Properties();
+ protected byte[] key = new byte[16];
+ private byte[] iv = new byte[16];
+ private int count = 10000;
+ protected static int defaultBufferSize = 8192;
+ protected static int smallBufferSize = 1024;
+
+ private final String jceCipherClass = JceCipher.class.getName();
+ private final String opensslCipherClass = OpensslCipher.class.getName();
+ protected CipherTransformation transformation;
+
+ public abstract void setUp() throws IOException;
+
+ @Before
+ public void before() throws IOException {
+ Random random = new SecureRandom();
+ random.nextBytes(data);
+ random.nextBytes(key);
+ random.nextBytes(iv);
+ setUp();
+ prepareData();
}
- // Skip after EOF
- skipped = in.skip(3);
- Assert.assertEquals(skipped, 0);
-
- in.close();
- }
-
- private void doByteBufferRead(String cipherClass, boolean withChannel) throws Exception {
- // Default buffer size, initial buffer position is 0
- InputStream in = getCryptoInputStream(new ByteArrayInputStream(encData),
- getCipher(cipherClass), defaultBufferSize, iv, withChannel);
- ByteBuffer buf = ByteBuffer.allocate(dataLen + 100);
- byteBufferReadCheck(in, buf, 0);
- in.close();
-
- // Default buffer size, initial buffer position is not 0
- in = getCryptoInputStream(new ByteArrayInputStream(encData),
- getCipher(cipherClass), defaultBufferSize, iv, withChannel);
- buf.clear();
- byteBufferReadCheck(in, buf, 11);
- in.close();
-
- // Small buffer size, initial buffer position is 0
- in = getCryptoInputStream(new ByteArrayInputStream(encData),
- getCipher(cipherClass), smallBufferSize, iv, withChannel);
- buf.clear();
- byteBufferReadCheck(in, buf, 0);
- in.close();
-
- // Small buffer size, initial buffer position is not 0
- in = getCryptoInputStream(new ByteArrayInputStream(encData),
- getCipher(cipherClass), smallBufferSize, iv, withChannel);
- buf.clear();
- byteBufferReadCheck(in, buf, 11);
- in.close();
-
- // Direct buffer, default buffer size, initial buffer position is 0
- in = getCryptoInputStream(new ByteArrayInputStream(encData),
- getCipher(cipherClass), defaultBufferSize, iv, withChannel);
- buf = ByteBuffer.allocateDirect(dataLen + 100);
- byteBufferReadCheck(in, buf, 0);
- in.close();
-
- // Direct buffer, default buffer size, initial buffer position is not 0
- in = getCryptoInputStream(new ByteArrayInputStream(encData),
- getCipher(cipherClass), defaultBufferSize, iv, withChannel);
- buf.clear();
- byteBufferReadCheck(in, buf, 11);
- in.close();
-
- // Direct buffer, small buffer size, initial buffer position is 0
- in = getCryptoInputStream(new ByteArrayInputStream(encData),
- getCipher(cipherClass), smallBufferSize, iv, withChannel);
- buf.clear();
- byteBufferReadCheck(in, buf, 0);
- in.close();
-
- // Direct buffer, small buffer size, initial buffer position is not 0
- in = getCryptoInputStream(new ByteArrayInputStream(encData),
- getCipher(cipherClass), smallBufferSize, iv, withChannel);
- buf.clear();
- byteBufferReadCheck(in, buf, 11);
- in.close();
- }
-
- private void doByteBufferWrite(String cipherClass, ByteArrayOutputStream baos,
- boolean withChannel)
- throws Exception {
- baos.reset();
- CryptoOutputStream out =
- getCryptoOutputStream(baos, getCipher(cipherClass), defaultBufferSize,
- iv, withChannel);
- ByteBuffer buf = ByteBuffer.allocateDirect(dataLen / 2);
- buf.put(data, 0, dataLen / 2);
- buf.flip();
- int n1 = out.write(buf);
-
- buf.clear();
- buf.put(data, n1, dataLen / 3);
- buf.flip();
- int n2 = out.write(buf);
-
- buf.clear();
- buf.put(data, n1 + n2, dataLen - n1 - n2);
- buf.flip();
- int n3 = out.write(buf);
-
- Assert.assertEquals(dataLen, n1 + n2 + n3);
-
- out.flush();
-
- InputStream in = getCryptoInputStream(new ByteArrayInputStream(encData),
- getCipher(cipherClass), defaultBufferSize, iv, withChannel);
- buf = ByteBuffer.allocate(dataLen + 100);
- byteBufferReadCheck(in, buf, 0);
- in.close();
- }
-
- private void byteBufferReadCheck(InputStream in, ByteBuffer buf,
- int bufPos) throws Exception {
- buf.position(bufPos);
- int n = ((ReadableByteChannel) in).read(buf);
- Assert.assertEquals(bufPos + n, buf.position());
- byte[] readData = new byte[n];
- buf.rewind();
- buf.position(bufPos);
- buf.get(readData);
- byte[] expectedData = new byte[n];
- System.arraycopy(data, 0, expectedData, 0, n);
- Assert.assertArrayEquals(readData, expectedData);
- }
-
- private void prepareData() throws IOException {
- CryptoCipher cipher = null;
- try {
- cipher = (CryptoCipher)ReflectionUtils.newInstance(
- ReflectionUtils.getClassByName(jceCipherClass), props, transformation);
- } catch (ClassNotFoundException cnfe) {
- throw new IOException("Illegal crypto cipher!");
+ /** Test skip. */
+ @Test(timeout = 120000)
+ public void testSkip() throws Exception {
+ doSkipTest(jceCipherClass, false);
+ doSkipTest(opensslCipherClass, false);
+
+ doSkipTest(jceCipherClass, true);
+ doSkipTest(opensslCipherClass, true);
+ }
+
+ /** Test byte buffer read with different buffer size. */
+ @Test(timeout = 120000)
+ public void testByteBufferRead() throws Exception {
+ doByteBufferRead(jceCipherClass, false);
+ doByteBufferRead(opensslCipherClass, false);
+
+ doByteBufferRead(jceCipherClass, true);
+ doByteBufferRead(opensslCipherClass, true);
+ }
+
+ /** Test byte buffer write. */
+ @Test(timeout = 120000)
+ public void testByteBufferWrite() throws Exception {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ doByteBufferWrite(jceCipherClass, baos, false);
+ doByteBufferWrite(opensslCipherClass, baos, false);
+
+ doByteBufferWrite(jceCipherClass, baos, true);
+ doByteBufferWrite(opensslCipherClass, baos, true);
+ }
+
+ private void doSkipTest(String cipherClass, boolean withChannel)
+ throws IOException {
+ InputStream in = getCryptoInputStream(
+ new ByteArrayInputStream(encData), getCipher(cipherClass),
+ defaultBufferSize, iv, withChannel);
+ byte[] result = new byte[dataLen];
+ int n1 = readAll(in, result, 0, dataLen / 3);
+
+ long skipped = in.skip(dataLen / 3);
+ int n2 = readAll(in, result, 0, dataLen);
+
+ Assert.assertEquals(dataLen, n1 + skipped + n2);
+ byte[] readData = new byte[n2];
+ System.arraycopy(result, 0, readData, 0, n2);
+ byte[] expectedData = new byte[n2];
+ System.arraycopy(data, dataLen - n2, expectedData, 0, n2);
+ Assert.assertArrayEquals(readData, expectedData);
+
+ try {
+ skipped = in.skip(-3);
+ Assert.fail("Skip Negative length should fail.");
+ } catch (IllegalArgumentException e) {
+ Assert.assertTrue(e.getMessage().contains("Negative skip length"));
+ }
+
+ // Skip after EOF
+ skipped = in.skip(3);
+ Assert.assertEquals(skipped, 0);
+
+ in.close();
}
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- OutputStream out = new CryptoOutputStream(baos, cipher, defaultBufferSize,
- new SecretKeySpec(key,"AES"), new IvParameterSpec(iv));
- out.write(data);
- out.flush();
- out.close();
- encData = baos.toByteArray();
- }
-
- protected CryptoInputStream getCryptoInputStream(ByteArrayInputStream bais,
- CryptoCipher cipher,
- int bufferSize, byte[] iv,
- boolean withChannel) throws
- IOException {
- if (withChannel) {
- return new CryptoInputStream(Channels.newChannel(bais), cipher,
- bufferSize, new SecretKeySpec(key,"AES"), new IvParameterSpec(iv));
- } else {
- return new CryptoInputStream(bais, cipher, bufferSize,
- new SecretKeySpec(key,"AES"), new IvParameterSpec(iv));
+ private void doByteBufferRead(String cipherClass, boolean withChannel)
+ throws Exception {
+ // Default buffer size, initial buffer position is 0
+ InputStream in = getCryptoInputStream(
+ new ByteArrayInputStream(encData), getCipher(cipherClass),
+ defaultBufferSize, iv, withChannel);
+ ByteBuffer buf = ByteBuffer.allocate(dataLen + 100);
+ byteBufferReadCheck(in, buf, 0);
+ in.close();
+
+ // Default buffer size, initial buffer position is not 0
+ in = getCryptoInputStream(new ByteArrayInputStream(encData),
+ getCipher(cipherClass), defaultBufferSize, iv, withChannel);
+ buf.clear();
+ byteBufferReadCheck(in, buf, 11);
+ in.close();
+
+ // Small buffer size, initial buffer position is 0
+ in = getCryptoInputStream(new ByteArrayInputStream(encData),
+ getCipher(cipherClass), smallBufferSize, iv, withChannel);
+ buf.clear();
+ byteBufferReadCheck(in, buf, 0);
+ in.close();
+
+ // Small buffer size, initial buffer position is not 0
+ in = getCryptoInputStream(new ByteArrayInputStream(encData),
+ getCipher(cipherClass), smallBufferSize, iv, withChannel);
+ buf.clear();
+ byteBufferReadCheck(in, buf, 11);
+ in.close();
+
+ // Direct buffer, default buffer size, initial buffer position is 0
+ in = getCryptoInputStream(new ByteArrayInputStream(encData),
+ getCipher(cipherClass), defaultBufferSize, iv, withChannel);
+ buf = ByteBuffer.allocateDirect(dataLen + 100);
+ byteBufferReadCheck(in, buf, 0);
+ in.close();
+
+ // Direct buffer, default buffer size, initial buffer position is not 0
+ in = getCryptoInputStream(new ByteArrayInputStream(encData),
+ getCipher(cipherClass), defaultBufferSize, iv, withChannel);
+ buf.clear();
+ byteBufferReadCheck(in, buf, 11);
+ in.close();
+
+ // Direct buffer, small buffer size, initial buffer position is 0
+ in = getCryptoInputStream(new ByteArrayInputStream(encData),
+ getCipher(cipherClass), smallBufferSize, iv, withChannel);
+ buf.clear();
+ byteBufferReadCheck(in, buf, 0);
+ in.close();
+
+ // Direct buffer, small buffer size, initial buffer position is not 0
+ in = getCryptoInputStream(new ByteArrayInputStream(encData),
+ getCipher(cipherClass), smallBufferSize, iv, withChannel);
+ buf.clear();
+ byteBufferReadCheck(in, buf, 11);
+ in.close();
}
- }
-
- protected CryptoOutputStream getCryptoOutputStream(ByteArrayOutputStream baos,
- CryptoCipher cipher,
- int bufferSize, byte[] iv,
- boolean withChannel) throws
- IOException {
- if (withChannel) {
- return new CryptoOutputStream(Channels.newChannel(baos), cipher,
- bufferSize, new SecretKeySpec(key,"AES"), new IvParameterSpec(iv));
- } else {
- return new CryptoOutputStream(baos, cipher, bufferSize,
- new SecretKeySpec(key,"AES"), new IvParameterSpec(iv));
+
+ private void doByteBufferWrite(String cipherClass,
+ ByteArrayOutputStream baos, boolean withChannel) throws Exception {
+ baos.reset();
+ CryptoOutputStream out = getCryptoOutputStream(baos,
+ getCipher(cipherClass), defaultBufferSize, iv, withChannel);
+ ByteBuffer buf = ByteBuffer.allocateDirect(dataLen / 2);
+ buf.put(data, 0, dataLen / 2);
+ buf.flip();
+ int n1 = out.write(buf);
+
+ buf.clear();
+ buf.put(data, n1, dataLen / 3);
+ buf.flip();
+ int n2 = out.write(buf);
+
+ buf.clear();
+ buf.put(data, n1 + n2, dataLen - n1 - n2);
+ buf.flip();
+ int n3 = out.write(buf);
+
+ Assert.assertEquals(dataLen, n1 + n2 + n3);
+
+ out.flush();
+
+ InputStream in = getCryptoInputStream(
+ new ByteArrayInputStream(encData), getCipher(cipherClass),
+ defaultBufferSize, iv, withChannel);
+ buf = ByteBuffer.allocate(dataLen + 100);
+ byteBufferReadCheck(in, buf, 0);
+ in.close();
}
- }
-
- private int readAll(InputStream in, byte[] b, int offset, int len)
- throws IOException {
- int n = 0;
- int total = 0;
- while (n != -1) {
- total += n;
- if (total >= len) {
- break;
- }
- n = in.read(b, offset + total, len - total);
+
+ private void byteBufferReadCheck(InputStream in, ByteBuffer buf, int bufPos)
+ throws Exception {
+ buf.position(bufPos);
+ int n = ((ReadableByteChannel) in).read(buf);
+ Assert.assertEquals(bufPos + n, buf.position());
+ byte[] readData = new byte[n];
+ buf.rewind();
+ buf.position(bufPos);
+ buf.get(readData);
+ byte[] expectedData = new byte[n];
+ System.arraycopy(data, 0, expectedData, 0, n);
+ Assert.assertArrayEquals(readData, expectedData);
}
- return total;
- }
+ private void prepareData() throws IOException {
+ CryptoCipher cipher = null;
+ try {
+ cipher = (CryptoCipher) ReflectionUtils.newInstance(
+ ReflectionUtils.getClassByName(jceCipherClass), props,
+ transformation);
+ } catch (ClassNotFoundException cnfe) {
+ throw new IOException("Illegal crypto cipher!");
+ }
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ OutputStream out = new CryptoOutputStream(baos, cipher,
+ defaultBufferSize, new SecretKeySpec(key, "AES"),
+ new IvParameterSpec(iv));
+ out.write(data);
+ out.flush();
+ out.close();
+ encData = baos.toByteArray();
+ }
- protected CryptoCipher getCipher(String cipherClass) throws IOException {
- try {
- return (CryptoCipher)ReflectionUtils.newInstance(
- ReflectionUtils.getClassByName(cipherClass), props, transformation);
- } catch (ClassNotFoundException cnfe) {
- throw new IOException("Illegal crypto cipher!");
+ protected CryptoInputStream getCryptoInputStream(ByteArrayInputStream bais,
+ CryptoCipher cipher, int bufferSize, byte[] iv, boolean withChannel)
+ throws IOException {
+ if (withChannel) {
+ return new CryptoInputStream(Channels.newChannel(bais), cipher,
+ bufferSize, new SecretKeySpec(key, "AES"),
+ new IvParameterSpec(iv));
+ } else {
+ return new CryptoInputStream(bais, cipher, bufferSize,
+ new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));
+ }
}
- }
-
- @Test
- public void testReadWrite() throws Exception {
- Assert.assertEquals(null, Openssl.getLoadingFailureReason());
- doReadWriteTest(0, jceCipherClass, jceCipherClass, iv);
- doReadWriteTest(0, opensslCipherClass, opensslCipherClass, iv);
- doReadWriteTest(count, jceCipherClass, jceCipherClass, iv);
- doReadWriteTest(count, opensslCipherClass, opensslCipherClass, iv);
- doReadWriteTest(count, jceCipherClass, opensslCipherClass, iv);
- doReadWriteTest(count, opensslCipherClass, jceCipherClass, iv);
- // Overflow test, IV: xx xx xx xx xx xx xx xx ff ff ff ff ff ff ff ff
- for(int i = 0; i < 8; i++) {
- iv[8 + i] = (byte) 0xff;
+
+ protected CryptoOutputStream getCryptoOutputStream(
+ ByteArrayOutputStream baos, CryptoCipher cipher, int bufferSize,
+ byte[] iv, boolean withChannel) throws IOException {
+ if (withChannel) {
+ return new CryptoOutputStream(Channels.newChannel(baos), cipher,
+ bufferSize, new SecretKeySpec(key, "AES"),
+ new IvParameterSpec(iv));
+ } else {
+ return new CryptoOutputStream(baos, cipher, bufferSize,
+ new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));
+ }
}
- doReadWriteTest(count, jceCipherClass, jceCipherClass, iv);
- doReadWriteTest(count, opensslCipherClass, opensslCipherClass, iv);
- doReadWriteTest(count, jceCipherClass, opensslCipherClass, iv);
- doReadWriteTest(count, opensslCipherClass, jceCipherClass, iv);
- }
-
- private void doReadWriteTest(int count, String encCipherClass,
- String decCipherClass, byte[] iv) throws IOException {
- doReadWriteTestForInputStream(count, encCipherClass, decCipherClass, iv);
- doReadWriteTestForReadableByteChannel(count, encCipherClass, decCipherClass,
- iv);
- }
-
- private void doReadWriteTestForInputStream(int count, String encCipherClass,
- String decCipherClass, byte[] iv) throws IOException {
- CryptoCipher encCipher = getCipher(encCipherClass);
- LOG.debug("Created a cipher object of type: " + encCipherClass);
-
- // Generate data
- SecureRandom random = new SecureRandom();
- byte[] originalData = new byte[count];
- byte[] decryptedData = new byte[count];
- random.nextBytes(originalData);
- LOG.debug("Generated " + count + " records");
-
- // Encrypt data
- ByteArrayOutputStream encryptedData = new ByteArrayOutputStream();
- CryptoOutputStream out =
- getCryptoOutputStream(encryptedData, encCipher, defaultBufferSize, iv,
- false);
- out.write(originalData, 0, originalData.length);
- out.flush();
- out.close();
- LOG.debug("Finished encrypting data");
-
- CryptoCipher decCipher = getCipher(decCipherClass);
- LOG.debug("Created a cipher object of type: " + decCipherClass);
-
- // Decrypt data
- CryptoInputStream in = getCryptoInputStream(
- new ByteArrayInputStream(encryptedData.toByteArray()), decCipher,
- defaultBufferSize, iv, false);
-
- // Check
- int remainingToRead = count;
- int offset = 0;
- while (remainingToRead > 0) {
- int n = in.read(decryptedData, offset, decryptedData.length - offset);
- if (n >=0) {
- remainingToRead -= n;
- offset += n;
- }
+
+ private int readAll(InputStream in, byte[] b, int offset, int len)
+ throws IOException {
+ int n = 0;
+ int total = 0;
+ while (n != -1) {
+ total += n;
+ if (total >= len) {
+ break;
+ }
+ n = in.read(b, offset + total, len - total);
+ }
+
+ return total;
}
- Assert.assertArrayEquals("originalData and decryptedData not equal",
- originalData, decryptedData);
-
- // Decrypt data byte-at-a-time
- in = getCryptoInputStream(
- new ByteArrayInputStream(encryptedData.toByteArray()), decCipher,
- defaultBufferSize, iv, false);
-
- // Check
- DataInputStream originalIn = new DataInputStream(new BufferedInputStream(new ByteArrayInputStream(originalData)));
- int expected;
- do {
- expected = originalIn.read();
- Assert.assertEquals("Decrypted stream read by byte does not match",
- expected, in.read());
- } while (expected != -1);
-
- LOG.debug("SUCCESS! Completed checking " + count + " records");
- }
-
- private void doReadWriteTestForReadableByteChannel(int count,
- String encCipherClass,
- String decCipherClass,
- byte[] iv) throws IOException {
- CryptoCipher encCipher = getCipher(encCipherClass);
- LOG.debug("Created a cipher object of type: " + encCipherClass);
-
- // Generate data
- SecureRandom random = new SecureRandom();
- byte[] originalData = new byte[count];
- byte[] decryptedData = new byte[count];
- random.nextBytes(originalData);
- LOG.debug("Generated " + count + " records");
-
- // Encrypt data
- ByteArrayOutputStream encryptedData = new ByteArrayOutputStream();
- CryptoOutputStream out =
- getCryptoOutputStream(encryptedData, encCipher, defaultBufferSize, iv,
- true);
- out.write(originalData, 0, originalData.length);
- out.flush();
- out.close();
- LOG.debug("Finished encrypting data");
-
- CryptoCipher decCipher = getCipher(decCipherClass);
- LOG.debug("Created a cipher object of type: " + decCipherClass);
-
- // Decrypt data
- CryptoInputStream in = getCryptoInputStream(
- new ByteArrayInputStream(encryptedData.toByteArray()), decCipher,
- defaultBufferSize, iv, true);
-
- // Check
- int remainingToRead = count;
- int offset = 0;
- while (remainingToRead > 0) {
- int n = in.read(decryptedData, offset, decryptedData.length - offset);
- if (n >=0) {
- remainingToRead -= n;
- offset += n;
- }
+ protected CryptoCipher getCipher(String cipherClass) throws IOException {
+ try {
+ return (CryptoCipher) ReflectionUtils.newInstance(
+ ReflectionUtils.getClassByName(cipherClass), props,
+ transformation);
+ } catch (ClassNotFoundException cnfe) {
+ throw new IOException("Illegal crypto cipher!");
+ }
}
- Assert.assertArrayEquals("originalData and decryptedData not equal",
- originalData, decryptedData);
+ @Test
+ public void testReadWrite() throws Exception {
+ Assert.assertEquals(null, Openssl.getLoadingFailureReason());
+ doReadWriteTest(0, jceCipherClass, jceCipherClass, iv);
+ doReadWriteTest(0, opensslCipherClass, opensslCipherClass, iv);
+ doReadWriteTest(count, jceCipherClass, jceCipherClass, iv);
+ doReadWriteTest(count, opensslCipherClass, opensslCipherClass, iv);
+ doReadWriteTest(count, jceCipherClass, opensslCipherClass, iv);
+ doReadWriteTest(count, opensslCipherClass, jceCipherClass, iv);
+ // Overflow test, IV: xx xx xx xx xx xx xx xx ff ff ff ff ff ff ff ff
+ for (int i = 0; i < 8; i++) {
+ iv[8 + i] = (byte) 0xff;
+ }
+ doReadWriteTest(count, jceCipherClass, jceCipherClass, iv);
+ doReadWriteTest(count, opensslCipherClass, opensslCipherClass, iv);
+ doReadWriteTest(count, jceCipherClass, opensslCipherClass, iv);
+ doReadWriteTest(count, opensslCipherClass, jceCipherClass, iv);
+ }
- // Decrypt data byte-at-a-time
- in = getCryptoInputStream(new ByteArrayInputStream(
- encryptedData.toByteArray()),decCipher,defaultBufferSize,iv,true);
+ private void doReadWriteTest(int count, String encCipherClass,
+ String decCipherClass, byte[] iv) throws IOException {
+ doReadWriteTestForInputStream(count, encCipherClass, decCipherClass, iv);
+ doReadWriteTestForReadableByteChannel(count, encCipherClass,
+ decCipherClass, iv);
+ }
- // Check
- DataInputStream originalIn = new DataInputStream(new BufferedInputStream(new ByteArrayInputStream(originalData)));
- int expected;
- do {
- expected = originalIn.read();
- Assert.assertEquals("Decrypted stream read by byte does not match",
- expected, in.read());
- } while (expected != -1);
+ private void doReadWriteTestForInputStream(int count,
+ String encCipherClass, String decCipherClass, byte[] iv)
+ throws IOException {
+ CryptoCipher encCipher = getCipher(encCipherClass);
+ LOG.debug("Created a cipher object of type: " + encCipherClass);
+
+ // Generate data
+ SecureRandom random = new SecureRandom();
+ byte[] originalData = new byte[count];
+ byte[] decryptedData = new byte[count];
+ random.nextBytes(originalData);
+ LOG.debug("Generated " + count + " records");
+
+ // Encrypt data
+ ByteArrayOutputStream encryptedData = new ByteArrayOutputStream();
+ CryptoOutputStream out = getCryptoOutputStream(encryptedData,
+ encCipher, defaultBufferSize, iv, false);
+ out.write(originalData, 0, originalData.length);
+ out.flush();
+ out.close();
+ LOG.debug("Finished encrypting data");
+
+ CryptoCipher decCipher = getCipher(decCipherClass);
+ LOG.debug("Created a cipher object of type: " + decCipherClass);
+
+ // Decrypt data
+ CryptoInputStream in = getCryptoInputStream(new ByteArrayInputStream(
+ encryptedData.toByteArray()), decCipher, defaultBufferSize, iv,
+ false);
+
+ // Check
+ int remainingToRead = count;
+ int offset = 0;
+ while (remainingToRead > 0) {
+ int n = in.read(decryptedData, offset, decryptedData.length
+ - offset);
+ if (n >= 0) {
+ remainingToRead -= n;
+ offset += n;
+ }
+ }
+
+ Assert.assertArrayEquals("originalData and decryptedData not equal",
+ originalData, decryptedData);
+
+ // Decrypt data byte-at-a-time
+ in = getCryptoInputStream(
+ new ByteArrayInputStream(encryptedData.toByteArray()),
+ decCipher, defaultBufferSize, iv, false);
+
+ // Check
+ DataInputStream originalIn = new DataInputStream(
+ new BufferedInputStream(new ByteArrayInputStream(originalData)));
+ int expected;
+ do {
+ expected = originalIn.read();
+ Assert.assertEquals("Decrypted stream read by byte does not match",
+ expected, in.read());
+ } while (expected != -1);
+
+ LOG.debug("SUCCESS! Completed checking " + count + " records");
+ }
- LOG.debug("SUCCESS! Completed checking " + count + " records");
- }
+ private void doReadWriteTestForReadableByteChannel(int count,
+ String encCipherClass, String decCipherClass, byte[] iv)
+ throws IOException {
+ CryptoCipher encCipher = getCipher(encCipherClass);
+ LOG.debug("Created a cipher object of type: " + encCipherClass);
+
+ // Generate data
+ SecureRandom random = new SecureRandom();
+ byte[] originalData = new byte[count];
+ byte[] decryptedData = new byte[count];
+ random.nextBytes(originalData);
+ LOG.debug("Generated " + count + " records");
+
+ // Encrypt data
+ ByteArrayOutputStream encryptedData = new ByteArrayOutputStream();
+ CryptoOutputStream out = getCryptoOutputStream(encryptedData,
+ encCipher, defaultBufferSize, iv, true);
+ out.write(originalData, 0, originalData.length);
+ out.flush();
+ out.close();
+ LOG.debug("Finished encrypting data");
+
+ CryptoCipher decCipher = getCipher(decCipherClass);
+ LOG.debug("Created a cipher object of type: " + decCipherClass);
+
+ // Decrypt data
+ CryptoInputStream in = getCryptoInputStream(new ByteArrayInputStream(
+ encryptedData.toByteArray()), decCipher, defaultBufferSize, iv,
+ true);
+
+ // Check
+ int remainingToRead = count;
+ int offset = 0;
+ while (remainingToRead > 0) {
+ int n = in.read(decryptedData, offset, decryptedData.length
+ - offset);
+ if (n >= 0) {
+ remainingToRead -= n;
+ offset += n;
+ }
+ }
+
+ Assert.assertArrayEquals("originalData and decryptedData not equal",
+ originalData, decryptedData);
+
+ // Decrypt data byte-at-a-time
+ in = getCryptoInputStream(
+ new ByteArrayInputStream(encryptedData.toByteArray()),
+ decCipher, defaultBufferSize, iv, true);
+
+ // Check
+ DataInputStream originalIn = new DataInputStream(
+ new BufferedInputStream(new ByteArrayInputStream(originalData)));
+ int expected;
+ do {
+ expected = originalIn.read();
+ Assert.assertEquals("Decrypted stream read by byte does not match",
+ expected, in.read());
+ } while (expected != -1);
+
+ LOG.debug("SUCCESS! Completed checking " + count + " records");
+ }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/test/java/org/apache/commons/crypto/stream/CBCNoPaddingCipherStreamTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/crypto/stream/CBCNoPaddingCipherStreamTest.java b/src/test/java/org/apache/commons/crypto/stream/CBCNoPaddingCipherStreamTest.java
index 3b4c66e..fcf569d 100644
--- a/src/test/java/org/apache/commons/crypto/stream/CBCNoPaddingCipherStreamTest.java
+++ b/src/test/java/org/apache/commons/crypto/stream/CBCNoPaddingCipherStreamTest.java
@@ -23,10 +23,9 @@ import org.apache.commons.crypto.cipher.CipherTransformation;
public class CBCNoPaddingCipherStreamTest extends AbstractCipherStreamTest {
- @Override
-public void setUp() throws IOException {
- transformation = CipherTransformation
- .AES_CBC_NOPADDING;
- }
+ @Override
+ public void setUp() throws IOException {
+ transformation = CipherTransformation.AES_CBC_NOPADDING;
+ }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/test/java/org/apache/commons/crypto/stream/CBCPKCS5PaddingCipherStreamTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/crypto/stream/CBCPKCS5PaddingCipherStreamTest.java b/src/test/java/org/apache/commons/crypto/stream/CBCPKCS5PaddingCipherStreamTest.java
index c605a3b..830b970 100644
--- a/src/test/java/org/apache/commons/crypto/stream/CBCPKCS5PaddingCipherStreamTest.java
+++ b/src/test/java/org/apache/commons/crypto/stream/CBCPKCS5PaddingCipherStreamTest.java
@@ -23,9 +23,8 @@ import org.apache.commons.crypto.cipher.CipherTransformation;
public class CBCPKCS5PaddingCipherStreamTest extends AbstractCipherStreamTest {
- @Override
-public void setUp() throws IOException {
- transformation = CipherTransformation
- .AES_CBC_PKCS5PADDING;
- }
+ @Override
+ public void setUp() throws IOException {
+ transformation = CipherTransformation.AES_CBC_PKCS5PADDING;
+ }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/test/java/org/apache/commons/crypto/stream/CTRCryptoStreamTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/crypto/stream/CTRCryptoStreamTest.java b/src/test/java/org/apache/commons/crypto/stream/CTRCryptoStreamTest.java
index 0953196..ad8220b 100644
--- a/src/test/java/org/apache/commons/crypto/stream/CTRCryptoStreamTest.java
+++ b/src/test/java/org/apache/commons/crypto/stream/CTRCryptoStreamTest.java
@@ -27,33 +27,32 @@ import org.apache.commons.crypto.cipher.CipherTransformation;
public class CTRCryptoStreamTest extends AbstractCipherStreamTest {
- @Override
-public void setUp() throws IOException {
- transformation = CipherTransformation
- .AES_CTR_NOPADDING;
- }
+ @Override
+ public void setUp() throws IOException {
+ transformation = CipherTransformation.AES_CTR_NOPADDING;
+ }
- @Override
- protected CTRCryptoInputStream getCryptoInputStream
- (ByteArrayInputStream bais, CryptoCipher cipher, int
- bufferSize, byte[] iv, boolean withChannel)
- throws IOException {
- if (withChannel) {
- return new CTRCryptoInputStream(Channels.newChannel(bais), cipher,
- bufferSize, key, iv);
- } else {
- return new CTRCryptoInputStream(bais, cipher, bufferSize, key, iv);
+ @Override
+ protected CTRCryptoInputStream getCryptoInputStream(
+ ByteArrayInputStream bais, CryptoCipher cipher, int bufferSize,
+ byte[] iv, boolean withChannel) throws IOException {
+ if (withChannel) {
+ return new CTRCryptoInputStream(Channels.newChannel(bais), cipher,
+ bufferSize, key, iv);
+ } else {
+ return new CTRCryptoInputStream(bais, cipher, bufferSize, key, iv);
+ }
}
- }
- @Override
- protected CTRCryptoOutputStream getCryptoOutputStream(ByteArrayOutputStream baos, CryptoCipher cipher,
- int bufferSize, byte[] iv, boolean withChannel)
- throws IOException {
- if (withChannel) {
- return new CTRCryptoOutputStream(Channels.newChannel(baos), cipher, bufferSize, key, iv);
- } else {
- return new CTRCryptoOutputStream(baos, cipher, bufferSize, key, iv);
+ @Override
+ protected CTRCryptoOutputStream getCryptoOutputStream(
+ ByteArrayOutputStream baos, CryptoCipher cipher, int bufferSize,
+ byte[] iv, boolean withChannel) throws IOException {
+ if (withChannel) {
+ return new CTRCryptoOutputStream(Channels.newChannel(baos), cipher,
+ bufferSize, key, iv);
+ } else {
+ return new CTRCryptoOutputStream(baos, cipher, bufferSize, key, iv);
+ }
}
- }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/test/java/org/apache/commons/crypto/stream/CTRNoPaddingCipherStreamTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/crypto/stream/CTRNoPaddingCipherStreamTest.java b/src/test/java/org/apache/commons/crypto/stream/CTRNoPaddingCipherStreamTest.java
index dc9907f..2638a39 100644
--- a/src/test/java/org/apache/commons/crypto/stream/CTRNoPaddingCipherStreamTest.java
+++ b/src/test/java/org/apache/commons/crypto/stream/CTRNoPaddingCipherStreamTest.java
@@ -23,10 +23,9 @@ import org.apache.commons.crypto.cipher.CipherTransformation;
public class CTRNoPaddingCipherStreamTest extends AbstractCipherStreamTest {
- @Override
-public void setUp() throws IOException {
- transformation = CipherTransformation
- .AES_CTR_NOPADDING;
- }
+ @Override
+ public void setUp() throws IOException {
+ transformation = CipherTransformation.AES_CTR_NOPADDING;
+ }
}
[7/7] commons-crypto git commit: CRYPTO-37: Change all the 2 spaces
indent to 4 to comply Commons code style
Posted by xu...@apache.org.
CRYPTO-37: Change all the 2 spaces indent to 4 to comply Commons code style
Project: http://git-wip-us.apache.org/repos/asf/commons-crypto/repo
Commit: http://git-wip-us.apache.org/repos/asf/commons-crypto/commit/95a8d486
Tree: http://git-wip-us.apache.org/repos/asf/commons-crypto/tree/95a8d486
Diff: http://git-wip-us.apache.org/repos/asf/commons-crypto/diff/95a8d486
Branch: refs/heads/master
Commit: 95a8d486eac81fbb84a42df35d5c00fe6d6dace8
Parents: e2cc6ae
Author: Ferdinand Xu <ch...@intel.com>
Authored: Wed May 4 04:05:27 2016 +0800
Committer: Ferdinand Xu <ch...@intel.com>
Committed: Wed May 4 04:14:45 2016 +0800
----------------------------------------------------------------------
.../crypto/cipher/CipherTransformation.java | 131 +-
.../commons/crypto/cipher/CryptoCipher.java | 225 ++--
.../crypto/cipher/CryptoCipherFactory.java | 129 +-
.../apache/commons/crypto/cipher/JceCipher.java | 310 ++---
.../apache/commons/crypto/cipher/Openssl.java | 530 ++++-----
.../commons/crypto/cipher/OpensslCipher.java | 336 +++---
.../commons/crypto/cipher/OpensslNative.java | 181 +--
.../commons/crypto/cipher/package-info.java | 1 +
.../commons/crypto/conf/ConfigurationKeys.java | 216 ++--
.../commons/crypto/conf/package-info.java | 1 +
.../commons/crypto/random/CryptoRandom.java | 16 +-
.../crypto/random/CryptoRandomFactory.java | 79 +-
.../commons/crypto/random/JavaCryptoRandom.java | 71 +-
.../crypto/random/OpensslCryptoRandom.java | 188 +--
.../random/OpensslCryptoRandomNative.java | 34 +-
.../commons/crypto/random/OsCryptoRandom.java | 172 +--
.../commons/crypto/random/package-info.java | 1 +
.../crypto/stream/CTRCryptoInputStream.java | 1115 +++++++++---------
.../crypto/stream/CTRCryptoOutputStream.java | 607 +++++-----
.../crypto/stream/CryptoInputStream.java | 977 +++++++--------
.../crypto/stream/CryptoOutputStream.java | 740 ++++++------
.../stream/PositionedCryptoInputStream.java | 582 ++++-----
.../crypto/stream/input/ChannelInput.java | 253 ++--
.../commons/crypto/stream/input/Input.java | 208 ++--
.../crypto/stream/input/StreamInput.java | 245 ++--
.../crypto/stream/input/package-info.java | 1 +
.../crypto/stream/output/ChannelOutput.java | 93 +-
.../commons/crypto/stream/output/Output.java | 95 +-
.../crypto/stream/output/StreamOutput.java | 127 +-
.../crypto/stream/output/package-info.java | 1 +
.../commons/crypto/stream/package-info.java | 1 +
.../apache/commons/crypto/utils/IOUtils.java | 123 +-
.../commons/crypto/utils/NativeCodeLoader.java | 432 ++++---
.../org/apache/commons/crypto/utils/OSInfo.java | 332 +++---
.../commons/crypto/utils/ReflectionUtils.java | 334 +++---
.../org/apache/commons/crypto/utils/Utils.java | 582 ++++-----
.../commons/crypto/utils/package-info.java | 1 +
.../crypto/cipher/AbstractCipherTest.java | 394 ++++---
.../crypto/cipher/CryptoCipherFactoryTest.java | 52 +-
.../commons/crypto/cipher/JceCipherTest.java | 16 +-
.../crypto/cipher/OpensslCipherTest.java | 248 ++--
.../apache/commons/crypto/cipher/TestData.java | 241 ++--
.../crypto/random/AbstractRandomTest.java | 53 +-
.../crypto/random/TestJavaCryptoRandom.java | 22 +-
.../crypto/random/TestOpensslCryptoRandom.java | 22 +-
.../crypto/random/TestOsCryptoRandom.java | 10 +-
.../crypto/stream/AbstractCipherStreamTest.java | 796 ++++++-------
.../stream/CBCNoPaddingCipherStreamTest.java | 9 +-
.../stream/CBCPKCS5PaddingCipherStreamTest.java | 9 +-
.../crypto/stream/CTRCryptoStreamTest.java | 49 +-
.../stream/CTRNoPaddingCipherStreamTest.java | 9 +-
.../stream/PositionedCryptoInputStreamTest.java | 630 +++++-----
.../apache/commons/crypto/utils/UtilsTest.java | 22 +-
53 files changed, 6076 insertions(+), 5976 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/cipher/CipherTransformation.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/cipher/CipherTransformation.java b/src/main/java/org/apache/commons/crypto/cipher/CipherTransformation.java
index 72f2f4d..9a6a358 100644
--- a/src/main/java/org/apache/commons/crypto/cipher/CipherTransformation.java
+++ b/src/main/java/org/apache/commons/crypto/cipher/CipherTransformation.java
@@ -18,78 +18,81 @@
package org.apache.commons.crypto.cipher;
/**
- * Defines properties of a CipherTransformation. Modeled after the ciphers in Cipher.
+ * Defines properties of a CipherTransformation. Modeled after the ciphers in
+ * Cipher.
*/
public enum CipherTransformation {
- /** A crypto transformation representing AES/CTR/NoPadding */
- AES_CTR_NOPADDING("AES/CTR/NoPadding", 16),
- /** A crypto transformation representing AES/CBC/NoPadding */
- AES_CBC_NOPADDING("AES/CBC/NoPadding", 16),
- /** A crypto transformation representing AES/CBC/PKCS5Padding */
- AES_CBC_PKCS5PADDING("AES/CBC/PKCS5Padding", 16);
+ /** A crypto transformation representing AES/CTR/NoPadding */
+ AES_CTR_NOPADDING("AES/CTR/NoPadding", 16),
+ /** A crypto transformation representing AES/CBC/NoPadding */
+ AES_CBC_NOPADDING("AES/CBC/NoPadding", 16),
+ /** A crypto transformation representing AES/CBC/PKCS5Padding */
+ AES_CBC_PKCS5PADDING("AES/CBC/PKCS5Padding", 16);
- private final String name;
- private final int algorithmBlockSize;
+ private final String name;
+ private final int algorithmBlockSize;
- /**
- * Constructor for CipherTransformation. Initalizes the cipher with algorithm
- * name and block size of the algorithm.
- *
- * @param name the name of cipher algorithm
- * @param algorithmBlockSize the blockSize of cipher algorithm
- */
- CipherTransformation(String name, int algorithmBlockSize) {
- this.name = name;
- this.algorithmBlockSize = algorithmBlockSize;
- }
+ /**
+ * Constructor for CipherTransformation. Initalizes the cipher with
+ * algorithm name and block size of the algorithm.
+ *
+ * @param name the name of cipher algorithm
+ * @param algorithmBlockSize the blockSize of cipher algorithm
+ */
+ CipherTransformation(String name, int algorithmBlockSize) {
+ this.name = name;
+ this.algorithmBlockSize = algorithmBlockSize;
+ }
- /**
- * Gets the algorithm name of cipher.
- *
- * @return name of cipher transformation, as in Cipher
- */
- public String getName() {
- return name;
- }
+ /**
+ * Gets the algorithm name of cipher.
+ *
+ * @return name of cipher transformation, as in Cipher
+ */
+ public String getName() {
+ return name;
+ }
- /**
- * Gets the algorithm block size of cipher.
- *
- * @return size of an algorithm block in bytes.
- */
- public int getAlgorithmBlockSize() {
- return algorithmBlockSize;
- }
+ /**
+ * Gets the algorithm block size of cipher.
+ *
+ * @return size of an algorithm block in bytes.
+ */
+ public int getAlgorithmBlockSize() {
+ return algorithmBlockSize;
+ }
- /**
- * Overrides {@link java.lang.Enum#toString()}
- *
- * @return the name of cipher algorithm and blocksize.
- */
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder("{");
- builder.append("name: " + name);
- builder.append(", algorithmBlockSize: " + algorithmBlockSize);
- builder.append("}");
- return builder.toString();
- }
+ /**
+ * Overrides {@link java.lang.Enum#toString()}
+ *
+ * @return the name of cipher algorithm and blocksize.
+ */
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder("{");
+ builder.append("name: " + name);
+ builder.append(", algorithmBlockSize: " + algorithmBlockSize);
+ builder.append("}");
+ return builder.toString();
+ }
- /**
- * Converts to CipherTransformation from name, {@link #algorithmBlockSize}
- * is fixed for certain cipher transformation, just need to compare the name.
- *
- * @param name cipher transformation name
- * @return CipherTransformation cipher transformation
- */
- public static CipherTransformation fromName(String name) {
- CipherTransformation[] transformations = CipherTransformation.values();
- for (CipherTransformation transformation : transformations) {
- if (transformation.getName().equals(name)) {
- return transformation;
- }
+ /**
+ * Converts to CipherTransformation from name, {@link #algorithmBlockSize}
+ * is fixed for certain cipher transformation, just need to compare the
+ * name.
+ *
+ * @param name cipher transformation name
+ * @return CipherTransformation cipher transformation
+ */
+ public static CipherTransformation fromName(String name) {
+ CipherTransformation[] transformations = CipherTransformation.values();
+ for (CipherTransformation transformation : transformations) {
+ if (transformation.getName().equals(name)) {
+ return transformation;
+ }
+ }
+ throw new IllegalArgumentException("Invalid transformation name: "
+ + name);
}
- throw new IllegalArgumentException("Invalid transformation name: " + name);
- }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/cipher/CryptoCipher.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/cipher/CryptoCipher.java b/src/main/java/org/apache/commons/crypto/cipher/CryptoCipher.java
index 41c764a..9781ab2 100644
--- a/src/main/java/org/apache/commons/crypto/cipher/CryptoCipher.java
+++ b/src/main/java/org/apache/commons/crypto/cipher/CryptoCipher.java
@@ -35,124 +35,125 @@ import javax.crypto.ShortBufferException;
*/
public interface CryptoCipher extends Closeable {
- /**
- * A constant representing encrypt mode. The mode constant to be used
- * when calling init method of the CryptoCipher.
- */
- int ENCRYPT_MODE = Cipher.ENCRYPT_MODE;
+ /**
+ * A constant representing encrypt mode. The mode constant to be used when
+ * calling init method of the CryptoCipher.
+ */
+ int ENCRYPT_MODE = Cipher.ENCRYPT_MODE;
- /**
- * A constant representing decrypt mode. The mode constant to be used
- * when calling init method of the CryptoCipher.
- */
- int DECRYPT_MODE = Cipher.DECRYPT_MODE;
+ /**
+ * A constant representing decrypt mode. The mode constant to be used when
+ * calling init method of the CryptoCipher.
+ */
+ int DECRYPT_MODE = Cipher.DECRYPT_MODE;
- /**
- * Gets the CipherTransformation for this cipher.
- *
- * @return the CipherTransformation for this cipher.
- */
- CipherTransformation getTransformation();
+ /**
+ * Gets the CipherTransformation for this cipher.
+ *
+ * @return the CipherTransformation for this cipher.
+ */
+ CipherTransformation getTransformation();
- /**
- * Gets the properties for this cipher.
- *
- * @return the properties for this cipher.
- */
- Properties getProperties();
+ /**
+ * Gets the properties for this cipher.
+ *
+ * @return the properties for this cipher.
+ */
+ Properties getProperties();
- /**
- * Initializes the cipher with mode, key and iv.
- *
- * @param mode {@link #ENCRYPT_MODE} or {@link #DECRYPT_MODE}
- * @param key crypto key for the cipher
- * @param params the algorithm parameters
- * @throws InvalidKeyException if the given key is inappropriate for
- * initializing this cipher, or its keysize exceeds the maximum allowable
- * keysize (as determined from the configured jurisdiction policy files).
- * @throws InvalidAlgorithmParameterException if the given algorithm
- * parameters are inappropriate for this cipher, or this cipher requires
- * algorithm parameters and <code>params</code> is null, or the given
- * algorithm parameters imply a cryptographic strength that would exceed
- * the legal limits (as determined from the configured jurisdiction
- * policy files).
- */
- void init(int mode, Key key, AlgorithmParameterSpec params)
- throws InvalidKeyException, InvalidAlgorithmParameterException;
+ /**
+ * Initializes the cipher with mode, key and iv.
+ *
+ * @param mode {@link #ENCRYPT_MODE} or {@link #DECRYPT_MODE}
+ * @param key crypto key for the cipher
+ * @param params the algorithm parameters
+ * @throws InvalidKeyException if the given key is inappropriate for
+ * initializing this cipher, or its keysize exceeds the maximum
+ * allowable keysize (as determined from the configured jurisdiction
+ * policy files).
+ * @throws InvalidAlgorithmParameterException if the given algorithm
+ * parameters are inappropriate for this cipher, or this cipher
+ * requires algorithm parameters and <code>params</code> is null, or
+ * the given algorithm parameters imply a cryptographic strength
+ * that would exceed the legal limits (as determined from the
+ * configured jurisdiction policy files).
+ */
+ void init(int mode, Key key, AlgorithmParameterSpec params)
+ throws InvalidKeyException, InvalidAlgorithmParameterException;
- /**
- * Continues a multiple-part encryption/decryption operation. The data
- * is encrypted or decrypted, depending on how this cipher was initialized.
- *
- * @param inBuffer the input ByteBuffer
- * @param outBuffer the output ByteBuffer
- * @return int number of bytes stored in <code>output</code>
- * @throws ShortBufferException if there is insufficient space
- * in the output buffer
- */
- int update(ByteBuffer inBuffer, ByteBuffer outBuffer)
- throws ShortBufferException;
+ /**
+ * Continues a multiple-part encryption/decryption operation. The data is
+ * encrypted or decrypted, depending on how this cipher was initialized.
+ *
+ * @param inBuffer the input ByteBuffer
+ * @param outBuffer the output ByteBuffer
+ * @return int number of bytes stored in <code>output</code>
+ * @throws ShortBufferException if there is insufficient space in the output
+ * buffer
+ */
+ int update(ByteBuffer inBuffer, ByteBuffer outBuffer)
+ throws ShortBufferException;
- /**
- * Continues a multiple-part encryption/decryption operation. The data
- * is encrypted or decrypted, depending on how this cipher was initialized.
- *
- * @param input the input byte array
- * @param inputOffset the offset in input where the input starts
- * @param inputLen the input length
- * @param output the byte array for the result
- * @param outputOffset the offset in output where the result is stored
- * @return the number of bytes stored in output
- * @throws ShortBufferException if there is insufficient space in the output byte array
- */
- int update(byte[] input, int inputOffset, int inputLen,
- byte[] output, int outputOffset)
- throws ShortBufferException;
+ /**
+ * Continues a multiple-part encryption/decryption operation. The data is
+ * encrypted or decrypted, depending on how this cipher was initialized.
+ *
+ * @param input the input byte array
+ * @param inputOffset the offset in input where the input starts
+ * @param inputLen the input length
+ * @param output the byte array for the result
+ * @param outputOffset the offset in output where the result is stored
+ * @return the number of bytes stored in output
+ * @throws ShortBufferException if there is insufficient space in the output
+ * byte array
+ */
+ int update(byte[] input, int inputOffset, int inputLen, byte[] output,
+ int outputOffset) throws ShortBufferException;
- /**
- * Encrypts or decrypts data in a single-part operation, or finishes a
- * multiple-part operation.
- *
- * @param inBuffer the input ByteBuffer
- * @param outBuffer the output ByteBuffer
- * @return int number of bytes stored in <code>output</code>
- * @throws BadPaddingException if this cipher is in decryption mode,
- * and (un)padding has been requested, but the decrypted data is not
- * bounded by the appropriate padding bytes
- * @throws IllegalBlockSizeException if this cipher is a block cipher,
- * no padding has been requested (only in encryption mode), and the total
- * input length of the data processed by this cipher is not a multiple of
- * block size; or if this encryption algorithm is unable to
- * process the input data provided.
- * @throws ShortBufferException if the given output buffer is too small
- * to hold the result
- */
- int doFinal(ByteBuffer inBuffer, ByteBuffer outBuffer)
- throws ShortBufferException, IllegalBlockSizeException,
- BadPaddingException;
+ /**
+ * Encrypts or decrypts data in a single-part operation, or finishes a
+ * multiple-part operation.
+ *
+ * @param inBuffer the input ByteBuffer
+ * @param outBuffer the output ByteBuffer
+ * @return int number of bytes stored in <code>output</code>
+ * @throws BadPaddingException if this cipher is in decryption mode, and
+ * (un)padding has been requested, but the decrypted data is not
+ * bounded by the appropriate padding bytes
+ * @throws IllegalBlockSizeException if this cipher is a block cipher, no
+ * padding has been requested (only in encryption mode), and the
+ * total input length of the data processed by this cipher is not a
+ * multiple of block size; or if this encryption algorithm is unable
+ * to process the input data provided.
+ * @throws ShortBufferException if the given output buffer is too small to
+ * hold the result
+ */
+ int doFinal(ByteBuffer inBuffer, ByteBuffer outBuffer)
+ throws ShortBufferException, IllegalBlockSizeException,
+ BadPaddingException;
- /**
- * Encrypts or decrypts data in a single-part operation, or finishes a
- * multiple-part operation.
- *
- * @param input the input byte array
- * @param inputOffset the offset in input where the input starts
- * @param inputLen the input length
- * @param output the byte array for the result
- * @param outputOffset the offset in output where the result is stored
- * @return the number of bytes stored in output
- * @throws ShortBufferException if the given output byte array is too small
- * to hold the result
- * @throws BadPaddingException if this cipher is in decryption mode,
- * and (un)padding has been requested, but the decrypted data is not
- * bounded by the appropriate padding bytes
- * @throws IllegalBlockSizeException if this cipher is a block cipher,
- * no padding has been requested (only in encryption mode), and the total
- * input length of the data processed by this cipher is not a multiple of
- * block size; or if this encryption algorithm is unable to
- * process the input data provided.
- */
- int doFinal(byte[] input, int inputOffset, int inputLen,
- byte[] output, int outputOffset)
- throws ShortBufferException, IllegalBlockSizeException, BadPaddingException;
+ /**
+ * Encrypts or decrypts data in a single-part operation, or finishes a
+ * multiple-part operation.
+ *
+ * @param input the input byte array
+ * @param inputOffset the offset in input where the input starts
+ * @param inputLen the input length
+ * @param output the byte array for the result
+ * @param outputOffset the offset in output where the result is stored
+ * @return the number of bytes stored in output
+ * @throws ShortBufferException if the given output byte array is too small
+ * to hold the result
+ * @throws BadPaddingException if this cipher is in decryption mode, and
+ * (un)padding has been requested, but the decrypted data is not
+ * bounded by the appropriate padding bytes
+ * @throws IllegalBlockSizeException if this cipher is a block cipher, no
+ * padding has been requested (only in encryption mode), and the
+ * total input length of the data processed by this cipher is not a
+ * multiple of block size; or if this encryption algorithm is unable
+ * to process the input data provided.
+ */
+ int doFinal(byte[] input, int inputOffset, int inputLen, byte[] output,
+ int outputOffset) throws ShortBufferException,
+ IllegalBlockSizeException, BadPaddingException;
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/cipher/CryptoCipherFactory.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/cipher/CryptoCipherFactory.java b/src/main/java/org/apache/commons/crypto/cipher/CryptoCipherFactory.java
index 578c962..181589d 100644
--- a/src/main/java/org/apache/commons/crypto/cipher/CryptoCipherFactory.java
+++ b/src/main/java/org/apache/commons/crypto/cipher/CryptoCipherFactory.java
@@ -32,77 +32,80 @@ import org.slf4j.LoggerFactory;
*/
public class CryptoCipherFactory {
- /** LOG instance for {@link CryptoCipherFactory} */
- public final static Logger LOG = LoggerFactory.getLogger(CryptoCipherFactory.class);
+ /** LOG instance for {@link CryptoCipherFactory} */
+ public final static Logger LOG = LoggerFactory
+ .getLogger(CryptoCipherFactory.class);
- private CryptoCipherFactory() {}
+ private CryptoCipherFactory() {
+ }
- /**
- * Gets a cipher instance for specified algorithm/mode/padding.
- *
- * @param props
- * the configuration properties
- * @param transformation
- * algorithm/mode/padding
- * @return CryptoCipher the cipher. Null value will be returned if no
- * cipher classes with transformation configured.
- * @throws GeneralSecurityException if cipher initialize failed
- */
- public static CryptoCipher getInstance(CipherTransformation transformation,
- Properties props) throws GeneralSecurityException {
- List<Class<? extends CryptoCipher>> klasses = getCipherClasses(props);
- CryptoCipher cipher = null;
- if (klasses != null) {
- for (Class<? extends CryptoCipher> klass : klasses) {
- try {
- cipher = ReflectionUtils.newInstance(klass, props, transformation);
- if (cipher != null) {
- LOG.debug("Using cipher {} for transformation {}.", klass.getName(),
- transformation.getName());
- break;
- }
- } catch (Exception e) {
- LOG.error("CryptoCipher {} is not available or transformation {} is not " +
- "supported.", klass.getName(), transformation.getName());
+ /**
+ * Gets a cipher instance for specified algorithm/mode/padding.
+ *
+ * @param props the configuration properties
+ * @param transformation algorithm/mode/padding
+ * @return CryptoCipher the cipher. Null value will be returned if no cipher
+ * classes with transformation configured.
+ * @throws GeneralSecurityException if cipher initialize failed
+ */
+ public static CryptoCipher getInstance(CipherTransformation transformation,
+ Properties props) throws GeneralSecurityException {
+ List<Class<? extends CryptoCipher>> klasses = getCipherClasses(props);
+ CryptoCipher cipher = null;
+ if (klasses != null) {
+ for (Class<? extends CryptoCipher> klass : klasses) {
+ try {
+ cipher = ReflectionUtils.newInstance(klass, props,
+ transformation);
+ if (cipher != null) {
+ LOG.debug("Using cipher {} for transformation {}.",
+ klass.getName(), transformation.getName());
+ break;
+ }
+ } catch (Exception e) {
+ LOG.error(
+ "CryptoCipher {} is not available or transformation {} is not "
+ + "supported.", klass.getName(),
+ transformation.getName());
+ }
+ }
}
- }
+
+ return (cipher == null) ? new JceCipher(props, transformation) : cipher;
}
- return (cipher == null) ? new JceCipher(props, transformation) : cipher;
- }
+ /**
+ * Gets a cipher for algorithm/mode/padding in config value
+ * commons.crypto.cipher.transformation
+ *
+ * @param transformation CipherTransformation instance.
+ * @return CryptoCipher the cipher object Null value will be returned if no
+ * cipher classes with transformation configured.
+ * @throws GeneralSecurityException if JCE cipher initialize failed
+ */
+ public static CryptoCipher getInstance(CipherTransformation transformation)
+ throws GeneralSecurityException {
+ return getInstance(transformation, new Properties());
+ }
- /**
- * Gets a cipher for algorithm/mode/padding in config value
- * commons.crypto.cipher.transformation
- *
- * @param transformation CipherTransformation instance.
- * @return CryptoCipher the cipher object Null value will be returned if no
- * cipher classes with transformation configured.
- * @throws GeneralSecurityException if JCE cipher initialize failed
- */
- public static CryptoCipher getInstance(CipherTransformation transformation)
- throws GeneralSecurityException {
- return getInstance(transformation, new Properties());
- }
+ // Return OpenSSLCipher if Properties is null or empty by default
+ private static List<Class<? extends CryptoCipher>> getCipherClasses(
+ Properties props) {
+ List<Class<? extends CryptoCipher>> result = new ArrayList<Class<? extends CryptoCipher>>();
+ String cipherClassString = Utils.getCipherClassString(props);
- // Return OpenSSLCipher if Properties is null or empty by default
- private static List<Class<? extends CryptoCipher>> getCipherClasses(Properties props) {
- List<Class<? extends CryptoCipher>> result = new ArrayList<Class<? extends
- CryptoCipher>>();
- String cipherClassString = Utils.getCipherClassString(props);
+ for (String c : Utils.splitClassNames(cipherClassString, ",")) {
+ try {
+ Class<?> cls = ReflectionUtils.getClassByName(c);
+ result.add(cls.asSubclass(CryptoCipher.class));
+ } catch (ClassCastException e) {
+ LOG.error("Class {} is not a CryptoCipher.", c);
+ } catch (ClassNotFoundException e) {
+ LOG.error("CryptoCipher {} not found.", c);
+ }
+ }
- for (String c : Utils.splitClassNames(cipherClassString, ",")) {
- try {
- Class<?> cls = ReflectionUtils.getClassByName(c);
- result.add(cls.asSubclass(CryptoCipher.class));
- } catch (ClassCastException e) {
- LOG.error("Class {} is not a CryptoCipher.", c);
- } catch (ClassNotFoundException e) {
- LOG.error("CryptoCipher {} not found.", c);
- }
+ return result;
}
- return result;
- }
-
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/cipher/JceCipher.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/cipher/JceCipher.java b/src/main/java/org/apache/commons/crypto/cipher/JceCipher.java
index 9dadbfb..65079b6 100644
--- a/src/main/java/org/apache/commons/crypto/cipher/JceCipher.java
+++ b/src/main/java/org/apache/commons/crypto/cipher/JceCipher.java
@@ -36,172 +36,172 @@ import org.apache.commons.crypto.utils.Utils;
* Implements the {@link CryptoCipher} using JCE provider.
*/
public class JceCipher implements CryptoCipher {
- private final Properties props;
- private final CipherTransformation transformation;
- private final Cipher cipher;
+ private final Properties props;
+ private final CipherTransformation transformation;
+ private final Cipher cipher;
- /**
- * Constructs a {@link CryptoCipher} based on JCE
- * Cipher {@link Cipher}.
- * @param props properties for JCE cipher
- * @param transformation transformation for JCE cipher
- * @throws GeneralSecurityException if JCE cipher initialize failed
- */
- public JceCipher(Properties props, CipherTransformation transformation)
- throws GeneralSecurityException {
- this.props = props;
- this.transformation = transformation;
+ /**
+ * Constructs a {@link CryptoCipher} based on JCE Cipher {@link Cipher}.
+ *
+ * @param props properties for JCE cipher
+ * @param transformation transformation for JCE cipher
+ * @throws GeneralSecurityException if JCE cipher initialize failed
+ */
+ public JceCipher(Properties props, CipherTransformation transformation)
+ throws GeneralSecurityException {
+ this.props = props;
+ this.transformation = transformation;
- String provider = Utils.getJCEProvider(props);
- if (provider == null || provider.isEmpty()) {
- cipher = Cipher.getInstance(transformation.getName());
- } else {
- cipher = Cipher.getInstance(transformation.getName(), provider);
+ String provider = Utils.getJCEProvider(props);
+ if (provider == null || provider.isEmpty()) {
+ cipher = Cipher.getInstance(transformation.getName());
+ } else {
+ cipher = Cipher.getInstance(transformation.getName(), provider);
+ }
}
- }
- /**
- * Gets the CipherTransformation for the jce cipher.
- *
- * @return the CipherTransformation for this cipher
- */
- @Override
- public CipherTransformation getTransformation() {
- return transformation;
- }
+ /**
+ * Gets the CipherTransformation for the jce cipher.
+ *
+ * @return the CipherTransformation for this cipher
+ */
+ @Override
+ public CipherTransformation getTransformation() {
+ return transformation;
+ }
- /**
- * Gets the properties for the jce cipher.
- *
- * @return the properties for this cipher.
- */
- @Override
- public Properties getProperties() {
- return props;
- }
+ /**
+ * Gets the properties for the jce cipher.
+ *
+ * @return the properties for this cipher.
+ */
+ @Override
+ public Properties getProperties() {
+ return props;
+ }
- /**
- * Initializes the cipher with mode, key and iv.
- *
- * @param mode {@link #ENCRYPT_MODE} or {@link #DECRYPT_MODE}
- * @param key crypto key for the cipher
- * @param params the algorithm parameters
- * @throws InvalidAlgorithmParameterException if the given algorithm
- * parameters are inappropriate for this cipher, or this cipher requires
- * algorithm parameters and <code>params</code> is null, or the given
- * algorithm parameters imply a cryptographic strength that would exceed
- * the legal limits (as determined from the configured jurisdiction
- * policy files).
- */
- @Override
- public void init(int mode, Key key, AlgorithmParameterSpec params)
- throws InvalidKeyException, InvalidAlgorithmParameterException {
- Utils.checkNotNull(key);
- Utils.checkNotNull(params);
+ /**
+ * Initializes the cipher with mode, key and iv.
+ *
+ * @param mode {@link #ENCRYPT_MODE} or {@link #DECRYPT_MODE}
+ * @param key crypto key for the cipher
+ * @param params the algorithm parameters
+ * @throws InvalidAlgorithmParameterException if the given algorithm
+ * parameters are inappropriate for this cipher, or this cipher
+ * requires algorithm parameters and <code>params</code> is null, or
+ * the given algorithm parameters imply a cryptographic strength
+ * that would exceed the legal limits (as determined from the
+ * configured jurisdiction policy files).
+ */
+ @Override
+ public void init(int mode, Key key, AlgorithmParameterSpec params)
+ throws InvalidKeyException, InvalidAlgorithmParameterException {
+ Utils.checkNotNull(key);
+ Utils.checkNotNull(params);
- int cipherMode = Cipher.DECRYPT_MODE;
- if (mode == ENCRYPT_MODE) {
- cipherMode = Cipher.ENCRYPT_MODE;
+ int cipherMode = Cipher.DECRYPT_MODE;
+ if (mode == ENCRYPT_MODE) {
+ cipherMode = Cipher.ENCRYPT_MODE;
+ }
+ cipher.init(cipherMode, key, params);
}
- cipher.init(cipherMode, key, params);
- }
- /**
- * Continues a multiple-part encryption/decryption operation. The data
- * is encrypted or decrypted, depending on how this cipher was initialized.
- *
- * @param inBuffer the input ByteBuffer
- * @param outBuffer the output ByteBuffer
- * @return int number of bytes stored in <code>output</code>
- * @throws ShortBufferException if there is insufficient space
- * in the output buffer
- */
- @Override
- public int update(ByteBuffer inBuffer, ByteBuffer outBuffer)
- throws ShortBufferException {
- return cipher.update(inBuffer, outBuffer);
- }
+ /**
+ * Continues a multiple-part encryption/decryption operation. The data is
+ * encrypted or decrypted, depending on how this cipher was initialized.
+ *
+ * @param inBuffer the input ByteBuffer
+ * @param outBuffer the output ByteBuffer
+ * @return int number of bytes stored in <code>output</code>
+ * @throws ShortBufferException if there is insufficient space in the output
+ * buffer
+ */
+ @Override
+ public int update(ByteBuffer inBuffer, ByteBuffer outBuffer)
+ throws ShortBufferException {
+ return cipher.update(inBuffer, outBuffer);
+ }
- /**
- * Continues a multiple-part encryption/decryption operation. The data
- * is encrypted or decrypted, depending on how this cipher was initialized.
- *
- * @param input the input byte array
- * @param inputOffset the offset in input where the input starts
- * @param inputLen the input length
- * @param output the byte array for the result
- * @param outputOffset the offset in output where the result is stored
- * @return the number of bytes stored in output
- * @throws ShortBufferException if there is insufficient space in the output byte array
- */
- @Override
- public int update(byte[] input, int inputOffset, int inputLen,
- byte[] output, int outputOffset)
- throws ShortBufferException {
- return cipher.update(input, inputOffset, inputLen,
- output, outputOffset);
- }
+ /**
+ * Continues a multiple-part encryption/decryption operation. The data is
+ * encrypted or decrypted, depending on how this cipher was initialized.
+ *
+ * @param input the input byte array
+ * @param inputOffset the offset in input where the input starts
+ * @param inputLen the input length
+ * @param output the byte array for the result
+ * @param outputOffset the offset in output where the result is stored
+ * @return the number of bytes stored in output
+ * @throws ShortBufferException if there is insufficient space in the output
+ * byte array
+ */
+ @Override
+ public int update(byte[] input, int inputOffset, int inputLen,
+ byte[] output, int outputOffset) throws ShortBufferException {
+ return cipher
+ .update(input, inputOffset, inputLen, output, outputOffset);
+ }
- /**
- * Encrypts or decrypts data in a single-part operation, or finishes a
- * multiple-part operation. The data is encrypted or decrypted, depending
- * on how this cipher was initialized.
- *
- * @param inBuffer the input ByteBuffer
- * @param outBuffer the output ByteBuffer
- * @return int number of bytes stored in <code>output</code>
- * @throws BadPaddingException if this cipher is in decryption mode,
- * and (un)padding has been requested, but the decrypted data is not
- * bounded by the appropriate padding bytes
- * @throws IllegalBlockSizeException if this cipher is a block cipher,
- * no padding has been requested (only in encryption mode), and the total
- * input length of the data processed by this cipher is not a multiple of
- * block size; or if this encryption algorithm is unable to
- * process the input data provided.
- * @throws ShortBufferException if the given output buffer is too small
- * to hold the result
- */
- @Override
- public int doFinal(ByteBuffer inBuffer, ByteBuffer outBuffer)
- throws ShortBufferException, IllegalBlockSizeException,
- BadPaddingException {
- return cipher.doFinal(inBuffer, outBuffer);
- }
+ /**
+ * Encrypts or decrypts data in a single-part operation, or finishes a
+ * multiple-part operation. The data is encrypted or decrypted, depending on
+ * how this cipher was initialized.
+ *
+ * @param inBuffer the input ByteBuffer
+ * @param outBuffer the output ByteBuffer
+ * @return int number of bytes stored in <code>output</code>
+ * @throws BadPaddingException if this cipher is in decryption mode, and
+ * (un)padding has been requested, but the decrypted data is not
+ * bounded by the appropriate padding bytes
+ * @throws IllegalBlockSizeException if this cipher is a block cipher, no
+ * padding has been requested (only in encryption mode), and the
+ * total input length of the data processed by this cipher is not a
+ * multiple of block size; or if this encryption algorithm is unable
+ * to process the input data provided.
+ * @throws ShortBufferException if the given output buffer is too small to
+ * hold the result
+ */
+ @Override
+ public int doFinal(ByteBuffer inBuffer, ByteBuffer outBuffer)
+ throws ShortBufferException, IllegalBlockSizeException,
+ BadPaddingException {
+ return cipher.doFinal(inBuffer, outBuffer);
+ }
- /**
- * Encrypts or decrypts data in a single-part operation, or finishes a
- * multiple-part operation.
- *
- * @param input the input byte array
- * @param inputOffset the offset in input where the input starts
- * @param inputLen the input length
- * @param output the byte array for the result
- * @param outputOffset the offset in output where the result is stored
- * @return the number of bytes stored in output
- * @throws ShortBufferException if the given output byte array is too small
- * to hold the result
- * @throws BadPaddingException if this cipher is in decryption mode,
- * and (un)padding has been requested, but the decrypted data is not
- * bounded by the appropriate padding bytes
- * @throws IllegalBlockSizeException if this cipher is a block cipher,
- * no padding has been requested (only in encryption mode), and the total
- * input length of the data processed by this cipher is not a multiple of
- * block size; or if this encryption algorithm is unable to
- * process the input data provided.
- */
- @Override
- public int doFinal(byte[] input, int inputOffset, int inputLen,
- byte[] output, int outputOffset)
- throws ShortBufferException, IllegalBlockSizeException, BadPaddingException {
- return cipher.doFinal(input, inputOffset, inputLen,
- output, outputOffset);
- }
+ /**
+ * Encrypts or decrypts data in a single-part operation, or finishes a
+ * multiple-part operation.
+ *
+ * @param input the input byte array
+ * @param inputOffset the offset in input where the input starts
+ * @param inputLen the input length
+ * @param output the byte array for the result
+ * @param outputOffset the offset in output where the result is stored
+ * @return the number of bytes stored in output
+ * @throws ShortBufferException if the given output byte array is too small
+ * to hold the result
+ * @throws BadPaddingException if this cipher is in decryption mode, and
+ * (un)padding has been requested, but the decrypted data is not
+ * bounded by the appropriate padding bytes
+ * @throws IllegalBlockSizeException if this cipher is a block cipher, no
+ * padding has been requested (only in encryption mode), and the
+ * total input length of the data processed by this cipher is not a
+ * multiple of block size; or if this encryption algorithm is unable
+ * to process the input data provided.
+ */
+ @Override
+ public int doFinal(byte[] input, int inputOffset, int inputLen,
+ byte[] output, int outputOffset) throws ShortBufferException,
+ IllegalBlockSizeException, BadPaddingException {
+ return cipher.doFinal(input, inputOffset, inputLen, output,
+ outputOffset);
+ }
- /**
- * Closes Jce cipher.
- */
- @Override
- public void close() {
- // Do nothing
- }
+ /**
+ * Closes Jce cipher.
+ */
+ @Override
+ public void close() {
+ // Do nothing
+ }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/cipher/Openssl.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/cipher/Openssl.java b/src/main/java/org/apache/commons/crypto/cipher/Openssl.java
index bdee203..de8856c 100644
--- a/src/main/java/org/apache/commons/crypto/cipher/Openssl.java
+++ b/src/main/java/org/apache/commons/crypto/cipher/Openssl.java
@@ -33,302 +33,304 @@ import org.apache.commons.crypto.utils.NativeCodeLoader;
import org.apache.commons.crypto.utils.Utils;
/**
- * OpenSSL cryptographic wrapper using JNI.
- * Currently only AES-CTR is supported. It's flexible to add
- * other crypto algorithms/modes.
+ * OpenSSL cryptographic wrapper using JNI. Currently only AES-CTR is supported.
+ * It's flexible to add other crypto algorithms/modes.
*/
public final class Openssl {
- private static final Log LOG = LogFactory.getLog(Openssl.class.getName());
+ private static final Log LOG = LogFactory.getLog(Openssl.class.getName());
- // Mode constant defined by Openssl JNI
- public static final int ENCRYPT_MODE = 1;
- public static final int DECRYPT_MODE = 0;
+ // Mode constant defined by Openssl JNI
+ public static final int ENCRYPT_MODE = 1;
+ public static final int DECRYPT_MODE = 0;
- /** Currently only support AES/CTR/NoPadding. */
- private static enum AlgorithmMode {
- AES_CTR,
- AES_CBC;
+ /** Currently only support AES/CTR/NoPadding. */
+ private static enum AlgorithmMode {
+ AES_CTR, AES_CBC;
- static int get(String algorithm, String mode)
- throws NoSuchAlgorithmException {
- try {
- return AlgorithmMode.valueOf(algorithm + "_" + mode).ordinal();
- } catch (Exception e) {
- throw new NoSuchAlgorithmException("Doesn't support algorithm: " +
- algorithm + " and mode: " + mode);
- }
+ static int get(String algorithm, String mode)
+ throws NoSuchAlgorithmException {
+ try {
+ return AlgorithmMode.valueOf(algorithm + "_" + mode).ordinal();
+ } catch (Exception e) {
+ throw new NoSuchAlgorithmException(
+ "Doesn't support algorithm: " + algorithm
+ + " and mode: " + mode);
+ }
+ }
}
- }
- private static enum Padding {
- NoPadding,
- PKCS5Padding;
+ private static enum Padding {
+ NoPadding, PKCS5Padding;
- static int get(String padding) throws NoSuchPaddingException {
- try {
- return Padding.valueOf(padding).ordinal();
- } catch (Exception e) {
- throw new NoSuchPaddingException("Doesn't support padding: " + padding);
- }
+ static int get(String padding) throws NoSuchPaddingException {
+ try {
+ return Padding.valueOf(padding).ordinal();
+ } catch (Exception e) {
+ throw new NoSuchPaddingException("Doesn't support padding: "
+ + padding);
+ }
+ }
}
- }
- private long context = 0;
- private final int algorithm;
- private final int padding;
+ private long context = 0;
+ private final int algorithm;
+ private final int padding;
- private static final String loadingFailureReason;
+ private static final String loadingFailureReason;
- static {
- String loadingFailure = null;
- try {
- if (NativeCodeLoader.isNativeCodeLoaded()) {
- OpensslNative.initIDs();
- }
- } catch (Throwable t) {
- loadingFailure = t.getMessage();
- LOG.debug("Failed to load OpenSSL CryptoCipher.", t);
- } finally {
- loadingFailureReason = loadingFailure;
+ static {
+ String loadingFailure = null;
+ try {
+ if (NativeCodeLoader.isNativeCodeLoaded()) {
+ OpensslNative.initIDs();
+ }
+ } catch (Throwable t) {
+ loadingFailure = t.getMessage();
+ LOG.debug("Failed to load OpenSSL CryptoCipher.", t);
+ } finally {
+ loadingFailureReason = loadingFailure;
+ }
}
- }
- /**
- * Gets the failure reason when loading Openssl native.
- * @return the failure reason.
- */
- public static String getLoadingFailureReason() {
- return loadingFailureReason;
- }
+ /**
+ * Gets the failure reason when loading Openssl native.
+ *
+ * @return the failure reason.
+ */
+ public static String getLoadingFailureReason() {
+ return loadingFailureReason;
+ }
- private Openssl(long context, int algorithm, int padding) {
- this.context = context;
- this.algorithm = algorithm;
- this.padding = padding;
- }
+ private Openssl(long context, int algorithm, int padding) {
+ this.context = context;
+ this.algorithm = algorithm;
+ this.padding = padding;
+ }
- /**
- * Return an <code>OpensslCipher</code> object that implements the specified
- * transformation.
- *
- * @param transformation the name of the transformation, e.g.,
- * AES/CTR/NoPadding.
- * @return OpensslCipher an <code>OpensslCipher</code> object
- * @throws NoSuchAlgorithmException if <code>transformation</code> is null,
- * empty, in an invalid format, or if Openssl doesn't implement the
- * specified algorithm.
- * @throws NoSuchPaddingException if <code>transformation</code> contains
- * a padding scheme that is not available.
- */
- public static final Openssl getInstance(String transformation)
- throws NoSuchAlgorithmException, NoSuchPaddingException {
- Transform transform = tokenizeTransformation(transformation);
- int algorithmMode = AlgorithmMode.get(transform.algorithm, transform.mode);
- int padding = Padding.get(transform.padding);
- long context = OpensslNative.initContext(algorithmMode, padding);
- return new Openssl(context, algorithmMode, padding);
- }
+ /**
+ * Return an <code>OpensslCipher</code> object that implements the specified
+ * transformation.
+ *
+ * @param transformation the name of the transformation, e.g.,
+ * AES/CTR/NoPadding.
+ * @return OpensslCipher an <code>OpensslCipher</code> object
+ * @throws NoSuchAlgorithmException if <code>transformation</code> is null,
+ * empty, in an invalid format, or if Openssl doesn't implement the
+ * specified algorithm.
+ * @throws NoSuchPaddingException if <code>transformation</code> contains a
+ * padding scheme that is not available.
+ */
+ public static final Openssl getInstance(String transformation)
+ throws NoSuchAlgorithmException, NoSuchPaddingException {
+ Transform transform = tokenizeTransformation(transformation);
+ int algorithmMode = AlgorithmMode.get(transform.algorithm,
+ transform.mode);
+ int padding = Padding.get(transform.padding);
+ long context = OpensslNative.initContext(algorithmMode, padding);
+ return new Openssl(context, algorithmMode, padding);
+ }
- /** Nested class for algorithm, mode and padding. */
- private static class Transform {
- final String algorithm;
- final String mode;
- final String padding;
+ /** Nested class for algorithm, mode and padding. */
+ private static class Transform {
+ final String algorithm;
+ final String mode;
+ final String padding;
- public Transform(String algorithm, String mode, String padding) {
- this.algorithm = algorithm;
- this.mode = mode;
- this.padding = padding;
+ public Transform(String algorithm, String mode, String padding) {
+ this.algorithm = algorithm;
+ this.mode = mode;
+ this.padding = padding;
+ }
}
- }
- private static Transform tokenizeTransformation(String transformation)
- throws NoSuchAlgorithmException {
- if (transformation == null) {
- throw new NoSuchAlgorithmException("No transformation given.");
+ private static Transform tokenizeTransformation(String transformation)
+ throws NoSuchAlgorithmException {
+ if (transformation == null) {
+ throw new NoSuchAlgorithmException("No transformation given.");
+ }
+
+ /*
+ * Array containing the components of a Cipher transformation: index 0:
+ * algorithm (e.g., AES) index 1: mode (e.g., CTR) index 2: padding
+ * (e.g., NoPadding)
+ */
+ String[] parts = new String[3];
+ int count = 0;
+ StringTokenizer parser = new StringTokenizer(transformation, "/");
+ while (parser.hasMoreTokens() && count < 3) {
+ parts[count++] = parser.nextToken().trim();
+ }
+ if (count != 3 || parser.hasMoreTokens()) {
+ throw new NoSuchAlgorithmException(
+ "Invalid transformation format: " + transformation);
+ }
+ return new Transform(parts[0], parts[1], parts[2]);
}
- /*
- * Array containing the components of a Cipher transformation:
+ /**
+ * Initialize this cipher with a key and IV.
*
- * index 0: algorithm (e.g., AES)
- * index 1: mode (e.g., CTR)
- * index 2: padding (e.g., NoPadding)
+ * @param mode {@link #ENCRYPT_MODE} or {@link #DECRYPT_MODE}
+ * @param key crypto key
+ * @param iv crypto iv
*/
- String[] parts = new String[3];
- int count = 0;
- StringTokenizer parser = new StringTokenizer(transformation, "/");
- while (parser.hasMoreTokens() && count < 3) {
- parts[count++] = parser.nextToken().trim();
+ public void init(int mode, byte[] key, byte[] iv) {
+ context = OpensslNative
+ .init(context, mode, algorithm, padding, key, iv);
}
- if (count != 3 || parser.hasMoreTokens()) {
- throw new NoSuchAlgorithmException("Invalid transformation format: " +
- transformation);
- }
- return new Transform(parts[0], parts[1], parts[2]);
- }
-
- /**
- * Initialize this cipher with a key and IV.
- *
- * @param mode {@link #ENCRYPT_MODE} or {@link #DECRYPT_MODE}
- * @param key crypto key
- * @param iv crypto iv
- */
- public void init(int mode, byte[] key, byte[] iv) {
- context = OpensslNative.init(context, mode, algorithm, padding, key, iv);
- }
- /**
- * <p>
- * Continues a multiple-part encryption or decryption operation. The data
- * is encrypted or decrypted, depending on how this cipher was initialized.
- * </p>
- *
- * <p>
- * All <code>input.remaining()</code> bytes starting at
- * <code>input.position()</code> are processed. The result is stored in
- * the output buffer.
- * </p>
- *
- * <p>
- * Upon return, the input buffer's position will be equal to its limit;
- * its limit will not have changed. The output buffer's position will have
- * advanced by n, when n is the value returned by this method; the output
- * buffer's limit will not have changed.
- * </p>
- *
- * If <code>output.remaining()</code> bytes are insufficient to hold the
- * result, a <code>ShortBufferException</code> is thrown.
- *
- * @param input the input ByteBuffer
- * @param output the output ByteBuffer
- * @return int number of bytes stored in <code>output</code>
- * @throws ShortBufferException if there is insufficient space in the
- * output buffer
- */
- public int update(ByteBuffer input, ByteBuffer output)
- throws ShortBufferException {
- checkState();
- Utils.checkArgument(input.isDirect() && output.isDirect(),
- "Direct buffers are required.");
- int len = OpensslNative.update(context, input, input.position(),
- input.remaining(), output, output.position(), output.remaining());
- input.position(input.limit());
- output.position(output.position() + len);
- return len;
- }
+ /**
+ * <p>
+ * Continues a multiple-part encryption or decryption operation. The data is
+ * encrypted or decrypted, depending on how this cipher was initialized.
+ * </p>
+ *
+ * <p>
+ * All <code>input.remaining()</code> bytes starting at
+ * <code>input.position()</code> are processed. The result is stored in the
+ * output buffer.
+ * </p>
+ *
+ * <p>
+ * Upon return, the input buffer's position will be equal to its limit; its
+ * limit will not have changed. The output buffer's position will have
+ * advanced by n, when n is the value returned by this method; the output
+ * buffer's limit will not have changed.
+ * </p>
+ *
+ * If <code>output.remaining()</code> bytes are insufficient to hold the
+ * result, a <code>ShortBufferException</code> is thrown.
+ *
+ * @param input the input ByteBuffer
+ * @param output the output ByteBuffer
+ * @return int number of bytes stored in <code>output</code>
+ * @throws ShortBufferException if there is insufficient space in the output
+ * buffer
+ */
+ public int update(ByteBuffer input, ByteBuffer output)
+ throws ShortBufferException {
+ checkState();
+ Utils.checkArgument(input.isDirect() && output.isDirect(),
+ "Direct buffers are required.");
+ int len = OpensslNative.update(context, input, input.position(),
+ input.remaining(), output, output.position(),
+ output.remaining());
+ input.position(input.limit());
+ output.position(output.position() + len);
+ return len;
+ }
- /**
- * Continues a multiple-part encryption/decryption operation. The data
- * is encrypted or decrypted, depending on how this cipher was initialized.
- *
- * @param input the input byte array
- * @param inputOffset the offset in input where the input starts
- * @param inputLen the input length
- * @param output the byte array for the result
- * @param outputOffset the offset in output where the result is stored
- * @return the number of bytes stored in output
- * @throws ShortBufferException if there is insufficient space in the output byte array
- */
- public int update(byte[] input, int inputOffset, int inputLen,
- byte[] output, int outputOffset)
- throws ShortBufferException {
- checkState();
- return OpensslNative.updateByteArray(context, input, inputOffset, inputLen,
- output, outputOffset, output.length - outputOffset);
- }
+ /**
+ * Continues a multiple-part encryption/decryption operation. The data is
+ * encrypted or decrypted, depending on how this cipher was initialized.
+ *
+ * @param input the input byte array
+ * @param inputOffset the offset in input where the input starts
+ * @param inputLen the input length
+ * @param output the byte array for the result
+ * @param outputOffset the offset in output where the result is stored
+ * @return the number of bytes stored in output
+ * @throws ShortBufferException if there is insufficient space in the output
+ * byte array
+ */
+ public int update(byte[] input, int inputOffset, int inputLen,
+ byte[] output, int outputOffset) throws ShortBufferException {
+ checkState();
+ return OpensslNative.updateByteArray(context, input, inputOffset,
+ inputLen, output, outputOffset, output.length - outputOffset);
+ }
- /**
- * <p>
- * Finishes a multiple-part operation. The data is encrypted or decrypted,
- * depending on how this cipher was initialized.
- * </p>
- *
- * <p>
- * The result is stored in the output buffer. Upon return, the output buffer's
- * position will have advanced by n, where n is the value returned by this
- * method; the output buffer's limit will not have changed.
- * </p>
- *
- * <p>
- * If <code>output.remaining()</code> bytes are insufficient to hold the result,
- * a <code>ShortBufferException</code> is thrown.
- * </p>
- *
- * <p>
- * Upon finishing, this method resets this cipher object to the state it was
- * in when previously initialized. That is, the object is available to encrypt
- * or decrypt more data.
- * </p>
- *
- * If any exception is thrown, this cipher object need to be reset before it
- * can be used again.
- *
- * @param output the output ByteBuffer
- * @return int number of bytes stored in <code>output</code>
- * @throws ShortBufferException if the given output byte array is too small
- * to hold the result.
- * @throws IllegalBlockSizeException if this cipher is a block cipher,
- * no padding has been requested (only in encryption mode), and the total
- * input length of the data processed by this cipher is not a multiple of
- * block size; or if this encryption algorithm is unable to
- * process the input data provided.
- * @throws BadPaddingException if this cipher is in decryption mode,
- * and (un)padding has been requested, but the decrypted data is not
- * bounded by the appropriate padding bytes
- */
- public int doFinal(ByteBuffer output)
- throws ShortBufferException, IllegalBlockSizeException,
- BadPaddingException {
- checkState();
- Utils.checkArgument(output.isDirect(), "Direct buffer is required.");
- int len = OpensslNative.doFinal(context, output, output.position(), output.remaining());
- output.position(output.position() + len);
- return len;
- }
+ /**
+ * <p>
+ * Finishes a multiple-part operation. The data is encrypted or decrypted,
+ * depending on how this cipher was initialized.
+ * </p>
+ *
+ * <p>
+ * The result is stored in the output buffer. Upon return, the output
+ * buffer's position will have advanced by n, where n is the value returned
+ * by this method; the output buffer's limit will not have changed.
+ * </p>
+ *
+ * <p>
+ * If <code>output.remaining()</code> bytes are insufficient to hold the
+ * result, a <code>ShortBufferException</code> is thrown.
+ * </p>
+ *
+ * <p>
+ * Upon finishing, this method resets this cipher object to the state it was
+ * in when previously initialized. That is, the object is available to
+ * encrypt or decrypt more data.
+ * </p>
+ *
+ * If any exception is thrown, this cipher object need to be reset before it
+ * can be used again.
+ *
+ * @param output the output ByteBuffer
+ * @return int number of bytes stored in <code>output</code>
+ * @throws ShortBufferException if the given output byte array is too small
+ * to hold the result.
+ * @throws IllegalBlockSizeException if this cipher is a block cipher, no
+ * padding has been requested (only in encryption mode), and the
+ * total input length of the data processed by this cipher is not a
+ * multiple of block size; or if this encryption algorithm is unable
+ * to process the input data provided.
+ * @throws BadPaddingException if this cipher is in decryption mode, and
+ * (un)padding has been requested, but the decrypted data is not
+ * bounded by the appropriate padding bytes
+ */
+ public int doFinal(ByteBuffer output) throws ShortBufferException,
+ IllegalBlockSizeException, BadPaddingException {
+ checkState();
+ Utils.checkArgument(output.isDirect(), "Direct buffer is required.");
+ int len = OpensslNative.doFinal(context, output, output.position(),
+ output.remaining());
+ output.position(output.position() + len);
+ return len;
+ }
- /**
- * Encrypts or decrypts data in a single-part operation, or finishes a
- * multiple-part operation.
- *
- * @param output the byte array for the result
- * @param outputOffset the offset in output where the result is stored
- * @return the number of bytes stored in output
- * @throws ShortBufferException if the given output byte array is too small
- * to hold the result
- * @throws BadPaddingException if this cipher is in decryption mode,
- * and (un)padding has been requested, but the decrypted data is not
- * bounded by the appropriate padding bytes
- * @throws IllegalBlockSizeException if this cipher is a block cipher,
- * no padding has been requested (only in encryption mode), and the total
- * input length of the data processed by this cipher is not a multiple of
- * block size; or if this encryption algorithm is unable to
- * process the input data provided.
- */
- public int doFinal(byte[] output, int outputOffset)
- throws ShortBufferException, IllegalBlockSizeException, BadPaddingException {
- checkState();
- return OpensslNative.doFinalByteArray(context,
- output, outputOffset, output.length - outputOffset);
- }
+ /**
+ * Encrypts or decrypts data in a single-part operation, or finishes a
+ * multiple-part operation.
+ *
+ * @param output the byte array for the result
+ * @param outputOffset the offset in output where the result is stored
+ * @return the number of bytes stored in output
+ * @throws ShortBufferException if the given output byte array is too small
+ * to hold the result
+ * @throws BadPaddingException if this cipher is in decryption mode, and
+ * (un)padding has been requested, but the decrypted data is not
+ * bounded by the appropriate padding bytes
+ * @throws IllegalBlockSizeException if this cipher is a block cipher, no
+ * padding has been requested (only in encryption mode), and the
+ * total input length of the data processed by this cipher is not a
+ * multiple of block size; or if this encryption algorithm is unable
+ * to process the input data provided.
+ */
+ public int doFinal(byte[] output, int outputOffset)
+ throws ShortBufferException, IllegalBlockSizeException,
+ BadPaddingException {
+ checkState();
+ return OpensslNative.doFinalByteArray(context, output, outputOffset,
+ output.length - outputOffset);
+ }
- /** Forcibly clean the context. */
- public void clean() {
- if (context != 0) {
- OpensslNative.clean(context);
- context = 0;
+ /** Forcibly clean the context. */
+ public void clean() {
+ if (context != 0) {
+ OpensslNative.clean(context);
+ context = 0;
+ }
}
- }
- /** Checks whether context is initialized. */
- private void checkState() {
- Utils.checkState(context != 0);
- }
+ /** Checks whether context is initialized. */
+ private void checkState() {
+ Utils.checkState(context != 0);
+ }
- @Override
- protected void finalize() throws Throwable {
- clean();
- }
+ @Override
+ protected void finalize() throws Throwable {
+ clean();
+ }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/cipher/OpensslCipher.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/cipher/OpensslCipher.java b/src/main/java/org/apache/commons/crypto/cipher/OpensslCipher.java
index 0473c85..5594a51 100644
--- a/src/main/java/org/apache/commons/crypto/cipher/OpensslCipher.java
+++ b/src/main/java/org/apache/commons/crypto/cipher/OpensslCipher.java
@@ -36,174 +36,178 @@ import org.apache.commons.crypto.utils.Utils;
* Implements the CryptoCipher using JNI into OpenSSL.
*/
public class OpensslCipher implements CryptoCipher {
- private final Properties props;
- private final CipherTransformation transformation;
- private final Openssl cipher;
-
- /**
- * Constructs a {@link CryptoCipher} using JNI into OpenSSL
- *
- * @param props properties for OpenSSL cipher
- * @param transformation transformation for OpenSSL cipher
- * @throws GeneralSecurityException if OpenSSL cipher initialize failed
- */
- public OpensslCipher(Properties props, CipherTransformation transformation)
- throws GeneralSecurityException {
- this.props = props;
- this.transformation = transformation;
-
- String loadingFailureReason = Openssl.getLoadingFailureReason();
- if (loadingFailureReason != null) {
- throw new RuntimeException(loadingFailureReason);
+ private final Properties props;
+ private final CipherTransformation transformation;
+ private final Openssl cipher;
+
+ /**
+ * Constructs a {@link CryptoCipher} using JNI into OpenSSL
+ *
+ * @param props properties for OpenSSL cipher
+ * @param transformation transformation for OpenSSL cipher
+ * @throws GeneralSecurityException if OpenSSL cipher initialize failed
+ */
+ public OpensslCipher(Properties props, CipherTransformation transformation)
+ throws GeneralSecurityException {
+ this.props = props;
+ this.transformation = transformation;
+
+ String loadingFailureReason = Openssl.getLoadingFailureReason();
+ if (loadingFailureReason != null) {
+ throw new RuntimeException(loadingFailureReason);
+ }
+
+ cipher = Openssl.getInstance(transformation.getName());
}
- cipher = Openssl.getInstance(transformation.getName());
- }
-
- /**
- * Gets the CipherTransformation for the openssl cipher.
- *
- * @return the CipherTransformation for this cipher
- */
- @Override
- public CipherTransformation getTransformation() {
- return transformation;
- }
-
- /**
- * Gets the properties for the openssl cipher.
- *
- * @return the properties for this cipher.
- */
- @Override
- public Properties getProperties() {
- return props;
- }
-
- /**
- * Initializes the cipher with mode, key and iv.
- * @param mode {@link #ENCRYPT_MODE} or {@link #DECRYPT_MODE}
- * @param key crypto key for the cipher
- * @param params the algorithm parameters
- * @throws InvalidKeyException If key length is invalid
- * @throws InvalidAlgorithmParameterException if IV length is wrong
- */
- @Override
- public void init(int mode, Key key, AlgorithmParameterSpec params)
- throws InvalidKeyException, InvalidAlgorithmParameterException {
- Utils.checkNotNull(key);
- Utils.checkNotNull(params);
-
- int cipherMode = Openssl.DECRYPT_MODE;
- if (mode == ENCRYPT_MODE) {
- cipherMode = Openssl.ENCRYPT_MODE;
+ /**
+ * Gets the CipherTransformation for the openssl cipher.
+ *
+ * @return the CipherTransformation for this cipher
+ */
+ @Override
+ public CipherTransformation getTransformation() {
+ return transformation;
}
- byte[] iv;
- if (params instanceof IvParameterSpec) {
- iv = ((IvParameterSpec) params).getIV();
- } else {
- //other AlgorithmParameterSpec such as GCMParameterSpec is not supported now.
- throw new InvalidAlgorithmParameterException("Illegal parameters");
+
+ /**
+ * Gets the properties for the openssl cipher.
+ *
+ * @return the properties for this cipher.
+ */
+ @Override
+ public Properties getProperties() {
+ return props;
+ }
+
+ /**
+ * Initializes the cipher with mode, key and iv.
+ *
+ * @param mode {@link #ENCRYPT_MODE} or {@link #DECRYPT_MODE}
+ * @param key crypto key for the cipher
+ * @param params the algorithm parameters
+ * @throws InvalidKeyException If key length is invalid
+ * @throws InvalidAlgorithmParameterException if IV length is wrong
+ */
+ @Override
+ public void init(int mode, Key key, AlgorithmParameterSpec params)
+ throws InvalidKeyException, InvalidAlgorithmParameterException {
+ Utils.checkNotNull(key);
+ Utils.checkNotNull(params);
+
+ int cipherMode = Openssl.DECRYPT_MODE;
+ if (mode == ENCRYPT_MODE) {
+ cipherMode = Openssl.ENCRYPT_MODE;
+ }
+ byte[] iv;
+ if (params instanceof IvParameterSpec) {
+ iv = ((IvParameterSpec) params).getIV();
+ } else {
+ // other AlgorithmParameterSpec such as GCMParameterSpec is not
+ // supported now.
+ throw new InvalidAlgorithmParameterException("Illegal parameters");
+ }
+ cipher.init(cipherMode, key.getEncoded(), iv);
+ }
+
+ /**
+ * Continues a multiple-part encryption/decryption operation. The data is
+ * encrypted or decrypted, depending on how this cipher was initialized.
+ *
+ * @param inBuffer the input ByteBuffer
+ * @param outBuffer the output ByteBuffer
+ * @return int number of bytes stored in <code>output</code>
+ * @throws ShortBufferException if there is insufficient space in the output
+ * buffer
+ */
+ @Override
+ public int update(ByteBuffer inBuffer, ByteBuffer outBuffer)
+ throws ShortBufferException {
+ return cipher.update(inBuffer, outBuffer);
+ }
+
+ /**
+ * Continues a multiple-part encryption/decryption operation. The data is
+ * encrypted or decrypted, depending on how this cipher was initialized.
+ *
+ * @param input the input byte array
+ * @param inputOffset the offset in input where the input starts
+ * @param inputLen the input length
+ * @param output the byte array for the result
+ * @param outputOffset the offset in output where the result is stored
+ * @return the number of bytes stored in output
+ * @throws ShortBufferException if there is insufficient space in the output
+ * byte array
+ */
+ @Override
+ public int update(byte[] input, int inputOffset, int inputLen,
+ byte[] output, int outputOffset) throws ShortBufferException {
+ return cipher
+ .update(input, inputOffset, inputLen, output, outputOffset);
+ }
+
+ /**
+ * Encrypts or decrypts data in a single-part operation, or finishes a
+ * multiple-part operation. The data is encrypted or decrypted, depending on
+ * how this cipher was initialized.
+ *
+ * @param inBuffer the input ByteBuffer
+ * @param outBuffer the output ByteBuffer
+ * @return int number of bytes stored in <code>output</code>
+ * @throws BadPaddingException if this cipher is in decryption mode, and
+ * (un)padding has been requested, but the decrypted data is not
+ * bounded by the appropriate padding bytes
+ * @throws IllegalBlockSizeException if this cipher is a block cipher, no
+ * padding has been requested (only in encryption mode), and the
+ * total input length of the data processed by this cipher is not a
+ * multiple of block size; or if this encryption algorithm is unable
+ * to process the input data provided.
+ * @throws ShortBufferException if the given output buffer is too small to
+ * hold the result
+ */
+ @Override
+ public int doFinal(ByteBuffer inBuffer, ByteBuffer outBuffer)
+ throws ShortBufferException, IllegalBlockSizeException,
+ BadPaddingException {
+ int n = cipher.update(inBuffer, outBuffer);
+ return n + cipher.doFinal(outBuffer);
+ }
+
+ /**
+ * Encrypts or decrypts data in a single-part operation, or finishes a
+ * multiple-part operation.
+ *
+ * @param input the input byte array
+ * @param inputOffset the offset in input where the input starts
+ * @param inputLen the input length
+ * @param output the byte array for the result
+ * @param outputOffset the offset in output where the result is stored
+ * @return the number of bytes stored in output
+ * @throws ShortBufferException if the given output byte array is too small
+ * to hold the result
+ * @throws BadPaddingException if this cipher is in decryption mode, and
+ * (un)padding has been requested, but the decrypted data is not
+ * bounded by the appropriate padding bytes
+ * @throws IllegalBlockSizeException if this cipher is a block cipher, no
+ * padding has been requested (only in encryption mode), and the
+ * total input length of the data processed by this cipher is not a
+ * multiple of block size; or if this encryption algorithm is unable
+ * to process the input data provided.
+ */
+ @Override
+ public int doFinal(byte[] input, int inputOffset, int inputLen,
+ byte[] output, int outputOffset) throws ShortBufferException,
+ IllegalBlockSizeException, BadPaddingException {
+ int n = cipher.update(input, inputOffset, inputLen, output,
+ outputOffset);
+ return n + cipher.doFinal(output, outputOffset + n);
+ }
+
+ /**
+ * Closes the OpenSSL cipher. Clean the Openssl native context.
+ */
+ @Override
+ public void close() {
+ cipher.clean();
}
- cipher.init(cipherMode, key.getEncoded(), iv);
- }
-
- /**
- * Continues a multiple-part encryption/decryption operation. The data
- * is encrypted or decrypted, depending on how this cipher was initialized.
- * @param inBuffer the input ByteBuffer
- * @param outBuffer the output ByteBuffer
- * @return int number of bytes stored in <code>output</code>
- * @throws ShortBufferException if there is insufficient space
- * in the output buffer
- */
- @Override
- public int update(ByteBuffer inBuffer, ByteBuffer outBuffer)
- throws ShortBufferException {
- return cipher.update(inBuffer, outBuffer);
- }
-
- /**
- * Continues a multiple-part encryption/decryption operation. The data
- * is encrypted or decrypted, depending on how this cipher was initialized.
- *
- * @param input the input byte array
- * @param inputOffset the offset in input where the input starts
- * @param inputLen the input length
- * @param output the byte array for the result
- * @param outputOffset the offset in output where the result is stored
- * @return the number of bytes stored in output
- * @throws ShortBufferException if there is insufficient space in the output byte array
- */
- @Override
- public int update(byte[] input, int inputOffset, int inputLen,
- byte[] output, int outputOffset)
- throws ShortBufferException {
- return cipher.update(input, inputOffset, inputLen,
- output, outputOffset);
- }
-
- /**
- * Encrypts or decrypts data in a single-part operation, or finishes a
- * multiple-part operation. The data is encrypted or decrypted, depending
- * on how this cipher was initialized.
- * @param inBuffer the input ByteBuffer
- * @param outBuffer the output ByteBuffer
- * @return int number of bytes stored in <code>output</code>
- * @throws BadPaddingException if this cipher is in decryption mode,
- * and (un)padding has been requested, but the decrypted data is not
- * bounded by the appropriate padding bytes
- * @throws IllegalBlockSizeException if this cipher is a block cipher,
- * no padding has been requested (only in encryption mode), and the total
- * input length of the data processed by this cipher is not a multiple of
- * block size; or if this encryption algorithm is unable to
- * process the input data provided.
- * @throws ShortBufferException if the given output buffer is too small
- * to hold the result
- */
- @Override
- public int doFinal(ByteBuffer inBuffer, ByteBuffer outBuffer)
- throws ShortBufferException, IllegalBlockSizeException,
- BadPaddingException {
- int n = cipher.update(inBuffer, outBuffer);
- return n + cipher.doFinal(outBuffer);
- }
-
- /**
- * Encrypts or decrypts data in a single-part operation, or finishes a
- * multiple-part operation.
- *
- * @param input the input byte array
- * @param inputOffset the offset in input where the input starts
- * @param inputLen the input length
- * @param output the byte array for the result
- * @param outputOffset the offset in output where the result is stored
- * @return the number of bytes stored in output
- * @throws ShortBufferException if the given output byte array is too small
- * to hold the result
- * @throws BadPaddingException if this cipher is in decryption mode,
- * and (un)padding has been requested, but the decrypted data is not
- * bounded by the appropriate padding bytes
- * @throws IllegalBlockSizeException if this cipher is a block cipher,
- * no padding has been requested (only in encryption mode), and the total
- * input length of the data processed by this cipher is not a multiple of
- * block size; or if this encryption algorithm is unable to
- * process the input data provided.
- */
- @Override
- public int doFinal(byte[] input, int inputOffset, int inputLen,
- byte[] output, int outputOffset)
- throws ShortBufferException, IllegalBlockSizeException, BadPaddingException {
- int n = cipher.update(input, inputOffset, inputLen,
- output, outputOffset);
- return n + cipher.doFinal(output, outputOffset + n);
- }
-
- /**
- * Closes the OpenSSL cipher. Clean the Openssl native context.
- */
- @Override
- public void close() {
- cipher.clean();
- }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/cipher/OpensslNative.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/cipher/OpensslNative.java b/src/main/java/org/apache/commons/crypto/cipher/OpensslNative.java
index f290956..15060c9 100644
--- a/src/main/java/org/apache/commons/crypto/cipher/OpensslNative.java
+++ b/src/main/java/org/apache/commons/crypto/cipher/OpensslNative.java
@@ -20,105 +20,106 @@ package org.apache.commons.crypto.cipher;
import java.nio.ByteBuffer;
/**
- * JNI interface of {@link Openssl} implementation. The native method in this class is
- * defined in OpensslNative.h(genereted by javah).
+ * JNI interface of {@link Openssl} implementation. The native method in this
+ * class is defined in OpensslNative.h(genereted by javah).
*/
public class OpensslNative {
- private OpensslNative() {}
+ private OpensslNative() {
+ }
- /**
- * Declares a native method to initialize JNI field and method IDs.
- */
- public native static void initIDs();
+ /**
+ * Declares a native method to initialize JNI field and method IDs.
+ */
+ public native static void initIDs();
- /**
- * Declares a native method to initialize the cipher context.
- *
- * @param algorithm The algorithm name of cipher
- * @param padding The padding name of cipher
- * @return the context address of cipher
- */
- public native static long initContext(int algorithm, int padding);
+ /**
+ * Declares a native method to initialize the cipher context.
+ *
+ * @param algorithm The algorithm name of cipher
+ * @param padding The padding name of cipher
+ * @return the context address of cipher
+ */
+ public native static long initContext(int algorithm, int padding);
- /**
- * Declares a native method to initialize the cipher context.
- *
- * @param context The cipher context address
- * @param mode ENCRYPT_MODE or DECRYPT_MODE
- * @param alg Algorithm Mode of Openssl
- * @param padding the padding mode of Openssl cipher
- * @param key crypto key
- * @param iv crypto iv
- * @return the context address of cipher
- */
- public native static long init(long context, int mode, int alg, int padding,
- byte[] key, byte[] iv);
+ /**
+ * Declares a native method to initialize the cipher context.
+ *
+ * @param context The cipher context address
+ * @param mode ENCRYPT_MODE or DECRYPT_MODE
+ * @param alg Algorithm Mode of Openssl
+ * @param padding the padding mode of Openssl cipher
+ * @param key crypto key
+ * @param iv crypto iv
+ * @return the context address of cipher
+ */
+ public native static long init(long context, int mode, int alg,
+ int padding, byte[] key, byte[] iv);
- /**
- * Continues a multiple-part encryption/decryption operation. The data
- * is encrypted or decrypted, depending on how this cipher was initialized.
- *
- * @param context The cipher context address
- * @param input The input byte buffer
- * @param inputOffset The offset in input where the input starts
- * @param inputLength The input length
- * @param output The byte buffer for the result
- * @param outputOffset The offset in output where the result is stored
- * @param maxOutputLength The maximum length for output
- * @return The number of bytes stored in output
- */
- public native static int update(long context, ByteBuffer input,
- int inputOffset, int inputLength, ByteBuffer output, int outputOffset,
- int maxOutputLength);
+ /**
+ * Continues a multiple-part encryption/decryption operation. The data is
+ * encrypted or decrypted, depending on how this cipher was initialized.
+ *
+ * @param context The cipher context address
+ * @param input The input byte buffer
+ * @param inputOffset The offset in input where the input starts
+ * @param inputLength The input length
+ * @param output The byte buffer for the result
+ * @param outputOffset The offset in output where the result is stored
+ * @param maxOutputLength The maximum length for output
+ * @return The number of bytes stored in output
+ */
+ public native static int update(long context, ByteBuffer input,
+ int inputOffset, int inputLength, ByteBuffer output,
+ int outputOffset, int maxOutputLength);
- /**
- * Continues a multiple-part encryption/decryption operation. The data
- * is encrypted or decrypted, depending on how this cipher was initialized.
- *
- * @param context The cipher context address
- * @param input The input byte array
- * @param inputOffset The offset in input where the input starts
- * @param inputLength The input length
- * @param output The byte array for the result
- * @param outputOffset The offset in output where the result is stored
- * @param maxOutputLength The maximum length for output
- * @return The number of bytes stored in output
- */
- public native static int updateByteArray(long context, byte[] input,
- int inputOffset, int inputLength, byte[] output, int outputOffset,
- int maxOutputLength);
+ /**
+ * Continues a multiple-part encryption/decryption operation. The data is
+ * encrypted or decrypted, depending on how this cipher was initialized.
+ *
+ * @param context The cipher context address
+ * @param input The input byte array
+ * @param inputOffset The offset in input where the input starts
+ * @param inputLength The input length
+ * @param output The byte array for the result
+ * @param outputOffset The offset in output where the result is stored
+ * @param maxOutputLength The maximum length for output
+ * @return The number of bytes stored in output
+ */
+ public native static int updateByteArray(long context, byte[] input,
+ int inputOffset, int inputLength, byte[] output, int outputOffset,
+ int maxOutputLength);
- /**
- * Finishes a multiple-part operation. The data is encrypted or decrypted,
- * depending on how this cipher was initialized.
- *
- * @param context The cipher context address
- * @param output The byte buffer for the result
- * @param offset The offset in output where the result is stored
- * @param maxOutputLength The maximum length for output
- * @return The number of bytes stored in output
- */
- public native static int doFinal(long context, ByteBuffer output, int offset,
- int maxOutputLength);
+ /**
+ * Finishes a multiple-part operation. The data is encrypted or decrypted,
+ * depending on how this cipher was initialized.
+ *
+ * @param context The cipher context address
+ * @param output The byte buffer for the result
+ * @param offset The offset in output where the result is stored
+ * @param maxOutputLength The maximum length for output
+ * @return The number of bytes stored in output
+ */
+ public native static int doFinal(long context, ByteBuffer output,
+ int offset, int maxOutputLength);
- /**
- * Finishes a multiple-part operation. The data is encrypted or decrypted,
- * depending on how this cipher was initialized.
- *
- * @param context The cipher context address
- * @param output The byte array for the result
- * @param offset The offset in output where the result is stored
- * @param maxOutputLength The maximum length for output
- * @return The number of bytes stored in output
- */
- public native static int doFinalByteArray(long context, byte[] output, int offset,
- int maxOutputLength);
+ /**
+ * Finishes a multiple-part operation. The data is encrypted or decrypted,
+ * depending on how this cipher was initialized.
+ *
+ * @param context The cipher context address
+ * @param output The byte array for the result
+ * @param offset The offset in output where the result is stored
+ * @param maxOutputLength The maximum length for output
+ * @return The number of bytes stored in output
+ */
+ public native static int doFinalByteArray(long context, byte[] output,
+ int offset, int maxOutputLength);
- /**
- * Cleans the context at native.
- *
- * @param context The cipher context address
- */
- public native static void clean(long context);
+ /**
+ * Cleans the context at native.
+ *
+ * @param context The cipher context address
+ */
+ public native static void clean(long context);
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/cipher/package-info.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/cipher/package-info.java b/src/main/java/org/apache/commons/crypto/cipher/package-info.java
index 0da563f..b3e358a 100644
--- a/src/main/java/org/apache/commons/crypto/cipher/package-info.java
+++ b/src/main/java/org/apache/commons/crypto/cipher/package-info.java
@@ -20,3 +20,4 @@
* CryptoCipher classes
*/
package org.apache.commons.crypto.cipher;
+
[6/7] commons-crypto git commit: CRYPTO-37: Change all the 2 spaces
indent to 4 to comply Commons code style
Posted by xu...@apache.org.
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/conf/ConfigurationKeys.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/conf/ConfigurationKeys.java b/src/main/java/org/apache/commons/crypto/conf/ConfigurationKeys.java
index 7bab928..c6005a5 100644
--- a/src/main/java/org/apache/commons/crypto/conf/ConfigurationKeys.java
+++ b/src/main/java/org/apache/commons/crypto/conf/ConfigurationKeys.java
@@ -25,112 +25,112 @@ import org.apache.commons.crypto.random.CryptoRandom;
*/
public class ConfigurationKeys {
- /**
- * The prefix of crypto configuration.
- */
- public static final String CONF_PREFIX = "commons.crypto.";
-
- /**
- * The filename of configuration file.
- */
- public static final String COMMONS_CRYPTO_SYSTEM_PROPERTIES_FILE =
- CONF_PREFIX + "properties";
-
- /**
- * The configuration key of implementation class for crypto cipher.
- * The values of COMMONS_CRYPTO_CIPHER_CLASSES_KEY can be
- * "org.apache.commons.crypto.cipher.JceCipher" and "org.apache.commons.crypto.cipher.OpensslCipher".
- * And it takes a common separated list.
- * The "org.apache.commons.crypto.cipher.JceCipher" use jce provider to
- * implement CryptoCipher and
- * the "org.apache.commons.crypto.cipher.OpensslCipher" use jni into openssl to implement.
- * Note that for each value,the first value which can be created without exception
- * will be used (priority by order).
- */
- public static final String COMMONS_CRYPTO_CIPHER_CLASSES_KEY =
- CONF_PREFIX + "cipher.classes";
-
- /**
- * The default value for crypto cipher.
- */
- public static final String COMMONS_CRYPTO_CIPHER_CLASSES_DEFAULT =
- OpensslCipher.class.getName();
-
- /**
- * The configuration key of the provider class for JCE cipher.
- */
- public static final String COMMONS_CRYPTO_CIPHER_JCE_PROVIDER_KEY =
- CONF_PREFIX + "cipher.jce.provider";
-
- // security random related configuration keys
- /**
- * The configuration key of the file path for secure random device.
- */
- public static final String COMMONS_CRYPTO_SECURE_RANDOM_DEVICE_FILE_PATH_KEY =
- CONF_PREFIX + "secure.random.device.file.path";
-
- /**
- * The default value of the file path for secure random device.
- */
- public static final String COMMONS_CRYPTO_SECURE_RANDOM_DEVICE_FILE_PATH_DEFAULT =
- "/dev/urandom";
-
- /**
- * The configuration key of the algorithm of secure random.
- */
- public static final String COMMONS_CRYPTO_SECURE_RANDOM_JAVA_ALGORITHM_KEY =
- CONF_PREFIX + "secure.random.java.algorithm";
-
- /**
- * The default value of the algorithm of secure random.
- */
- public static final String
- COMMONS_CRYPTO_SECURE_RANDOM_JAVA_ALGORITHM_DEFAULT = "SHA1PRNG";
-
- /**
- * The configuration key of the implementation class for secure random.
- * The values of COMMONS_CRYPTO_SECURE_RANDOM_CLASSES_KEY can be
- * "org.apache.commons.crypto.random.JavaCryptoRandom" and "org.apache.commons.crypto.random.OpensslCryptoRandom".
- * And it takes a common separated list.
- * The "org.apache.commons.crypto.random.JavaCryptoRandom" use java to
- * implement {@link CryptoRandom} and
- * the "org.apache.commons.crypto.random.OpensslCryptoRandom" use jni into openssl to implement.
- * Note that for each value,the first value which can be created without exception
- * will be used (priority by order).
- */
- public static final String COMMONS_CRYPTO_SECURE_RANDOM_CLASSES_KEY =
- CONF_PREFIX + "secure.random.classes";
-
- /**
- * The configuration key of the buffer size for stream.
- */
- public static final String COMMONS_CRYPTO_STREAM_BUFFER_SIZE_KEY =
- CONF_PREFIX + "stream.buffer.size";
-
- // stream related configuration keys
- /**
- * The default value of the buffer size for stream.
- */
- public static final int COMMONS_CRYPTO_STREAM_BUFFER_SIZE_DEFAULT = 8192;
-
- // native lib related configuration keys
- /**
- * The configuration key of the path for loading crypto library.
- */
- public static final String COMMONS_CRYPTO_LIB_PATH_KEY =
- CONF_PREFIX + "lib.path";
-
- /**
- * The configuration key of the file name for loading crypto library.
- */
- public static final String COMMONS_CRYPTO_LIB_NAME_KEY =
- CONF_PREFIX + "lib.name";
-
- /**
- * The configuration key of temp directory for extracting crypto library.
- */
- public static final String COMMONS_CRYPTO_LIB_TEMPDIR_KEY =
- CONF_PREFIX + "lib.tempdir";
-
- private ConfigurationKeys() {}
+ /**
+ * The prefix of crypto configuration.
+ */
+ public static final String CONF_PREFIX = "commons.crypto.";
+
+ /**
+ * The filename of configuration file.
+ */
+ public static final String COMMONS_CRYPTO_SYSTEM_PROPERTIES_FILE = CONF_PREFIX
+ + "properties";
+
+ /**
+ * The configuration key of implementation class for crypto cipher. The
+ * values of COMMONS_CRYPTO_CIPHER_CLASSES_KEY can be
+ * "org.apache.commons.crypto.cipher.JceCipher" and
+ * "org.apache.commons.crypto.cipher.OpensslCipher". And it takes a common
+ * separated list. The "org.apache.commons.crypto.cipher.JceCipher" use jce
+ * provider to implement CryptoCipher and the
+ * "org.apache.commons.crypto.cipher.OpensslCipher" use jni into openssl to
+ * implement. Note that for each value,the first value which can be created
+ * without exception will be used (priority by order).
+ */
+ public static final String COMMONS_CRYPTO_CIPHER_CLASSES_KEY = CONF_PREFIX
+ + "cipher.classes";
+
+ /**
+ * The default value for crypto cipher.
+ */
+ public static final String COMMONS_CRYPTO_CIPHER_CLASSES_DEFAULT = OpensslCipher.class
+ .getName();
+
+ /**
+ * The configuration key of the provider class for JCE cipher.
+ */
+ public static final String COMMONS_CRYPTO_CIPHER_JCE_PROVIDER_KEY = CONF_PREFIX
+ + "cipher.jce.provider";
+
+ // security random related configuration keys
+ /**
+ * The configuration key of the file path for secure random device.
+ */
+ public static final String COMMONS_CRYPTO_SECURE_RANDOM_DEVICE_FILE_PATH_KEY = CONF_PREFIX
+ + "secure.random.device.file.path";
+
+ /**
+ * The default value of the file path for secure random device.
+ */
+ public static final String COMMONS_CRYPTO_SECURE_RANDOM_DEVICE_FILE_PATH_DEFAULT = "/dev/urandom";
+
+ /**
+ * The configuration key of the algorithm of secure random.
+ */
+ public static final String COMMONS_CRYPTO_SECURE_RANDOM_JAVA_ALGORITHM_KEY = CONF_PREFIX
+ + "secure.random.java.algorithm";
+
+ /**
+ * The default value of the algorithm of secure random.
+ */
+ public static final String COMMONS_CRYPTO_SECURE_RANDOM_JAVA_ALGORITHM_DEFAULT = "SHA1PRNG";
+
+ /**
+ * The configuration key of the implementation class for secure random. The
+ * values of COMMONS_CRYPTO_SECURE_RANDOM_CLASSES_KEY can be
+ * "org.apache.commons.crypto.random.JavaCryptoRandom" and
+ * "org.apache.commons.crypto.random.OpensslCryptoRandom". And it takes a
+ * common separated list. The
+ * "org.apache.commons.crypto.random.JavaCryptoRandom" use java to implement
+ * {@link CryptoRandom} and the
+ * "org.apache.commons.crypto.random.OpensslCryptoRandom" use jni into
+ * openssl to implement. Note that for each value,the first value which can
+ * be created without exception will be used (priority by order).
+ */
+ public static final String COMMONS_CRYPTO_SECURE_RANDOM_CLASSES_KEY = CONF_PREFIX
+ + "secure.random.classes";
+
+ /**
+ * The configuration key of the buffer size for stream.
+ */
+ public static final String COMMONS_CRYPTO_STREAM_BUFFER_SIZE_KEY = CONF_PREFIX
+ + "stream.buffer.size";
+
+ // stream related configuration keys
+ /**
+ * The default value of the buffer size for stream.
+ */
+ public static final int COMMONS_CRYPTO_STREAM_BUFFER_SIZE_DEFAULT = 8192;
+
+ // native lib related configuration keys
+ /**
+ * The configuration key of the path for loading crypto library.
+ */
+ public static final String COMMONS_CRYPTO_LIB_PATH_KEY = CONF_PREFIX
+ + "lib.path";
+
+ /**
+ * The configuration key of the file name for loading crypto library.
+ */
+ public static final String COMMONS_CRYPTO_LIB_NAME_KEY = CONF_PREFIX
+ + "lib.name";
+
+ /**
+ * The configuration key of temp directory for extracting crypto library.
+ */
+ public static final String COMMONS_CRYPTO_LIB_TEMPDIR_KEY = CONF_PREFIX
+ + "lib.tempdir";
+
+ private ConfigurationKeys() {
+ }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/conf/package-info.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/conf/package-info.java b/src/main/java/org/apache/commons/crypto/conf/package-info.java
index 837b195..6e340a9 100644
--- a/src/main/java/org/apache/commons/crypto/conf/package-info.java
+++ b/src/main/java/org/apache/commons/crypto/conf/package-info.java
@@ -19,3 +19,4 @@
* Configuration classes
*/
package org.apache.commons.crypto.conf;
+
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/random/CryptoRandom.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/random/CryptoRandom.java b/src/main/java/org/apache/commons/crypto/random/CryptoRandom.java
index 8194a9b..6c8c983 100644
--- a/src/main/java/org/apache/commons/crypto/random/CryptoRandom.java
+++ b/src/main/java/org/apache/commons/crypto/random/CryptoRandom.java
@@ -24,13 +24,13 @@ import java.io.Closeable;
*/
public interface CryptoRandom extends Closeable {
- /**
- * Generates random bytes and places them into a user-supplied
- * byte array. The number of random bytes produced is equal to
- * the length of the byte array.
- *
- * @param bytes the byte array to fill with random bytes
- */
- void nextBytes(byte[] bytes);
+ /**
+ * Generates random bytes and places them into a user-supplied byte array.
+ * The number of random bytes produced is equal to the length of the byte
+ * array.
+ *
+ * @param bytes the byte array to fill with random bytes
+ */
+ void nextBytes(byte[] bytes);
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/random/CryptoRandomFactory.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/random/CryptoRandomFactory.java b/src/main/java/org/apache/commons/crypto/random/CryptoRandomFactory.java
index 8c9fd35..df57cd8 100644
--- a/src/main/java/org/apache/commons/crypto/random/CryptoRandomFactory.java
+++ b/src/main/java/org/apache/commons/crypto/random/CryptoRandomFactory.java
@@ -26,51 +26,56 @@ import org.slf4j.LoggerFactory;
import org.apache.commons.crypto.utils.Utils;
import org.apache.commons.crypto.utils.ReflectionUtils;
-import static org.apache.commons.crypto.conf.ConfigurationKeys
- .COMMONS_CRYPTO_SECURE_RANDOM_CLASSES_KEY;
+import static org.apache.commons.crypto.conf.ConfigurationKeys.COMMONS_CRYPTO_SECURE_RANDOM_CLASSES_KEY;
/**
* This is the factory class used for {@link CryptoRandom}.
*/
public class CryptoRandomFactory {
- public final static Logger LOG = LoggerFactory
- .getLogger(CryptoRandomFactory.class);
+ public final static Logger LOG = LoggerFactory
+ .getLogger(CryptoRandomFactory.class);
- private CryptoRandomFactory() {}
-
- /**
- * Gets a CryptoRandom instance for specified props.
- *
- * @param props the configuration properties.
- * @return CryptoRandom the cryptoRandom object.Null value will be returned if no CryptoRandom
- * classes with props.
- * @throws GeneralSecurityException if fail to create the {@link CryptoRandom}.
- */
- public static CryptoRandom getCryptoRandom(Properties props) throws GeneralSecurityException {
- String cryptoRandomClasses = props.getProperty(
- COMMONS_CRYPTO_SECURE_RANDOM_CLASSES_KEY);
- if (cryptoRandomClasses == null) {
- cryptoRandomClasses = System.getProperty(
- COMMONS_CRYPTO_SECURE_RANDOM_CLASSES_KEY);
+ private CryptoRandomFactory() {
}
- CryptoRandom random = null;
- if (cryptoRandomClasses != null) {
- for (String klassName : Utils.splitClassNames(cryptoRandomClasses, ",")) {
- try {
- final Class<?> klass = ReflectionUtils.getClassByName(klassName);
- random = (CryptoRandom) ReflectionUtils.newInstance(klass, props);
- if (random != null) {
- break;
- }
- } catch (ClassCastException e) {
- LOG.error("Class {} is not a CryptoCipher.", klassName);
- } catch (ClassNotFoundException e) {
- LOG.error("CryptoCipher {} not found.", klassName);
+ /**
+ * Gets a CryptoRandom instance for specified props.
+ *
+ * @param props the configuration properties.
+ * @return CryptoRandom the cryptoRandom object.Null value will be returned
+ * if no CryptoRandom classes with props.
+ * @throws GeneralSecurityException if fail to create the
+ * {@link CryptoRandom}.
+ */
+ public static CryptoRandom getCryptoRandom(Properties props)
+ throws GeneralSecurityException {
+ String cryptoRandomClasses = props
+ .getProperty(COMMONS_CRYPTO_SECURE_RANDOM_CLASSES_KEY);
+ if (cryptoRandomClasses == null) {
+ cryptoRandomClasses = System
+ .getProperty(COMMONS_CRYPTO_SECURE_RANDOM_CLASSES_KEY);
}
- }
- }
- return (random == null) ? new JavaCryptoRandom(props) : random;
- }
+ CryptoRandom random = null;
+ if (cryptoRandomClasses != null) {
+ for (String klassName : Utils.splitClassNames(cryptoRandomClasses,
+ ",")) {
+ try {
+ final Class<?> klass = ReflectionUtils
+ .getClassByName(klassName);
+ random = (CryptoRandom) ReflectionUtils.newInstance(klass,
+ props);
+ if (random != null) {
+ break;
+ }
+ } catch (ClassCastException e) {
+ LOG.error("Class {} is not a CryptoCipher.", klassName);
+ } catch (ClassNotFoundException e) {
+ LOG.error("CryptoCipher {} not found.", klassName);
+ }
+ }
+ }
+
+ return (random == null) ? new JavaCryptoRandom(props) : random;
+ }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/random/JavaCryptoRandom.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/random/JavaCryptoRandom.java b/src/main/java/org/apache/commons/crypto/random/JavaCryptoRandom.java
index ac0ab3e..69fbf98 100644
--- a/src/main/java/org/apache/commons/crypto/random/JavaCryptoRandom.java
+++ b/src/main/java/org/apache/commons/crypto/random/JavaCryptoRandom.java
@@ -30,42 +30,45 @@ import org.apache.commons.crypto.conf.ConfigurationKeys;
* A CryptoRandom of Java implementation.
*/
public class JavaCryptoRandom implements CryptoRandom {
- private static final Log LOG =
- LogFactory.getLog(JavaCryptoRandom.class.getName());
+ private static final Log LOG = LogFactory.getLog(JavaCryptoRandom.class
+ .getName());
- private final SecureRandom instance;
+ private final SecureRandom instance;
- /**
- * Constructs a {@link JavaCryptoRandom}.
- *
- * @param properties the configuration properties.
- * @throws NoSuchAlgorithmException if no Provider supports a SecureRandomSpi implementation for
- * the specified algorithm.
- */
- public JavaCryptoRandom(Properties properties) throws NoSuchAlgorithmException {
- instance = SecureRandom.getInstance(properties
- .getProperty(ConfigurationKeys.COMMONS_CRYPTO_SECURE_RANDOM_JAVA_ALGORITHM_KEY,
- ConfigurationKeys.COMMONS_CRYPTO_SECURE_RANDOM_JAVA_ALGORITHM_DEFAULT));
- }
+ /**
+ * Constructs a {@link JavaCryptoRandom}.
+ *
+ * @param properties the configuration properties.
+ * @throws NoSuchAlgorithmException if no Provider supports a
+ * SecureRandomSpi implementation for the specified algorithm.
+ */
+ public JavaCryptoRandom(Properties properties)
+ throws NoSuchAlgorithmException {
+ instance = SecureRandom
+ .getInstance(properties
+ .getProperty(
+ ConfigurationKeys.COMMONS_CRYPTO_SECURE_RANDOM_JAVA_ALGORITHM_KEY,
+ ConfigurationKeys.COMMONS_CRYPTO_SECURE_RANDOM_JAVA_ALGORITHM_DEFAULT));
+ }
- /**
- * Overrides {@link java.lang.AutoCloseable#close()}.
- * For{@link JavaCryptoRandom}, we don't need to recycle resource.
- */
- @Override
- public void close() {
- // do nothing
- }
+ /**
+ * Overrides {@link java.lang.AutoCloseable#close()}. For
+ * {@link JavaCryptoRandom}, we don't need to recycle resource.
+ */
+ @Override
+ public void close() {
+ // do nothing
+ }
- /**
- * Overrides {@link CryptoRandom#nextBytes(byte[])}.
- * Generates random bytes and places them into a user-supplied byte array.
- * The number of random bytes produced is equal to the length of the byte array.
- *
- * @param bytes the array to be filled in with random bytes.
- */
- @Override
- public void nextBytes(byte[] bytes) {
- instance.nextBytes(bytes);
- }
+ /**
+ * Overrides {@link CryptoRandom#nextBytes(byte[])}. Generates random bytes
+ * and places them into a user-supplied byte array. The number of random
+ * bytes produced is equal to the length of the byte array.
+ *
+ * @param bytes the array to be filled in with random bytes.
+ */
+ @Override
+ public void nextBytes(byte[] bytes) {
+ instance.nextBytes(bytes);
+ }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/random/OpensslCryptoRandom.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/random/OpensslCryptoRandom.java b/src/main/java/org/apache/commons/crypto/random/OpensslCryptoRandom.java
index 315e259..3adb9b6 100644
--- a/src/main/java/org/apache/commons/crypto/random/OpensslCryptoRandom.java
+++ b/src/main/java/org/apache/commons/crypto/random/OpensslCryptoRandom.java
@@ -33,118 +33,120 @@ import org.apache.commons.crypto.utils.Utils;
* </p>
*
* <p>
- * If using an Intel chipset with RDRAND, the high-performance hardware
- * random number generator will be used and it's much faster than
- * SecureRandom. If RDRAND is unavailable, default OpenSSL secure random
- * generator will be used. It's still faster and can generate strong random bytes.
+ * If using an Intel chipset with RDRAND, the high-performance hardware random
+ * number generator will be used and it's much faster than SecureRandom. If
+ * RDRAND is unavailable, default OpenSSL secure random generator will be used.
+ * It's still faster and can generate strong random bytes.
* </p>
+ *
* @see <a href="https://wiki.openssl.org/index.php/Random_Numbers">
* https://wiki.openssl.org/index.php/Random_Numbers</a>
* @see <a href="http://en.wikipedia.org/wiki/RdRand">
* http://en.wikipedia.org/wiki/RdRand</a>
*/
public class OpensslCryptoRandom extends Random implements CryptoRandom {
- private static final long serialVersionUID = -7828193502768789584L;
- private static final Log LOG =
- LogFactory.getLog(OpensslCryptoRandom.class.getName());
+ private static final long serialVersionUID = -7828193502768789584L;
+ private static final Log LOG = LogFactory.getLog(OpensslCryptoRandom.class
+ .getName());
- /** If native SecureRandom unavailable, use java SecureRandom */
- private final JavaCryptoRandom fallback;
- private static final boolean nativeEnabled;
+ /** If native SecureRandom unavailable, use java SecureRandom */
+ private final JavaCryptoRandom fallback;
+ private static final boolean nativeEnabled;
- static {
- boolean opensslLoaded = false;
- if (NativeCodeLoader.isNativeCodeLoaded()) {
- try {
- OpensslCryptoRandomNative.initSR();
- opensslLoaded = true;
- } catch (Throwable t) {
- LOG.error("Failed to load Openssl CryptoRandom", t);
- }
+ static {
+ boolean opensslLoaded = false;
+ if (NativeCodeLoader.isNativeCodeLoaded()) {
+ try {
+ OpensslCryptoRandomNative.initSR();
+ opensslLoaded = true;
+ } catch (Throwable t) {
+ LOG.error("Failed to load Openssl CryptoRandom", t);
+ }
+ }
+ nativeEnabled = opensslLoaded;
}
- nativeEnabled = opensslLoaded;
- }
- /**
- * Judges whether loading native library successfully.
- *
- * @return true if loading library successfully.
- */
- public static boolean isNativeCodeLoaded() {
- return nativeEnabled;
- }
+ /**
+ * Judges whether loading native library successfully.
+ *
+ * @return true if loading library successfully.
+ */
+ public static boolean isNativeCodeLoaded() {
+ return nativeEnabled;
+ }
- /**
- * Constructs a {@link OpensslCryptoRandom}.
- *
- * @param props the configuration properties.
- * @throws NoSuchAlgorithmException if no Provider supports a SecureRandomSpi implementation for
- * the specified algorithm.
- */
- public OpensslCryptoRandom(Properties props) throws NoSuchAlgorithmException {
- if (!nativeEnabled) {
- fallback = new JavaCryptoRandom(props);
- } else {
- fallback = null;
+ /**
+ * Constructs a {@link OpensslCryptoRandom}.
+ *
+ * @param props the configuration properties.
+ * @throws NoSuchAlgorithmException if no Provider supports a
+ * SecureRandomSpi implementation for the specified algorithm.
+ */
+ public OpensslCryptoRandom(Properties props)
+ throws NoSuchAlgorithmException {
+ if (!nativeEnabled) {
+ fallback = new JavaCryptoRandom(props);
+ } else {
+ fallback = null;
+ }
}
- }
- /**
- * Generates a user-specified number of random bytes.
- * It's thread-safe.
- *
- * @param bytes the array to be filled in with random bytes.
- */
- @Override
- public void nextBytes(byte[] bytes) {
- if (!nativeEnabled || !OpensslCryptoRandomNative.nextRandBytes(bytes)) {
- fallback.nextBytes(bytes);
+ /**
+ * Generates a user-specified number of random bytes. It's thread-safe.
+ *
+ * @param bytes the array to be filled in with random bytes.
+ */
+ @Override
+ public void nextBytes(byte[] bytes) {
+ if (!nativeEnabled || !OpensslCryptoRandomNative.nextRandBytes(bytes)) {
+ fallback.nextBytes(bytes);
+ }
}
- }
- /**
- * Overrides {@link OpensslCryptoRandom}.
- * For {@link OpensslCryptoRandom}, we don't need to set seed.
- *
- * @param seed the initial seed.
- */
- @Override
- public void setSeed(long seed) {
- // Self-seeding.
- }
+ /**
+ * Overrides {@link OpensslCryptoRandom}. For {@link OpensslCryptoRandom},
+ * we don't need to set seed.
+ *
+ * @param seed the initial seed.
+ */
+ @Override
+ public void setSeed(long seed) {
+ // Self-seeding.
+ }
- /**
- * Overrides Random#next(). Generates an integer containing the
- * user-specified number of random bits(right justified, with leading
- * zeros).
- *
- * @param numBits number of random bits to be generated, where 0
- * {@literal <=} <code>numBits</code> {@literal <=} 32.
- * @return int an <code>int</code> containing the user-specified number of
- * random bits (right justified, with leading zeros).
- */
- @Override
- final protected int next(int numBits) {
- Utils.checkArgument(numBits >= 0 && numBits <= 32);
- int numBytes = (numBits + 7) / 8;
- byte b[] = new byte[numBytes];
- int next = 0;
+ /**
+ * Overrides Random#next(). Generates an integer containing the
+ * user-specified number of random bits(right justified, with leading
+ * zeros).
+ *
+ * @param numBits number of random bits to be generated, where 0
+ * {@literal <=} <code>numBits</code> {@literal <=} 32.
+ * @return int an <code>int</code> containing the user-specified number of
+ * random bits (right justified, with leading zeros).
+ */
+ @Override
+ final protected int next(int numBits) {
+ Utils.checkArgument(numBits >= 0 && numBits <= 32);
+ int numBytes = (numBits + 7) / 8;
+ byte b[] = new byte[numBytes];
+ int next = 0;
- nextBytes(b);
- for (int i = 0; i < numBytes; i++) {
- next = (next << 8) + (b[i] & 0xFF);
- }
+ nextBytes(b);
+ for (int i = 0; i < numBytes; i++) {
+ next = (next << 8) + (b[i] & 0xFF);
+ }
- return next >>> (numBytes * 8 - numBits);
- }
+ return next >>> (numBytes * 8 - numBits);
+ }
- /**
- * Overrides {@link java.lang.AutoCloseable#close()}. Closes openssl context if native enabled.
- */
- @Override
- public void close() {
- if (!nativeEnabled && fallback !=null) {
- fallback.close();
+ /**
+ * Overrides {@link java.lang.AutoCloseable#close()}. Closes openssl context
+ * if native enabled.
+ */
+ @Override
+ public void close() {
+ if (!nativeEnabled && fallback != null) {
+ fallback.close();
+ }
}
- }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/random/OpensslCryptoRandomNative.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/random/OpensslCryptoRandomNative.java b/src/main/java/org/apache/commons/crypto/random/OpensslCryptoRandomNative.java
index 8b4a0a1..65078c3 100644
--- a/src/main/java/org/apache/commons/crypto/random/OpensslCryptoRandomNative.java
+++ b/src/main/java/org/apache/commons/crypto/random/OpensslCryptoRandomNative.java
@@ -18,26 +18,26 @@
package org.apache.commons.crypto.random;
/**
- * JNI interface of {@link CryptoRandom} implementation.
- * The native method in this class is defined in
- * OpensslCryptoRandomNative.h(genereted by javah).
+ * JNI interface of {@link CryptoRandom} implementation. The native method in
+ * this class is defined in OpensslCryptoRandomNative.h(genereted by javah).
*/
public class OpensslCryptoRandomNative {
- private OpensslCryptoRandomNative() {}
+ private OpensslCryptoRandomNative() {
+ }
- /**
- * Declares a native method to initialize SR.
- */
- public native static void initSR();
+ /**
+ * Declares a native method to initialize SR.
+ */
+ public native static void initSR();
- /**
- * Judges whether use {@link OpensslCryptoRandomNative} to
- * generate the user-specified number of random bits.
- *
- * @param bytes the array to be filled in with random bytes.
- * @return true if use {@link OpensslCryptoRandomNative} to
- * generate the user-specified number of random bits.
- */
- public native static boolean nextRandBytes(byte[] bytes);
+ /**
+ * Judges whether use {@link OpensslCryptoRandomNative} to generate the
+ * user-specified number of random bits.
+ *
+ * @param bytes the array to be filled in with random bytes.
+ * @return true if use {@link OpensslCryptoRandomNative} to generate the
+ * user-specified number of random bits.
+ */
+ public native static boolean nextRandBytes(byte[] bytes);
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/random/OsCryptoRandom.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/random/OsCryptoRandom.java b/src/main/java/org/apache/commons/crypto/random/OsCryptoRandom.java
index 7c8bc07..eca62d2 100644
--- a/src/main/java/org/apache/commons/crypto/random/OsCryptoRandom.java
+++ b/src/main/java/org/apache/commons/crypto/random/OsCryptoRandom.java
@@ -29,105 +29,105 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
- * A Random implementation that uses random bytes sourced from the
- * operating system.
+ * A Random implementation that uses random bytes sourced from the operating
+ * system.
*/
public class OsCryptoRandom extends Random implements CryptoRandom {
- public static final Log LOG = LogFactory.getLog(OsCryptoRandom.class);
+ public static final Log LOG = LogFactory.getLog(OsCryptoRandom.class);
- private static final long serialVersionUID = 6391500337172057900L;
+ private static final long serialVersionUID = 6391500337172057900L;
- private final int RESERVOIR_LENGTH = 8192;
+ private final int RESERVOIR_LENGTH = 8192;
- private String randomDevPath;
+ private String randomDevPath;
- private transient FileInputStream stream;
+ private transient FileInputStream stream;
- private final byte[] reservoir = new byte[RESERVOIR_LENGTH];
+ private final byte[] reservoir = new byte[RESERVOIR_LENGTH];
- private int pos = reservoir.length;
+ private int pos = reservoir.length;
- private void fillReservoir(int min) {
- if (pos >= reservoir.length - min) {
- try {
- IOUtils.readFully(stream, reservoir, 0, reservoir.length);
- } catch (IOException e) {
- throw new RuntimeException("failed to fill reservoir", e);
- }
- pos = 0;
- }
- }
-
- /**
- * Constructs a {@link OsCryptoRandom}.
- *
- * @param props the configuration properties.
- */
- public OsCryptoRandom(Properties props) {
- randomDevPath = Utils.getRandomDevPath(props);
- File randomDevFile = new File(randomDevPath);
-
- try {
- close();
- this.stream = new FileInputStream(randomDevFile);
- } catch (IOException e) {
- throw new RuntimeException(e);
+ private void fillReservoir(int min) {
+ if (pos >= reservoir.length - min) {
+ try {
+ IOUtils.readFully(stream, reservoir, 0, reservoir.length);
+ } catch (IOException e) {
+ throw new RuntimeException("failed to fill reservoir", e);
+ }
+ pos = 0;
+ }
}
- try {
- fillReservoir(0);
- } catch (RuntimeException e) {
- close();
- throw e;
+ /**
+ * Constructs a {@link OsCryptoRandom}.
+ *
+ * @param props the configuration properties.
+ */
+ public OsCryptoRandom(Properties props) {
+ randomDevPath = Utils.getRandomDevPath(props);
+ File randomDevFile = new File(randomDevPath);
+
+ try {
+ close();
+ this.stream = new FileInputStream(randomDevFile);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+
+ try {
+ fillReservoir(0);
+ } catch (RuntimeException e) {
+ close();
+ throw e;
+ }
}
- }
-
- /**
- * Overrides {@link CryptoRandom#nextBytes(byte[])}.
- * Generates random bytes and places them into a user-supplied byte array.
- * The number of random bytes produced is equal to the length of the byte array.
- *
- * @param bytes the array to be filled in with random bytes.
- */
- @Override
- synchronized public void nextBytes(byte[] bytes) {
- int off = 0;
- int n = 0;
- while (off < bytes.length) {
- fillReservoir(0);
- n = Math.min(bytes.length - off, reservoir.length - pos);
- System.arraycopy(reservoir, pos, bytes, off, n);
- off += n;
- pos += n;
+
+ /**
+ * Overrides {@link CryptoRandom#nextBytes(byte[])}. Generates random bytes
+ * and places them into a user-supplied byte array. The number of random
+ * bytes produced is equal to the length of the byte array.
+ *
+ * @param bytes the array to be filled in with random bytes.
+ */
+ @Override
+ synchronized public void nextBytes(byte[] bytes) {
+ int off = 0;
+ int n = 0;
+ while (off < bytes.length) {
+ fillReservoir(0);
+ n = Math.min(bytes.length - off, reservoir.length - pos);
+ System.arraycopy(reservoir, pos, bytes, off, n);
+ off += n;
+ pos += n;
+ }
}
- }
-
- /**
- * Overrides Random#next(). Generates the next pseudorandom number.
- * Subclasses should override this, as this is used by all other methods.
- *
- * @param nbits random bits.
- * @return the next pseudorandom value from this random number
- * generator's sequence.
- */
- @Override
- synchronized protected int next(int nbits) {
- fillReservoir(4);
- int n = 0;
- for (int i = 0; i < 4; i++) {
- n = ((n << 8) | (reservoir[pos++] & 0xff));
+
+ /**
+ * Overrides Random#next(). Generates the next pseudorandom number.
+ * Subclasses should override this, as this is used by all other methods.
+ *
+ * @param nbits random bits.
+ * @return the next pseudorandom value from this random number generator's
+ * sequence.
+ */
+ @Override
+ synchronized protected int next(int nbits) {
+ fillReservoir(4);
+ int n = 0;
+ for (int i = 0; i < 4; i++) {
+ n = ((n << 8) | (reservoir[pos++] & 0xff));
+ }
+ return n & (0xffffffff >> (32 - nbits));
}
- return n & (0xffffffff >> (32 - nbits));
- }
-
- /**
- * Overrides {@link java.lang.AutoCloseable#close()}. Closes the OS stream.
- */
- @Override
- synchronized public void close() {
- if (stream != null) {
- IOUtils.cleanup(LOG, stream);
- stream = null;
+
+ /**
+ * Overrides {@link java.lang.AutoCloseable#close()}. Closes the OS stream.
+ */
+ @Override
+ synchronized public void close() {
+ if (stream != null) {
+ IOUtils.cleanup(LOG, stream);
+ stream = null;
+ }
}
- }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/random/package-info.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/random/package-info.java b/src/main/java/org/apache/commons/crypto/random/package-info.java
index f8fd4de..9e392a7 100644
--- a/src/main/java/org/apache/commons/crypto/random/package-info.java
+++ b/src/main/java/org/apache/commons/crypto/random/package-info.java
@@ -19,3 +19,4 @@
* Random classes
*/
package org.apache.commons.crypto.random;
+
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/stream/CTRCryptoInputStream.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/stream/CTRCryptoInputStream.java b/src/main/java/org/apache/commons/crypto/stream/CTRCryptoInputStream.java
index 481b0d6..b357000 100644
--- a/src/main/java/org/apache/commons/crypto/stream/CTRCryptoInputStream.java
+++ b/src/main/java/org/apache/commons/crypto/stream/CTRCryptoInputStream.java
@@ -41,588 +41,581 @@ import org.apache.commons.crypto.utils.Utils;
* <p>
* CTRCryptoInputStream decrypts data. AES CTR mode is required in order to
* ensure that the plain text and cipher text have a 1:1 mapping. CTR crypto
- * stream has stream characteristic which is useful for implement features
- * like random seek. The decryption is buffer based. The key points of the
- * decryption are (1) calculating the counter and (2) padding through stream
- * position:
+ * stream has stream characteristic which is useful for implement features like
+ * random seek. The decryption is buffer based. The key points of the decryption
+ * are (1) calculating the counter and (2) padding through stream position:
* </p>
* <p>
- * counter = base + pos/(algorithm blocksize);
- * padding = pos%(algorithm blocksize);
+ * counter = base + pos/(algorithm blocksize); padding = pos%(algorithm
+ * blocksize);
* </p>
* The underlying stream offset is maintained as state. It is not thread-safe.
*/
public class CTRCryptoInputStream extends CryptoInputStream {
- /**
- * Underlying stream offset
- */
- long streamOffset = 0;
-
- /**
- * The initial IV.
- */
- protected final byte[] initIV;
-
- /**
- * Initialization vector for the cipher.
- */
- protected byte[] iv;
-
- /**
- * Padding = pos%(algorithm blocksize); Padding is put into {@link #inBuffer}
- * before any other data goes in. The purpose of padding is to put the input
- * data at proper position.
- */
- private byte padding;
-
- /**
- * Flag to mark whether the cipher has been reset
- */
- private boolean cipherReset = false;
-
- /**
- * Constructs a {@link CTRCryptoInputStream}.
- *
- * @param props The <code>Properties</code> class represents a set of
- * properties.
- * @param in the input stream.
- * @param key crypto key for the cipher.
- * @param iv Initialization vector for the cipher.
- * @throws IOException if an I/O error occurs.
- */
- public CTRCryptoInputStream(Properties props, InputStream in,
- byte[] key, byte[] iv)
- throws IOException {
- this(props, in, key, iv, 0);
- }
-
- /**
- * Constructs a {@link CTRCryptoInputStream}.
- *
- * @param props The <code>Properties</code> class represents a set of
- * properties.
- * @param in the ReadableByteChannel instance.
- * @param key crypto key for the cipher.
- * @param iv Initialization vector for the cipher.
- * @throws IOException if an I/O error occurs.
- */
- public CTRCryptoInputStream(Properties props, ReadableByteChannel in,
- byte[] key, byte[] iv)
- throws IOException {
- this(props, in, key, iv, 0);
- }
-
- /**
- * Constructs a {@link CTRCryptoInputStream}.
- *
- * @param in the input stream.
- * @param cipher the CryptoCipher instance.
- * @param bufferSize the bufferSize.
- * @param key crypto key for the cipher.
- * @param iv Initialization vector for the cipher.
- * @throws IOException if an I/O error occurs.
- */
- public CTRCryptoInputStream(InputStream in, CryptoCipher cipher, int bufferSize,
- byte[] key, byte[] iv) throws IOException {
- this(in, cipher, bufferSize, key, iv, 0);
- }
-
- /**
- * Constructs a {@link CTRCryptoInputStream}.
- *
- * @param in the ReadableByteChannel instance.
- * @param cipher the cipher instance.
- * @param bufferSize the bufferSize.
- * @param key crypto key for the cipher.
- * @param iv Initialization vector for the cipher.
- * @throws IOException if an I/O error occurs.
- */
- public CTRCryptoInputStream(ReadableByteChannel in, CryptoCipher cipher,
- int bufferSize, byte[] key, byte[] iv) throws IOException {
- this(in, cipher, bufferSize, key, iv, 0);
- }
-
- /**
- * Constructs a {@link CTRCryptoInputStream}.
- *
- * @param input the input data.
- * @param cipher the CryptoCipher instance.
- * @param bufferSize the bufferSize.
- * @param key crypto key for the cipher.
- * @param iv Initialization vector for the cipher.
- * @throws IOException if an I/O error occurs.
- */
- public CTRCryptoInputStream(
- Input input,
- CryptoCipher cipher,
- int bufferSize,
- byte[] key,
- byte[] iv) throws IOException {
- this(input, cipher, bufferSize, key, iv, 0);
- }
-
- /**
- * Constructs a {@link CTRCryptoInputStream}.
- *
- * @param props The <code>Properties</code> class represents a set of
- * properties.
- * @param in the InputStream instance.
- * @param key crypto key for the cipher.
- * @param iv Initialization vector for the cipher.
- * @param streamOffset the start offset in the stream.
- * @throws IOException if an I/O error occurs.
- */
- public CTRCryptoInputStream(Properties props, InputStream in,
- byte[] key, byte[] iv, long streamOffset)
- throws IOException {
- this(in, Utils.getCipherInstance(CipherTransformation.AES_CTR_NOPADDING, props),
- Utils.getBufferSize(props), key, iv, streamOffset);
- }
-
- /**
- *Constructs a {@link CTRCryptoInputStream}.
- *
- * @param props The <code>Properties</code> class represents a set of
- * properties.
- * @param in the ReadableByteChannel instance.
- * @param key crypto key for the cipher.
- * @param iv Initialization vector for the cipher.
- * @param streamOffset the start offset in the stream.
- * @throws IOException if an I/O error occurs.
- */
- public CTRCryptoInputStream(Properties props, ReadableByteChannel in,
- byte[] key, byte[] iv, long streamOffset)
- throws IOException {
- this(in, Utils.getCipherInstance(CipherTransformation.AES_CTR_NOPADDING, props),
- Utils.getBufferSize(props), key, iv, streamOffset);
- }
-
- /**
- * Constructs a {@link CTRCryptoInputStream}.
- *
- * @param in the InputStream instance.
- * @param cipher the CryptoCipher instance.
- * @param bufferSize the bufferSize.
- * @param key crypto key for the cipher.
- * @param iv Initialization vector for the cipher.
- * @param streamOffset the start offset in the stream.
- * @throws IOException if an I/O error occurs.
- */
- public CTRCryptoInputStream(InputStream in, CryptoCipher cipher, int bufferSize,
- byte[] key, byte[] iv, long streamOffset) throws IOException {
- this(new StreamInput(in, bufferSize), cipher, bufferSize, key, iv, streamOffset);
- }
-
- /**
- * Constructs a {@link CTRCryptoInputStream}.
- *
- * @param in the ReadableByteChannel instance.
- * @param cipher the CryptoCipher instance.
- * @param bufferSize the bufferSize.
- * @param key crypto key for the cipher.
- * @param iv Initialization vector for the cipher.
- * @param streamOffset the start offset in the stream.
- * @throws IOException if an I/O error occurs.
- */
- public CTRCryptoInputStream(ReadableByteChannel in, CryptoCipher cipher,
- int bufferSize, byte[] key, byte[] iv, long streamOffset) throws IOException {
- this(new ChannelInput(in), cipher, bufferSize, key, iv, streamOffset);
- }
-
- /**
- * Constructs a {@link CTRCryptoInputStream}.
- *
- * @param input the input data.
- * @param cipher the CryptoCipher instance.
- * @param bufferSize the bufferSize.
- * @param key crypto key for the cipher.
- * @param iv Initialization vector for the cipher.
- * @param streamOffset the start offset in the stream.
- * @throws IOException if an I/O error occurs.
- */
- public CTRCryptoInputStream(
- Input input,
- CryptoCipher cipher,
- int bufferSize,
- byte[] key,
- byte[] iv,
- long streamOffset) throws IOException {
- super(input, cipher, bufferSize, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));
-
- this.initIV = iv.clone();
- this.iv = iv.clone();
-
- Utils.checkStreamCipher(cipher);
-
- resetStreamOffset(streamOffset);
- }
-
- /**
- * Overrides the {@link CryptoInputStream#skip(long)}.
- * Skips over and discards <code>n</code> bytes of data from this input
- * stream.
- *
- * @param n the number of bytes to be skipped.
- * @return the actual number of bytes skipped.
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public long skip(long n) throws IOException {
- Utils.checkArgument(n >= 0, "Negative skip length.");
- checkStream();
-
- if (n == 0) {
- return 0;
- } else if (n <= outBuffer.remaining()) {
- int pos = outBuffer.position() + (int) n;
- outBuffer.position(pos);
- return n;
- } else {
- /*
- * Subtract outBuffer.remaining() to see how many bytes we need to
- * skip in the underlying stream. Add outBuffer.remaining() to the
- * actual number of skipped bytes in the underlying stream to get the
- * number of skipped bytes from the user's point of view.
- */
- n -= outBuffer.remaining();
- long skipped = input.skip(n);
- if (skipped < 0) {
- skipped = 0;
- }
- long pos = streamOffset + skipped;
- skipped += outBuffer.remaining();
- resetStreamOffset(pos);
- return skipped;
+ /**
+ * Underlying stream offset
+ */
+ long streamOffset = 0;
+
+ /**
+ * The initial IV.
+ */
+ protected final byte[] initIV;
+
+ /**
+ * Initialization vector for the cipher.
+ */
+ protected byte[] iv;
+
+ /**
+ * Padding = pos%(algorithm blocksize); Padding is put into
+ * {@link #inBuffer} before any other data goes in. The purpose of padding
+ * is to put the input data at proper position.
+ */
+ private byte padding;
+
+ /**
+ * Flag to mark whether the cipher has been reset
+ */
+ private boolean cipherReset = false;
+
+ /**
+ * Constructs a {@link CTRCryptoInputStream}.
+ *
+ * @param props The <code>Properties</code> class represents a set of
+ * properties.
+ * @param in the input stream.
+ * @param key crypto key for the cipher.
+ * @param iv Initialization vector for the cipher.
+ * @throws IOException if an I/O error occurs.
+ */
+ public CTRCryptoInputStream(Properties props, InputStream in, byte[] key,
+ byte[] iv) throws IOException {
+ this(props, in, key, iv, 0);
}
- }
-
- /**
- * Overrides the {@link CTRCryptoInputStream#read(ByteBuffer)}.
- * Reads a sequence of bytes from this channel into the given buffer.
- *
- * @param buf The buffer into which bytes are to be transferred.
- * @return The number of bytes read, possibly zero, or <tt>-1</tt> if the
- * channel has reached end-of-stream.
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public int read(ByteBuffer buf) throws IOException {
- checkStream();
- int unread = outBuffer.remaining();
- if (unread <= 0) { // Fill the unread decrypted data buffer firstly
- final int n = input.read(inBuffer);
- if (n <= 0) {
- return n;
- }
-
- streamOffset += n; // Read n bytes
- if (buf.isDirect() && buf.remaining() >= inBuffer.position() && padding == 0) {
- // Use buf as the output buffer directly
- decryptInPlace(buf);
- padding = postDecryption(streamOffset);
- return n;
- } else {
- // Use outBuffer as the output buffer
+
+ /**
+ * Constructs a {@link CTRCryptoInputStream}.
+ *
+ * @param props The <code>Properties</code> class represents a set of
+ * properties.
+ * @param in the ReadableByteChannel instance.
+ * @param key crypto key for the cipher.
+ * @param iv Initialization vector for the cipher.
+ * @throws IOException if an I/O error occurs.
+ */
+ public CTRCryptoInputStream(Properties props, ReadableByteChannel in,
+ byte[] key, byte[] iv) throws IOException {
+ this(props, in, key, iv, 0);
+ }
+
+ /**
+ * Constructs a {@link CTRCryptoInputStream}.
+ *
+ * @param in the input stream.
+ * @param cipher the CryptoCipher instance.
+ * @param bufferSize the bufferSize.
+ * @param key crypto key for the cipher.
+ * @param iv Initialization vector for the cipher.
+ * @throws IOException if an I/O error occurs.
+ */
+ public CTRCryptoInputStream(InputStream in, CryptoCipher cipher,
+ int bufferSize, byte[] key, byte[] iv) throws IOException {
+ this(in, cipher, bufferSize, key, iv, 0);
+ }
+
+ /**
+ * Constructs a {@link CTRCryptoInputStream}.
+ *
+ * @param in the ReadableByteChannel instance.
+ * @param cipher the cipher instance.
+ * @param bufferSize the bufferSize.
+ * @param key crypto key for the cipher.
+ * @param iv Initialization vector for the cipher.
+ * @throws IOException if an I/O error occurs.
+ */
+ public CTRCryptoInputStream(ReadableByteChannel in, CryptoCipher cipher,
+ int bufferSize, byte[] key, byte[] iv) throws IOException {
+ this(in, cipher, bufferSize, key, iv, 0);
+ }
+
+ /**
+ * Constructs a {@link CTRCryptoInputStream}.
+ *
+ * @param input the input data.
+ * @param cipher the CryptoCipher instance.
+ * @param bufferSize the bufferSize.
+ * @param key crypto key for the cipher.
+ * @param iv Initialization vector for the cipher.
+ * @throws IOException if an I/O error occurs.
+ */
+ public CTRCryptoInputStream(Input input, CryptoCipher cipher,
+ int bufferSize, byte[] key, byte[] iv) throws IOException {
+ this(input, cipher, bufferSize, key, iv, 0);
+ }
+
+ /**
+ * Constructs a {@link CTRCryptoInputStream}.
+ *
+ * @param props The <code>Properties</code> class represents a set of
+ * properties.
+ * @param in the InputStream instance.
+ * @param key crypto key for the cipher.
+ * @param iv Initialization vector for the cipher.
+ * @param streamOffset the start offset in the stream.
+ * @throws IOException if an I/O error occurs.
+ */
+ public CTRCryptoInputStream(Properties props, InputStream in, byte[] key,
+ byte[] iv, long streamOffset) throws IOException {
+ this(in, Utils.getCipherInstance(
+ CipherTransformation.AES_CTR_NOPADDING, props), Utils
+ .getBufferSize(props), key, iv, streamOffset);
+ }
+
+ /**
+ * Constructs a {@link CTRCryptoInputStream}.
+ *
+ * @param props The <code>Properties</code> class represents a set of
+ * properties.
+ * @param in the ReadableByteChannel instance.
+ * @param key crypto key for the cipher.
+ * @param iv Initialization vector for the cipher.
+ * @param streamOffset the start offset in the stream.
+ * @throws IOException if an I/O error occurs.
+ */
+ public CTRCryptoInputStream(Properties props, ReadableByteChannel in,
+ byte[] key, byte[] iv, long streamOffset) throws IOException {
+ this(in, Utils.getCipherInstance(
+ CipherTransformation.AES_CTR_NOPADDING, props), Utils
+ .getBufferSize(props), key, iv, streamOffset);
+ }
+
+ /**
+ * Constructs a {@link CTRCryptoInputStream}.
+ *
+ * @param in the InputStream instance.
+ * @param cipher the CryptoCipher instance.
+ * @param bufferSize the bufferSize.
+ * @param key crypto key for the cipher.
+ * @param iv Initialization vector for the cipher.
+ * @param streamOffset the start offset in the stream.
+ * @throws IOException if an I/O error occurs.
+ */
+ public CTRCryptoInputStream(InputStream in, CryptoCipher cipher,
+ int bufferSize, byte[] key, byte[] iv, long streamOffset)
+ throws IOException {
+ this(new StreamInput(in, bufferSize), cipher, bufferSize, key, iv,
+ streamOffset);
+ }
+
+ /**
+ * Constructs a {@link CTRCryptoInputStream}.
+ *
+ * @param in the ReadableByteChannel instance.
+ * @param cipher the CryptoCipher instance.
+ * @param bufferSize the bufferSize.
+ * @param key crypto key for the cipher.
+ * @param iv Initialization vector for the cipher.
+ * @param streamOffset the start offset in the stream.
+ * @throws IOException if an I/O error occurs.
+ */
+ public CTRCryptoInputStream(ReadableByteChannel in, CryptoCipher cipher,
+ int bufferSize, byte[] key, byte[] iv, long streamOffset)
+ throws IOException {
+ this(new ChannelInput(in), cipher, bufferSize, key, iv, streamOffset);
+ }
+
+ /**
+ * Constructs a {@link CTRCryptoInputStream}.
+ *
+ * @param input the input data.
+ * @param cipher the CryptoCipher instance.
+ * @param bufferSize the bufferSize.
+ * @param key crypto key for the cipher.
+ * @param iv Initialization vector for the cipher.
+ * @param streamOffset the start offset in the stream.
+ * @throws IOException if an I/O error occurs.
+ */
+ public CTRCryptoInputStream(Input input, CryptoCipher cipher,
+ int bufferSize, byte[] key, byte[] iv, long streamOffset)
+ throws IOException {
+ super(input, cipher, bufferSize, new SecretKeySpec(key, "AES"),
+ new IvParameterSpec(iv));
+
+ this.initIV = iv.clone();
+ this.iv = iv.clone();
+
+ Utils.checkStreamCipher(cipher);
+
+ resetStreamOffset(streamOffset);
+ }
+
+ /**
+ * Overrides the {@link CryptoInputStream#skip(long)}. Skips over and
+ * discards <code>n</code> bytes of data from this input stream.
+ *
+ * @param n the number of bytes to be skipped.
+ * @return the actual number of bytes skipped.
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public long skip(long n) throws IOException {
+ Utils.checkArgument(n >= 0, "Negative skip length.");
+ checkStream();
+
+ if (n == 0) {
+ return 0;
+ } else if (n <= outBuffer.remaining()) {
+ int pos = outBuffer.position() + (int) n;
+ outBuffer.position(pos);
+ return n;
+ } else {
+ /*
+ * Subtract outBuffer.remaining() to see how many bytes we need to
+ * skip in the underlying stream. Add outBuffer.remaining() to the
+ * actual number of skipped bytes in the underlying stream to get
+ * the number of skipped bytes from the user's point of view.
+ */
+ n -= outBuffer.remaining();
+ long skipped = input.skip(n);
+ if (skipped < 0) {
+ skipped = 0;
+ }
+ long pos = streamOffset + skipped;
+ skipped += outBuffer.remaining();
+ resetStreamOffset(pos);
+ return skipped;
+ }
+ }
+
+ /**
+ * Overrides the {@link CTRCryptoInputStream#read(ByteBuffer)}. Reads a
+ * sequence of bytes from this channel into the given buffer.
+ *
+ * @param buf The buffer into which bytes are to be transferred.
+ * @return The number of bytes read, possibly zero, or <tt>-1</tt> if the
+ * channel has reached end-of-stream.
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public int read(ByteBuffer buf) throws IOException {
+ checkStream();
+ int unread = outBuffer.remaining();
+ if (unread <= 0) { // Fill the unread decrypted data buffer firstly
+ final int n = input.read(inBuffer);
+ if (n <= 0) {
+ return n;
+ }
+
+ streamOffset += n; // Read n bytes
+ if (buf.isDirect() && buf.remaining() >= inBuffer.position()
+ && padding == 0) {
+ // Use buf as the output buffer directly
+ decryptInPlace(buf);
+ padding = postDecryption(streamOffset);
+ return n;
+ } else {
+ // Use outBuffer as the output buffer
+ decrypt();
+ padding = postDecryption(streamOffset);
+ }
+ }
+
+ // Copy decrypted data from outBuffer to buf
+ unread = outBuffer.remaining();
+ final int toRead = buf.remaining();
+ if (toRead <= unread) {
+ final int limit = outBuffer.limit();
+ outBuffer.limit(outBuffer.position() + toRead);
+ buf.put(outBuffer);
+ outBuffer.limit(limit);
+ return toRead;
+ } else {
+ buf.put(outBuffer);
+ return unread;
+ }
+ }
+
+ /**
+ * Seeks the stream to a specific position relative to start of the under
+ * layer stream.
+ *
+ * @param position the given position in the data.
+ * @throws IOException if an I/O error occurs.
+ */
+ public void seek(long position) throws IOException {
+ Utils.checkArgument(position >= 0, "Cannot seek to negative offset.");
+ checkStream();
+ /*
+ * If data of target pos in the underlying stream has already been read
+ * and decrypted in outBuffer, we just need to re-position outBuffer.
+ */
+ if (position >= getStreamPosition() && position <= getStreamOffset()) {
+ int forward = (int) (position - getStreamPosition());
+ if (forward > 0) {
+ outBuffer.position(outBuffer.position() + forward);
+ }
+ } else {
+ input.seek(position);
+ resetStreamOffset(position);
+ }
+ }
+
+ /**
+ * Gets the offset of the stream.
+ *
+ * @return the stream offset.
+ */
+ protected long getStreamOffset() {
+ return streamOffset;
+ }
+
+ protected void setStreamOffset(long streamOffset) {
+ this.streamOffset = streamOffset;
+ }
+
+ /**
+ * Gets the position of the stream.
+ *
+ * @return the position of the stream.
+ */
+ protected long getStreamPosition() {
+ return streamOffset - outBuffer.remaining();
+ }
+
+ /**
+ * Decrypts more data by reading the under layer stream. The decrypted data
+ * will be put in the output buffer.
+ *
+ * @return The number of decrypted data. -1 if end of the decrypted stream.
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ protected int decryptMore() throws IOException {
+ int n = input.read(inBuffer);
+ if (n <= 0) {
+ return n;
+ }
+
+ streamOffset += n; // Read n bytes
decrypt();
padding = postDecryption(streamOffset);
- }
+ return outBuffer.remaining();
}
- // Copy decrypted data from outBuffer to buf
- unread = outBuffer.remaining();
- final int toRead = buf.remaining();
- if (toRead <= unread) {
- final int limit = outBuffer.limit();
- outBuffer.limit(outBuffer.position() + toRead);
- buf.put(outBuffer);
- outBuffer.limit(limit);
- return toRead;
- } else {
- buf.put(outBuffer);
- return unread;
+ /**
+ * Does the decryption using inBuffer as input and outBuffer as output. Upon
+ * return, inBuffer is cleared; the decrypted data starts at
+ * outBuffer.position() and ends at outBuffer.limit().
+ *
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ protected void decrypt() throws IOException {
+ Utils.checkState(inBuffer.position() >= padding);
+ if (inBuffer.position() == padding) {
+ // There is no real data in inBuffer.
+ return;
+ }
+
+ inBuffer.flip();
+ outBuffer.clear();
+ decryptBuffer(outBuffer);
+ inBuffer.clear();
+ outBuffer.flip();
+
+ if (padding > 0) {
+ /*
+ * The plain text and cipher text have a 1:1 mapping, they start at
+ * the same position.
+ */
+ outBuffer.position(padding);
+ }
}
- }
-
- /**
- * Seeks the stream to a specific position relative to start of the under layer stream.
- *
- * @param position the given position in the data.
- * @throws IOException if an I/O error occurs.
- */
- public void seek(long position) throws IOException {
- Utils.checkArgument(position >= 0, "Cannot seek to negative offset.");
- checkStream();
- /*
- * If data of target pos in the underlying stream has already been read
- * and decrypted in outBuffer, we just need to re-position outBuffer.
- */
- if (position >= getStreamPosition() && position <= getStreamOffset()) {
- int forward = (int) (position - getStreamPosition());
- if (forward > 0) {
- outBuffer.position(outBuffer.position() + forward);
- }
- } else {
- input.seek(position);
- resetStreamOffset(position);
+
+ /**
+ * Does the decryption using inBuffer as input and buf as output. Upon
+ * return, inBuffer is cleared; the buf's position will be equal to
+ * <i>p</i> <tt>+</tt> <i>n</i> where <i>p</i> is the position
+ * before decryption, <i>n</i> is the number of bytes decrypted. The buf's
+ * limit will not have changed.
+ *
+ * @param buf The buffer into which bytes are to be transferred.
+ * @throws IOException if an I/O error occurs.
+ */
+ protected void decryptInPlace(ByteBuffer buf) throws IOException {
+ Utils.checkState(inBuffer.position() >= padding);
+ Utils.checkState(buf.isDirect());
+ Utils.checkState(buf.remaining() >= inBuffer.position());
+ Utils.checkState(padding == 0);
+
+ if (inBuffer.position() == padding) {
+ // There is no real data in inBuffer.
+ return;
+ }
+ inBuffer.flip();
+ decryptBuffer(buf);
+ inBuffer.clear();
}
- }
-
- /**
- * Gets the offset of the stream.
- *
- * @return the stream offset.
- */
- protected long getStreamOffset() {
- return streamOffset;
- }
-
- protected void setStreamOffset(long streamOffset) {
- this.streamOffset = streamOffset;
- }
-
- /**
- * Gets the position of the stream.
- *
- * @return the position of the stream.
- */
- protected long getStreamPosition() {
- return streamOffset - outBuffer.remaining();
- }
-
- /**
- * Decrypts more data by reading the under layer stream. The decrypted data will
- * be put in the output buffer.
- *
- * @return The number of decrypted data. -1 if end of the decrypted stream.
- * @throws IOException if an I/O error occurs.
- */
- @Override
- protected int decryptMore() throws IOException {
- int n = input.read(inBuffer);
- if (n <= 0) {
- return n;
+
+ /**
+ * Decrypts all data in buf: total n bytes from given start position. Output
+ * is also buf and same start position. buf.position() and buf.limit()
+ * should be unchanged after decryption.
+ *
+ * @param buf The buffer into which bytes are to be transferred.
+ * @param offset the start offset in the data.
+ * @param len the the maximum number of decrypted data bytes to read.
+ * @throws IOException if an I/O error occurs.
+ */
+ protected void decrypt(ByteBuffer buf, int offset, int len)
+ throws IOException {
+ final int pos = buf.position();
+ final int limit = buf.limit();
+ int n = 0;
+ while (n < len) {
+ buf.position(offset + n);
+ buf.limit(offset + n + Math.min(len - n, inBuffer.remaining()));
+ inBuffer.put(buf);
+ // Do decryption
+ try {
+ decrypt();
+ buf.position(offset + n);
+ buf.limit(limit);
+ n += outBuffer.remaining();
+ buf.put(outBuffer);
+ } finally {
+ padding = postDecryption(streamOffset - (len - n));
+ }
+ }
+ buf.position(pos);
}
- streamOffset += n; // Read n bytes
- decrypt();
- padding = postDecryption(streamOffset);
- return outBuffer.remaining();
- }
-
- /**
- * Does the decryption using inBuffer as input and outBuffer as output.
- * Upon return, inBuffer is cleared; the decrypted data starts at
- * outBuffer.position() and ends at outBuffer.limit().
- *
- * @throws IOException if an I/O error occurs.
- */
- @Override
- protected void decrypt() throws IOException {
- Utils.checkState(inBuffer.position() >= padding);
- if(inBuffer.position() == padding) {
- // There is no real data in inBuffer.
- return;
+ /**
+ * This method is executed immediately after decryption. Checks whether
+ * cipher should be updated and recalculate padding if needed.
+ *
+ * @param position the given position in the data..
+ * @return the byte.
+ * @throws IOException if an I/O error occurs.
+ */
+ protected byte postDecryption(long position) throws IOException {
+ byte padding = 0;
+ if (cipherReset) {
+ /*
+ * This code is generally not executed since the cipher usually
+ * maintains cipher context (e.g. the counter) internally. However,
+ * some implementations can't maintain context so a re-init is
+ * necessary after each decryption call.
+ */
+ resetCipher(position);
+ padding = getPadding(position);
+ inBuffer.position(padding);
+ }
+ return padding;
}
- inBuffer.flip();
- outBuffer.clear();
- decryptBuffer(outBuffer);
- inBuffer.clear();
- outBuffer.flip();
-
- if (padding > 0) {
- /*
- * The plain text and cipher text have a 1:1 mapping, they start at the
- * same position.
- */
- outBuffer.position(padding);
+ /**
+ * Gets the initialization vector.
+ *
+ * @return the initIV.
+ */
+ protected byte[] getInitIV() {
+ return initIV;
}
- }
-
- /**
- * Does the decryption using inBuffer as input and buf as output.
- * Upon return, inBuffer is cleared; the buf's position will be equal to
- * <i>p</i> <tt>+</tt> <i>n</i> where <i>p</i> is the position before
- * decryption, <i>n</i> is the number of bytes decrypted.
- * The buf's limit will not have changed.
- *
- * @param buf The buffer into which bytes are to be transferred.
- * @throws IOException if an I/O error occurs.
- */
- protected void decryptInPlace(ByteBuffer buf) throws IOException {
- Utils.checkState(inBuffer.position() >= padding);
- Utils.checkState(buf.isDirect());
- Utils.checkState(buf.remaining() >= inBuffer.position());
- Utils.checkState(padding == 0);
-
- if(inBuffer.position() == padding) {
- // There is no real data in inBuffer.
- return;
+
+ /**
+ * Gets the counter for input stream position.
+ *
+ * @param position the given position in the data.
+ * @return the counter for input stream position.
+ */
+ protected long getCounter(long position) {
+ return position / cipher.getTransformation().getAlgorithmBlockSize();
}
- inBuffer.flip();
- decryptBuffer(buf);
- inBuffer.clear();
- }
-
- /**
- * Decrypts all data in buf: total n bytes from given start position.
- * Output is also buf and same start position.
- * buf.position() and buf.limit() should be unchanged after decryption.
- *
- * @param buf The buffer into which bytes are to be transferred.
- * @param offset the start offset in the data.
- * @param len the the maximum number of decrypted data bytes to read.
- * @throws IOException if an I/O error occurs.
- */
- protected void decrypt(ByteBuffer buf, int offset, int len)
- throws IOException {
- final int pos = buf.position();
- final int limit = buf.limit();
- int n = 0;
- while (n < len) {
- buf.position(offset + n);
- buf.limit(offset + n + Math.min(len - n, inBuffer.remaining()));
- inBuffer.put(buf);
- // Do decryption
- try {
- decrypt();
- buf.position(offset + n);
- buf.limit(limit);
- n += outBuffer.remaining();
- buf.put(outBuffer);
- } finally {
- padding = postDecryption(streamOffset - (len - n));
- }
+
+ /**
+ * Gets the padding for input stream position.
+ *
+ * @param position the given position in the data.
+ * @return the padding for input stream position.
+ */
+ protected byte getPadding(long position) {
+ return (byte) (position % cipher.getTransformation()
+ .getAlgorithmBlockSize());
}
- buf.position(pos);
- }
-
- /**
- * This method is executed immediately after decryption. Checks whether
- * cipher should be updated and recalculate padding if needed.
- *
- * @param position the given position in the data..
- * @return the byte.
- * @throws IOException if an I/O error occurs.
- */
- protected byte postDecryption(long position) throws IOException {
- byte padding = 0;
- if (cipherReset) {
- /*
- * This code is generally not executed since the cipher usually
- * maintains cipher context (e.g. the counter) internally. However,
- * some implementations can't maintain context so a re-init is necessary
- * after each decryption call.
- */
- resetCipher(position);
- padding = getPadding(position);
- inBuffer.position(padding);
+
+ /**
+ * Overrides the {@link CTRCryptoInputStream#initCipher()}. Initializes the
+ * cipher.
+ */
+ @Override
+ protected void initCipher() {
+ // Do nothing for initCipher
+ // Will reset the cipher when reset the stream offset
}
- return padding;
- }
-
- /**
- * Gets the initialization vector.
- *
- * @return the initIV.
- */
- protected byte[] getInitIV() {
- return initIV;
- }
-
- /**
- * Gets the counter for input stream position.
- *
- * @param position the given position in the data.
- * @return the counter for input stream position.
- */
- protected long getCounter(long position) {
- return position / cipher.getTransformation().getAlgorithmBlockSize();
- }
-
- /**
- * Gets the padding for input stream position.
- *
- * @param position the given position in the data.
- * @return the padding for input stream position.
- */
- protected byte getPadding(long position) {
- return (byte)(position % cipher.getTransformation().getAlgorithmBlockSize());
- }
-
- /**
- * Overrides the {@link CTRCryptoInputStream#initCipher()}.
- * Initializes the cipher.
- */
- @Override
- protected void initCipher() {
- // Do nothing for initCipher
- // Will reset the cipher when reset the stream offset
- }
-
- /**
- * Calculates the counter and iv, resets the cipher.
- *
- * @param position the given position in the data.
- * @throws IOException if an I/O error occurs.
- */
- protected void resetCipher(long position)
- throws IOException {
- final long counter = getCounter(position);
- Utils.calculateIV(initIV, counter, iv);
- try {
- cipher.init(CryptoCipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
- } catch (InvalidKeyException e) {
- throw new IOException(e);
- } catch (InvalidAlgorithmParameterException e) {
- throw new IOException(e);
+
+ /**
+ * Calculates the counter and iv, resets the cipher.
+ *
+ * @param position the given position in the data.
+ * @throws IOException if an I/O error occurs.
+ */
+ protected void resetCipher(long position) throws IOException {
+ final long counter = getCounter(position);
+ Utils.calculateIV(initIV, counter, iv);
+ try {
+ cipher.init(CryptoCipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
+ } catch (InvalidKeyException e) {
+ throw new IOException(e);
+ } catch (InvalidAlgorithmParameterException e) {
+ throw new IOException(e);
+ }
+ cipherReset = false;
}
- cipherReset = false;
- }
-
- /**
- * Resets the underlying stream offset; clear {@link #inBuffer} and
- * {@link #outBuffer}. This Typically happens during {@link #skip(long)}.
- *
- * @param offset the offset of the stream.
- * @throws IOException if an I/O error occurs.
- */
- protected void resetStreamOffset(long offset) throws IOException {
- streamOffset = offset;
- inBuffer.clear();
- outBuffer.clear();
- outBuffer.limit(0);
- resetCipher(offset);
- padding = getPadding(offset);
- inBuffer.position(padding); // Set proper position for input data.
- }
-
- /**
- * Does the decryption using out as output.
- *
- * @param out the output ByteBuffer.
- * @throws IOException if an I/O error occurs.
- */
- protected void decryptBuffer(ByteBuffer out)
- throws IOException {
- int inputSize = inBuffer.remaining();
- try {
- int n = cipher.update(inBuffer, out);
- if (n < inputSize) {
- /**
- * Typically code will not get here. CryptoCipher#update will consume all
- * input data and put result in outBuffer.
- * CryptoCipher#doFinal will reset the cipher context.
- */
- cipher.doFinal(inBuffer, out);
- cipherReset = true;
- }
- } catch (ShortBufferException e) {
- throw new IOException(e);
- } catch (IllegalBlockSizeException e) {
- throw new IOException(e);
- } catch (BadPaddingException e) {
- throw new IOException(e);
+
+ /**
+ * Resets the underlying stream offset; clear {@link #inBuffer} and
+ * {@link #outBuffer}. This Typically happens during {@link #skip(long)}.
+ *
+ * @param offset the offset of the stream.
+ * @throws IOException if an I/O error occurs.
+ */
+ protected void resetStreamOffset(long offset) throws IOException {
+ streamOffset = offset;
+ inBuffer.clear();
+ outBuffer.clear();
+ outBuffer.limit(0);
+ resetCipher(offset);
+ padding = getPadding(offset);
+ inBuffer.position(padding); // Set proper position for input data.
+ }
+
+ /**
+ * Does the decryption using out as output.
+ *
+ * @param out the output ByteBuffer.
+ * @throws IOException if an I/O error occurs.
+ */
+ protected void decryptBuffer(ByteBuffer out) throws IOException {
+ int inputSize = inBuffer.remaining();
+ try {
+ int n = cipher.update(inBuffer, out);
+ if (n < inputSize) {
+ /**
+ * Typically code will not get here. CryptoCipher#update will
+ * consume all input data and put result in outBuffer.
+ * CryptoCipher#doFinal will reset the cipher context.
+ */
+ cipher.doFinal(inBuffer, out);
+ cipherReset = true;
+ }
+ } catch (ShortBufferException e) {
+ throw new IOException(e);
+ } catch (IllegalBlockSizeException e) {
+ throw new IOException(e);
+ } catch (BadPaddingException e) {
+ throw new IOException(e);
+ }
}
- }
}
[4/7] commons-crypto git commit: CRYPTO-37: Change all the 2 spaces
indent to 4 to comply Commons code style
Posted by xu...@apache.org.
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/stream/PositionedCryptoInputStream.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/stream/PositionedCryptoInputStream.java b/src/main/java/org/apache/commons/crypto/stream/PositionedCryptoInputStream.java
index 255e57e..a962215 100644
--- a/src/main/java/org/apache/commons/crypto/stream/PositionedCryptoInputStream.java
+++ b/src/main/java/org/apache/commons/crypto/stream/PositionedCryptoInputStream.java
@@ -40,324 +40,326 @@ import org.apache.commons.crypto.utils.Utils;
import static org.apache.commons.crypto.cipher.CipherTransformation.AES_CTR_NOPADDING;
/**
- * PositionedCryptoInputStream provides the capability to decrypt the stream starting
- * at random position as well as provides the foundation for positioned read for
- * decrypting. This needs a stream cipher mode such as AES CTR mode.
+ * PositionedCryptoInputStream provides the capability to decrypt the stream
+ * starting at random position as well as provides the foundation for positioned
+ * read for decrypting. This needs a stream cipher mode such as AES CTR mode.
*/
public class PositionedCryptoInputStream extends CTRCryptoInputStream {
- /**
- * DirectBuffer pool
- */
- private final Queue<ByteBuffer> bufferPool = new
- ConcurrentLinkedQueue<ByteBuffer>();
-
- /**
- * CryptoCipher pool
- */
- private final Queue<CipherState> cipherPool = new
- ConcurrentLinkedQueue<CipherState>();
-
- /**
- * Constructs a {@link PositionedCryptoInputStream}.
- *
- * @param props The <code>Properties</code> class represents a set of
- * properties.
- * @param in the input data.
- * @param key crypto key for the cipher.
- * @param iv Initialization vector for the cipher.
- * @param streamOffset the start offset in the data.
- * @throws IOException if an I/O error occurs.
- */
- public PositionedCryptoInputStream(Properties props, Input in, byte[] key,
- byte[] iv, long streamOffset) throws IOException {
- this(in, Utils.getCipherInstance(AES_CTR_NOPADDING, props),
- Utils.getBufferSize(props), key, iv, streamOffset);
- }
-
- /**
- * Constructs a {@link PositionedCryptoInputStream}.
- *
- * @param input the input data.
- * @param cipher the CryptoCipher instance.
- * @param bufferSize the bufferSize.
- * @param key crypto key for the cipher.
- * @param iv Initialization vector for the cipher.
- * @param streamOffset the start offset in the data.
- * @throws IOException if an I/O error occurs.
- */
- public PositionedCryptoInputStream(Input input, CryptoCipher cipher, int bufferSize,
- byte[] key, byte[] iv, long streamOffset) throws IOException {
- super(input, cipher, bufferSize, key, iv, streamOffset);
- }
-
- /**
- * Reads up to the specified number of bytes from a given position
- * within a stream and return the number of bytes read. This does not
- * change the current offset of the stream, and is thread-safe.
- *
- * @param buffer the buffer into which the data is read.
- * @param length the maximum number of bytes to read.
- * @param offset the start offset in the data.
- * @param position the offset from the start of the stream.
- * @throws IOException if an I/O error occurs.
- * @return int the total number of decrypted data bytes read into the buffer.
- */
- public int read(long position, byte[] buffer, int offset, int length)
- throws IOException {
- checkStream();
- final int n = input.read(position, buffer, offset, length);
- if (n > 0) {
- // This operation does not change the current offset of the file
- decrypt(position, buffer, offset, n);
+ /**
+ * DirectBuffer pool
+ */
+ private final Queue<ByteBuffer> bufferPool = new ConcurrentLinkedQueue<ByteBuffer>();
+
+ /**
+ * CryptoCipher pool
+ */
+ private final Queue<CipherState> cipherPool = new ConcurrentLinkedQueue<CipherState>();
+
+ /**
+ * Constructs a {@link PositionedCryptoInputStream}.
+ *
+ * @param props The <code>Properties</code> class represents a set of
+ * properties.
+ * @param in the input data.
+ * @param key crypto key for the cipher.
+ * @param iv Initialization vector for the cipher.
+ * @param streamOffset the start offset in the data.
+ * @throws IOException if an I/O error occurs.
+ */
+ public PositionedCryptoInputStream(Properties props, Input in, byte[] key,
+ byte[] iv, long streamOffset) throws IOException {
+ this(in, Utils.getCipherInstance(AES_CTR_NOPADDING, props), Utils
+ .getBufferSize(props), key, iv, streamOffset);
}
- return n;
- }
-
- /**
- * Reads the specified number of bytes from a given position within a stream.
- * This does not change the current offset of the stream and is thread-safe.
- *
- * @param buffer the buffer into which the data is read.
- * @param length the maximum number of bytes to read.
- * @param offset the start offset in the data.
- * @param position the offset from the start of the stream.
- * @throws IOException if an I/O error occurs.
- */
- public void readFully(long position, byte[] buffer, int offset, int length)
- throws IOException {
- checkStream();
- IOUtils.readFully(input, position, buffer, offset, length);
- if (length > 0) {
- // This operation does not change the current offset of the file
- decrypt(position, buffer, offset, length);
+
+ /**
+ * Constructs a {@link PositionedCryptoInputStream}.
+ *
+ * @param input the input data.
+ * @param cipher the CryptoCipher instance.
+ * @param bufferSize the bufferSize.
+ * @param key crypto key for the cipher.
+ * @param iv Initialization vector for the cipher.
+ * @param streamOffset the start offset in the data.
+ * @throws IOException if an I/O error occurs.
+ */
+ public PositionedCryptoInputStream(Input input, CryptoCipher cipher,
+ int bufferSize, byte[] key, byte[] iv, long streamOffset)
+ throws IOException {
+ super(input, cipher, bufferSize, key, iv, streamOffset);
}
- }
-
- /**
- * Reads the specified number of bytes from a given position within a stream.
- * This does not change the current offset of the stream and is thread-safe.
- *
- * @param position the offset from the start of the stream.
- * @param buffer the buffer into which the data is read.
- * @throws IOException if an I/O error occurs.
- */
- public void readFully(long position, byte[] buffer) throws IOException {
- readFully(position, buffer, 0, buffer.length);
- }
-
- /**
- * Decrypts length bytes in buffer starting at offset. Output is also put
- * into buffer starting at offset. It is thread-safe.
- *
- * @param buffer the buffer into which the data is read.
- * @param offset the start offset in the data.
- * @param position the offset from the start of the stream.
- * @param length the maximum number of bytes to read.
- * @throws IOException if an I/O error occurs.
- */
- protected void decrypt(long position, byte[] buffer, int offset, int length)
- throws IOException {
- ByteBuffer inBuffer = getBuffer();
- ByteBuffer outBuffer = getBuffer();
- CipherState state = null;
- try {
- state = getCipherState();
- byte[] iv = getInitIV().clone();
- resetCipher(state, position, iv);
- byte padding = getPadding(position);
- inBuffer.position(padding); // Set proper position for input data.
-
- int n = 0;
- while (n < length) {
- int toDecrypt = Math.min(length - n, inBuffer.remaining());
- inBuffer.put(buffer, offset + n, toDecrypt);
-
- // Do decryption
- decrypt(state, inBuffer, outBuffer, padding);
-
- outBuffer.get(buffer, offset + n, toDecrypt);
- n += toDecrypt;
- padding = postDecryption(state, inBuffer, position + n, iv);
- }
- } finally {
- returnBuffer(inBuffer);
- returnBuffer(outBuffer);
- returnCipherState(state);
+
+ /**
+ * Reads up to the specified number of bytes from a given position within a
+ * stream and return the number of bytes read. This does not change the
+ * current offset of the stream, and is thread-safe.
+ *
+ * @param buffer the buffer into which the data is read.
+ * @param length the maximum number of bytes to read.
+ * @param offset the start offset in the data.
+ * @param position the offset from the start of the stream.
+ * @throws IOException if an I/O error occurs.
+ * @return int the total number of decrypted data bytes read into the
+ * buffer.
+ */
+ public int read(long position, byte[] buffer, int offset, int length)
+ throws IOException {
+ checkStream();
+ final int n = input.read(position, buffer, offset, length);
+ if (n > 0) {
+ // This operation does not change the current offset of the file
+ decrypt(position, buffer, offset, n);
+ }
+ return n;
}
- }
-
- /**
- * Does the decryption using inBuffer as input and outBuffer as output.
- * Upon return, inBuffer is cleared; the decrypted data starts at
- * outBuffer.position() and ends at outBuffer.limit()
- */
- private void decrypt(CipherState state, ByteBuffer inBuffer,
- ByteBuffer outBuffer, byte padding) throws IOException {
- Utils.checkState(inBuffer.position() >= padding);
- if(inBuffer.position() == padding) {
- // There is no real data in inBuffer.
- return;
+
+ /**
+ * Reads the specified number of bytes from a given position within a
+ * stream. This does not change the current offset of the stream and is
+ * thread-safe.
+ *
+ * @param buffer the buffer into which the data is read.
+ * @param length the maximum number of bytes to read.
+ * @param offset the start offset in the data.
+ * @param position the offset from the start of the stream.
+ * @throws IOException if an I/O error occurs.
+ */
+ public void readFully(long position, byte[] buffer, int offset, int length)
+ throws IOException {
+ checkStream();
+ IOUtils.readFully(input, position, buffer, offset, length);
+ if (length > 0) {
+ // This operation does not change the current offset of the file
+ decrypt(position, buffer, offset, length);
+ }
}
- inBuffer.flip();
- outBuffer.clear();
- decryptBuffer(state, inBuffer, outBuffer);
- inBuffer.clear();
- outBuffer.flip();
- if (padding > 0) {
- /*
- * The plain text and cipher text have a 1:1 mapping, they start at the
- * same position.
- */
- outBuffer.position(padding);
+
+ /**
+ * Reads the specified number of bytes from a given position within a
+ * stream. This does not change the current offset of the stream and is
+ * thread-safe.
+ *
+ * @param position the offset from the start of the stream.
+ * @param buffer the buffer into which the data is read.
+ * @throws IOException if an I/O error occurs.
+ */
+ public void readFully(long position, byte[] buffer) throws IOException {
+ readFully(position, buffer, 0, buffer.length);
}
- }
-
- private void decryptBuffer(CipherState state, ByteBuffer inBuffer, ByteBuffer outBuffer)
- throws IOException {
- int inputSize = inBuffer.remaining();
- try {
- int n = state.getCipher().update(inBuffer, outBuffer);
- if (n < inputSize) {
- /**
- * Typically code will not get here. CryptoCipher#update will consume all
- * input data and put result in outBuffer.
- * CryptoCipher#doFinal will reset the cipher context.
- */
- state.getCipher().doFinal(inBuffer, outBuffer);
- state.reset(true);
- }
- } catch (ShortBufferException e) {
- throw new IOException(e);
- } catch (IllegalBlockSizeException e) {
- throw new IOException(e);
- } catch (BadPaddingException e) {
- throw new IOException(e);
+
+ /**
+ * Decrypts length bytes in buffer starting at offset. Output is also put
+ * into buffer starting at offset. It is thread-safe.
+ *
+ * @param buffer the buffer into which the data is read.
+ * @param offset the start offset in the data.
+ * @param position the offset from the start of the stream.
+ * @param length the maximum number of bytes to read.
+ * @throws IOException if an I/O error occurs.
+ */
+ protected void decrypt(long position, byte[] buffer, int offset, int length)
+ throws IOException {
+ ByteBuffer inBuffer = getBuffer();
+ ByteBuffer outBuffer = getBuffer();
+ CipherState state = null;
+ try {
+ state = getCipherState();
+ byte[] iv = getInitIV().clone();
+ resetCipher(state, position, iv);
+ byte padding = getPadding(position);
+ inBuffer.position(padding); // Set proper position for input data.
+
+ int n = 0;
+ while (n < length) {
+ int toDecrypt = Math.min(length - n, inBuffer.remaining());
+ inBuffer.put(buffer, offset + n, toDecrypt);
+
+ // Do decryption
+ decrypt(state, inBuffer, outBuffer, padding);
+
+ outBuffer.get(buffer, offset + n, toDecrypt);
+ n += toDecrypt;
+ padding = postDecryption(state, inBuffer, position + n, iv);
+ }
+ } finally {
+ returnBuffer(inBuffer);
+ returnBuffer(outBuffer);
+ returnCipherState(state);
+ }
}
- }
-
- /**
- * This method is executed immediately after decryption. Check whether
- * cipher should be updated and recalculate padding if needed.
- */
- private byte postDecryption(CipherState state, ByteBuffer inBuffer,
- long position, byte[] iv) throws IOException {
- byte padding = 0;
- if (state.isReset()) {
- /*
- * This code is generally not executed since the cipher usually
- * maintains cipher context (e.g. the counter) internally. However,
- * some implementations can't maintain context so a re-init is necessary
- * after each decryption call.
- */
- resetCipher(state, position, iv);
- padding = getPadding(position);
- inBuffer.position(padding);
+
+ /**
+ * Does the decryption using inBuffer as input and outBuffer as output. Upon
+ * return, inBuffer is cleared; the decrypted data starts at
+ * outBuffer.position() and ends at outBuffer.limit()
+ */
+ private void decrypt(CipherState state, ByteBuffer inBuffer,
+ ByteBuffer outBuffer, byte padding) throws IOException {
+ Utils.checkState(inBuffer.position() >= padding);
+ if (inBuffer.position() == padding) {
+ // There is no real data in inBuffer.
+ return;
+ }
+ inBuffer.flip();
+ outBuffer.clear();
+ decryptBuffer(state, inBuffer, outBuffer);
+ inBuffer.clear();
+ outBuffer.flip();
+ if (padding > 0) {
+ /*
+ * The plain text and cipher text have a 1:1 mapping, they start at
+ * the same position.
+ */
+ outBuffer.position(padding);
+ }
}
- return padding;
- }
-
- /** Calculate the counter and iv, reset the cipher. */
- private void resetCipher(CipherState state, long position, byte[] iv)
- throws IOException {
- final long counter = getCounter(position);
- Utils.calculateIV(getInitIV(), counter, iv);
- try {
- state.getCipher().init(CryptoCipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
- } catch (InvalidKeyException e) {
- throw new IOException(e);
- } catch (InvalidAlgorithmParameterException e) {
- throw new IOException(e);
+
+ private void decryptBuffer(CipherState state, ByteBuffer inBuffer,
+ ByteBuffer outBuffer) throws IOException {
+ int inputSize = inBuffer.remaining();
+ try {
+ int n = state.getCipher().update(inBuffer, outBuffer);
+ if (n < inputSize) {
+ /**
+ * Typically code will not get here. CryptoCipher#update will
+ * consume all input data and put result in outBuffer.
+ * CryptoCipher#doFinal will reset the cipher context.
+ */
+ state.getCipher().doFinal(inBuffer, outBuffer);
+ state.reset(true);
+ }
+ } catch (ShortBufferException e) {
+ throw new IOException(e);
+ } catch (IllegalBlockSizeException e) {
+ throw new IOException(e);
+ } catch (BadPaddingException e) {
+ throw new IOException(e);
+ }
}
- state.reset(false);
- }
-
- /** Get CryptoCipher from pool */
- private CipherState getCipherState() throws IOException {
- CipherState state = cipherPool.poll();
- if (state == null) {
- CryptoCipher cipher;
- try {
- cipher = CryptoCipherFactory.getInstance(getCipher().getTransformation(),
- getCipher().getProperties());
- } catch (GeneralSecurityException e) {
- throw new IOException(e);
- }
- state = new CipherState(cipher);
+
+ /**
+ * This method is executed immediately after decryption. Check whether
+ * cipher should be updated and recalculate padding if needed.
+ */
+ private byte postDecryption(CipherState state, ByteBuffer inBuffer,
+ long position, byte[] iv) throws IOException {
+ byte padding = 0;
+ if (state.isReset()) {
+ /*
+ * This code is generally not executed since the cipher usually
+ * maintains cipher context (e.g. the counter) internally. However,
+ * some implementations can't maintain context so a re-init is
+ * necessary after each decryption call.
+ */
+ resetCipher(state, position, iv);
+ padding = getPadding(position);
+ inBuffer.position(padding);
+ }
+ return padding;
}
- return state;
- }
+ /** Calculate the counter and iv, reset the cipher. */
+ private void resetCipher(CipherState state, long position, byte[] iv)
+ throws IOException {
+ final long counter = getCounter(position);
+ Utils.calculateIV(getInitIV(), counter, iv);
+ try {
+ state.getCipher().init(CryptoCipher.DECRYPT_MODE, key,
+ new IvParameterSpec(iv));
+ } catch (InvalidKeyException e) {
+ throw new IOException(e);
+ } catch (InvalidAlgorithmParameterException e) {
+ throw new IOException(e);
+ }
+ state.reset(false);
+ }
- /** Return CryptoCipher to pool */
- private void returnCipherState(CipherState state) {
- if (state != null) {
- cipherPool.add(state);
+ /** Get CryptoCipher from pool */
+ private CipherState getCipherState() throws IOException {
+ CipherState state = cipherPool.poll();
+ if (state == null) {
+ CryptoCipher cipher;
+ try {
+ cipher = CryptoCipherFactory.getInstance(getCipher()
+ .getTransformation(), getCipher().getProperties());
+ } catch (GeneralSecurityException e) {
+ throw new IOException(e);
+ }
+ state = new CipherState(cipher);
+ }
+
+ return state;
}
- }
- /** Get direct buffer from pool */
- private ByteBuffer getBuffer() {
- ByteBuffer buffer = bufferPool.poll();
- if (buffer == null) {
- buffer = ByteBuffer.allocateDirect(getBufferSize());
+ /** Return CryptoCipher to pool */
+ private void returnCipherState(CipherState state) {
+ if (state != null) {
+ cipherPool.add(state);
+ }
}
- return buffer;
- }
+ /** Get direct buffer from pool */
+ private ByteBuffer getBuffer() {
+ ByteBuffer buffer = bufferPool.poll();
+ if (buffer == null) {
+ buffer = ByteBuffer.allocateDirect(getBufferSize());
+ }
- /** Return direct buffer to pool */
- private void returnBuffer(ByteBuffer buf) {
- if (buf != null) {
- buf.clear();
- bufferPool.add(buf);
+ return buffer;
}
- }
-
- /**
- * Overrides the {@link CryptoInputStream#close()}.
- * Closes this input stream and releases any system resources associated
- * with the stream.
- *
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public void close() throws IOException {
- if (!isOpen()) {
- return;
+
+ /** Return direct buffer to pool */
+ private void returnBuffer(ByteBuffer buf) {
+ if (buf != null) {
+ buf.clear();
+ bufferPool.add(buf);
+ }
}
- cleanBufferPool();
- super.close();
- }
+ /**
+ * Overrides the {@link CryptoInputStream#close()}. Closes this input stream
+ * and releases any system resources associated with the stream.
+ *
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public void close() throws IOException {
+ if (!isOpen()) {
+ return;
+ }
+
+ cleanBufferPool();
+ super.close();
+ }
- /** Clean direct buffer pool */
- private void cleanBufferPool() {
- ByteBuffer buf;
- while ((buf = bufferPool.poll()) != null) {
- Utils.freeDirectBuffer(buf);
+ /** Clean direct buffer pool */
+ private void cleanBufferPool() {
+ ByteBuffer buf;
+ while ((buf = bufferPool.poll()) != null) {
+ Utils.freeDirectBuffer(buf);
+ }
}
- }
- private class CipherState {
- private CryptoCipher cipher;
- private boolean reset;
+ private class CipherState {
+ private CryptoCipher cipher;
+ private boolean reset;
- public CipherState(CryptoCipher cipher) {
- this.cipher = cipher;
- this.reset = false;
- }
+ public CipherState(CryptoCipher cipher) {
+ this.cipher = cipher;
+ this.reset = false;
+ }
- public CryptoCipher getCipher() {
- return cipher;
- }
+ public CryptoCipher getCipher() {
+ return cipher;
+ }
- public boolean isReset() {
- return reset;
- }
+ public boolean isReset() {
+ return reset;
+ }
- public void reset(boolean reset) {
- this.reset = reset;
+ public void reset(boolean reset) {
+ this.reset = reset;
+ }
}
- }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/stream/input/ChannelInput.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/stream/input/ChannelInput.java b/src/main/java/org/apache/commons/crypto/stream/input/ChannelInput.java
index cdf13e6..dbcba57 100644
--- a/src/main/java/org/apache/commons/crypto/stream/input/ChannelInput.java
+++ b/src/main/java/org/apache/commons/crypto/stream/input/ChannelInput.java
@@ -23,143 +23,148 @@ import java.nio.channels.ReadableByteChannel;
/**
* The ChannelInput class takes a <code>ReadableByteChannel</code> object and
- * wraps it as <code>Input</code> object acceptable by <code>CryptoInputStream</code>.
+ * wraps it as <code>Input</code> object acceptable by
+ * <code>CryptoInputStream</code>.
*/
public class ChannelInput implements Input {
- private static final int SKIP_BUFFER_SIZE = 2048;
+ private static final int SKIP_BUFFER_SIZE = 2048;
- private ByteBuffer buf;
- private final ReadableByteChannel channel;
+ private ByteBuffer buf;
+ private final ReadableByteChannel channel;
- /**
- * Constructs the {@link org.apache.commons.crypto.stream.input.ChannelInput}.
- *
- * @param channel the ReadableByteChannel object.
- */
- public ChannelInput(
- ReadableByteChannel channel) {
- this.channel = channel;
- }
+ /**
+ * Constructs the
+ * {@link org.apache.commons.crypto.stream.input.ChannelInput}.
+ *
+ * @param channel the ReadableByteChannel object.
+ */
+ public ChannelInput(ReadableByteChannel channel) {
+ this.channel = channel;
+ }
- /**
- * Overrides the {@link org.apache.commons.crypto.stream.input.Input#read(ByteBuffer)}.
- * Reads a sequence of bytes from input into the given buffer.
- *
- * @param dst The buffer into which bytes are to be transferred.
- * @return the total number of bytes read into the buffer, or
- * <code>-1</code> if there is no more data because the end of
- * the stream has been reached.
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public int read(ByteBuffer dst) throws IOException {
- return channel.read(dst);
- }
+ /**
+ * Overrides the
+ * {@link org.apache.commons.crypto.stream.input.Input#read(ByteBuffer)}.
+ * Reads a sequence of bytes from input into the given buffer.
+ *
+ * @param dst The buffer into which bytes are to be transferred.
+ * @return the total number of bytes read into the buffer, or
+ * <code>-1</code> if there is no more data because the end of the
+ * stream has been reached.
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public int read(ByteBuffer dst) throws IOException {
+ return channel.read(dst);
+ }
- /**
- * Overrides the {@link org.apache.commons.crypto.stream.input.Input#skip(long)}.
- * Skips over and discards <code>n</code> bytes of data from this input
- * stream.
- *
- * @param n the number of bytes to be skipped.
- * @return the actual number of bytes skipped.
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public long skip(long n) throws IOException {
- long remaining = n;
- int nr;
+ /**
+ * Overrides the
+ * {@link org.apache.commons.crypto.stream.input.Input#skip(long)}. Skips
+ * over and discards <code>n</code> bytes of data from this input stream.
+ *
+ * @param n the number of bytes to be skipped.
+ * @return the actual number of bytes skipped.
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public long skip(long n) throws IOException {
+ long remaining = n;
+ int nr;
- if (n <= 0) {
- return 0;
- }
+ if (n <= 0) {
+ return 0;
+ }
- int size = (int)Math.min(SKIP_BUFFER_SIZE, remaining);
- ByteBuffer skipBuffer = getSkipBuf();
- while (remaining > 0) {
- skipBuffer.clear();
- skipBuffer.limit((int)Math.min(size, remaining));
- nr = read(skipBuffer);
- if (nr < 0) {
- break;
- }
- remaining -= nr;
- }
+ int size = (int) Math.min(SKIP_BUFFER_SIZE, remaining);
+ ByteBuffer skipBuffer = getSkipBuf();
+ while (remaining > 0) {
+ skipBuffer.clear();
+ skipBuffer.limit((int) Math.min(size, remaining));
+ nr = read(skipBuffer);
+ if (nr < 0) {
+ break;
+ }
+ remaining -= nr;
+ }
- return n - remaining;
- }
+ return n - remaining;
+ }
- /**
- * Overrides the {@link Input#available()}.
- * Returns an estimate of the number of bytes that can be read (or
- * skipped over) from this input stream without blocking by the next
- * invocation of a method for this input stream. The next invocation
- * might be the same thread or another thread. A single read or skip of this
- * many bytes will not block, but may read or skip fewer bytes.
- *
- * @return an estimate of the number of bytes that can be read (or skipped
- * over) from this input stream without blocking or {@code 0} when
- * it reaches the end of the input stream.
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public int available() throws IOException {
- return 0;
- }
+ /**
+ * Overrides the {@link Input#available()}. Returns an estimate of the
+ * number of bytes that can be read (or skipped over) from this input stream
+ * without blocking by the next invocation of a method for this input
+ * stream. The next invocation might be the same thread or another thread. A
+ * single read or skip of this many bytes will not block, but may read or
+ * skip fewer bytes.
+ *
+ * @return an estimate of the number of bytes that can be read (or skipped
+ * over) from this input stream without blocking or {@code 0} when
+ * it reaches the end of the input stream.
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public int available() throws IOException {
+ return 0;
+ }
- /**
- * Overrides the {@link org.apache.commons.crypto.stream.input.Input#read(long, byte[], int, int)}.
- * Reads up to <code>len</code> bytes of data from the input stream into
- * an array of bytes. An attempt is made to read as many as
- * <code>len</code> bytes, but a smaller number may be read.
- * The number of bytes actually read is returned as an integer.
- *
- * @param position the given position within a stream.
- * @param buffer the buffer into which the data is read.
- * @param offset the start offset in array buffer.
- * @param length the maximum number of bytes to read.
- * @return the total number of bytes read into the buffer, or
- * <code>-1</code> if there is no more data because the end of
- * the stream has been reached.
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public int read(long position, byte[] buffer, int offset, int length)
- throws IOException {
- throw new UnsupportedOperationException(
- "Positioned read is not supported by this implementation");
- }
+ /**
+ * Overrides the
+ * {@link org.apache.commons.crypto.stream.input.Input#read(long, byte[], int, int)}
+ * . Reads up to <code>len</code> bytes of data from the input stream into
+ * an array of bytes. An attempt is made to read as many as <code>len</code>
+ * bytes, but a smaller number may be read. The number of bytes actually
+ * read is returned as an integer.
+ *
+ * @param position the given position within a stream.
+ * @param buffer the buffer into which the data is read.
+ * @param offset the start offset in array buffer.
+ * @param length the maximum number of bytes to read.
+ * @return the total number of bytes read into the buffer, or
+ * <code>-1</code> if there is no more data because the end of the
+ * stream has been reached.
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public int read(long position, byte[] buffer, int offset, int length)
+ throws IOException {
+ throw new UnsupportedOperationException(
+ "Positioned read is not supported by this implementation");
+ }
- /**
- * Overrides the {@link org.apache.commons.crypto.stream.input.Input#seek(long)}.
- * Seeks to the given offset from the start of the stream.
- * The next read() will be from that location.
- *
- * @param position the offset from the start of the stream.
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public void seek(long position) throws IOException {
- throw new UnsupportedOperationException(
- "Seek is not supported by this implementation");
- }
+ /**
+ * Overrides the
+ * {@link org.apache.commons.crypto.stream.input.Input#seek(long)}. Seeks to
+ * the given offset from the start of the stream. The next read() will be
+ * from that location.
+ *
+ * @param position the offset from the start of the stream.
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public void seek(long position) throws IOException {
+ throw new UnsupportedOperationException(
+ "Seek is not supported by this implementation");
+ }
- /**
- * Overrides the {@link org.apache.commons.crypto.stream.input.Input#seek(long)}.
- * Closes this input and releases any system resources associated
- * with the under layer input.
- *
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public void close() throws IOException {
- channel.close();
- }
+ /**
+ * Overrides the
+ * {@link org.apache.commons.crypto.stream.input.Input#seek(long)}. Closes
+ * this input and releases any system resources associated with the under
+ * layer input.
+ *
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public void close() throws IOException {
+ channel.close();
+ }
- private ByteBuffer getSkipBuf() {
- if (buf == null) {
- buf = ByteBuffer.allocate(SKIP_BUFFER_SIZE);
+ private ByteBuffer getSkipBuf() {
+ if (buf == null) {
+ buf = ByteBuffer.allocate(SKIP_BUFFER_SIZE);
+ }
+ return buf;
}
- return buf;
- }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/stream/input/Input.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/stream/input/Input.java b/src/main/java/org/apache/commons/crypto/stream/input/Input.java
index 1657a7c..c8e2f63 100644
--- a/src/main/java/org/apache/commons/crypto/stream/input/Input.java
+++ b/src/main/java/org/apache/commons/crypto/stream/input/Input.java
@@ -21,113 +21,117 @@ import java.io.IOException;
import java.nio.ByteBuffer;
/**
- * The Input interface abstract the input source of <code>CryptoInputStream</code> so that
- * different implementation of input can be used. The implementation Input interface will usually
- * wraps an input mechanism such as <code>InputStream</code> or <code>ReadableByteChannel</code>.
+ * The Input interface abstract the input source of
+ * <code>CryptoInputStream</code> so that different implementation of input can
+ * be used. The implementation Input interface will usually wraps an input
+ * mechanism such as <code>InputStream</code> or
+ * <code>ReadableByteChannel</code>.
*/
public interface Input {
- /**
- * Reads a sequence of bytes from input into the given buffer.
- *
- * <p> An attempt is made to read up to <i>r</i> bytes from the input,
- * where <i>r</i> is the number of bytes remaining in the buffer, that is,
- * <tt>dst.remaining()</tt>, at the moment this method is invoked.
- *
- * <p> Suppose that a byte sequence of length <i>n</i> is read, where
- * <tt>0</tt> <tt><=</tt> <i>n</i> <tt><=</tt> <i>r</i>.
- * This byte sequence will be transferred into the buffer so that the first
- * byte in the sequence is at index <i>p</i> and the last byte is at index
- * <i>p</i> <tt>+</tt> <i>n</i> <tt>-</tt> <tt>1</tt>,
- * where <i>p</i> is the buffer's position at the moment this method is
- * invoked. Upon return the buffer's position will be equal to
- * <i>p</i> <tt>+</tt> <i>n</i>; its limit will not have changed.
- *
- * @param dst
- * The buffer into which bytes are to be transferred.
- * @return the total number of bytes read into the buffer, or
- * <code>-1</code> if there is no more data because the end of
- * the stream has been reached.
- * @throws IOException
- * If some other I/O error occurs.
- */
- int read(ByteBuffer dst) throws IOException;
+ /**
+ * Reads a sequence of bytes from input into the given buffer.
+ *
+ * <p>
+ * An attempt is made to read up to <i>r</i> bytes from the input, where
+ * <i>r</i> is the number of bytes remaining in the buffer, that is,
+ * <tt>dst.remaining()</tt>, at the moment this method is invoked.
+ *
+ * <p>
+ * Suppose that a byte sequence of length <i>n</i> is read, where <tt>0</tt>
+ * <tt><=</tt> <i>n</i> <tt><=</tt> <i>r</i>.
+ * This byte sequence will be transferred into the buffer so that the first
+ * byte in the sequence is at index <i>p</i> and the last byte is at index
+ * <i>p</i> <tt>+</tt> <i>n</i> <tt>-</tt> <tt>1</tt>,
+ * where <i>p</i> is the buffer's position at the moment this method is
+ * invoked. Upon return the buffer's position will be equal to
+ * <i>p</i> <tt>+</tt> <i>n</i>; its limit will not have changed.
+ *
+ * @param dst The buffer into which bytes are to be transferred.
+ * @return the total number of bytes read into the buffer, or
+ * <code>-1</code> if there is no more data because the end of the
+ * stream has been reached.
+ * @throws IOException If some other I/O error occurs.
+ */
+ int read(ByteBuffer dst) throws IOException;
- /**
- * Skips over and discards <code>n</code> bytes of data from this input
- * The <code>skip</code> method may, for a variety of reasons, end
- * up skipping over some smaller number of bytes, possibly <code>0</code>.
- * This may result from any of a number of conditions; reaching end of file
- * before <code>n</code> bytes have been skipped is only one possibility.
- * The actual number of bytes skipped is returned. If <code>n</code> is
- * negative, no bytes are skipped.
- *
- * <p> The <code>skip</code> method of this class creates a
- * byte array and then repeatedly reads into it until <code>n</code> bytes
- * have been read or the end of the stream has been reached. Subclasses are
- * encouraged to provide a more efficient implementation of this method.
- * For instance, the implementation may depend on the ability to seek.
- *
- * @param n the number of bytes to be skipped.
- * @return the actual number of bytes skipped.
- * @exception IOException if the stream does not support seek,
- * or if some other I/O error occurs.
- */
- long skip(long n) throws IOException;
+ /**
+ * Skips over and discards <code>n</code> bytes of data from this input The
+ * <code>skip</code> method may, for a variety of reasons, end up skipping
+ * over some smaller number of bytes, possibly <code>0</code>. This may
+ * result from any of a number of conditions; reaching end of file before
+ * <code>n</code> bytes have been skipped is only one possibility. The
+ * actual number of bytes skipped is returned. If <code>n</code> is
+ * negative, no bytes are skipped.
+ *
+ * <p>
+ * The <code>skip</code> method of this class creates a byte array and then
+ * repeatedly reads into it until <code>n</code> bytes have been read or the
+ * end of the stream has been reached. Subclasses are encouraged to provide
+ * a more efficient implementation of this method. For instance, the
+ * implementation may depend on the ability to seek.
+ *
+ * @param n the number of bytes to be skipped.
+ * @return the actual number of bytes skipped.
+ * @exception IOException if the stream does not support seek, or if some
+ * other I/O error occurs.
+ */
+ long skip(long n) throws IOException;
- /**
- * Returns an estimate of the number of bytes that can be read (or
- * skipped over) from this input without blocking by the next
- * invocation of a method for this input stream. The next invocation
- * might be the same thread or another thread. A single read or skip of this
- * many bytes will not block, but may read or skip fewer bytes.
- *
- * <p> It is never correct to use the return value of this method to allocate
- * a buffer intended to hold all data in this stream.
- *
- * @return an estimate of the number of bytes that can be read (or skipped
- * over) from this input stream without blocking or {@code 0} when
- * it reaches the end of the input stream.
- * @exception IOException if an I/O error occurs.
- */
- int available() throws IOException;
+ /**
+ * Returns an estimate of the number of bytes that can be read (or skipped
+ * over) from this input without blocking by the next invocation of a method
+ * for this input stream. The next invocation might be the same thread or
+ * another thread. A single read or skip of this many bytes will not block,
+ * but may read or skip fewer bytes.
+ *
+ * <p>
+ * It is never correct to use the return value of this method to allocate a
+ * buffer intended to hold all data in this stream.
+ *
+ * @return an estimate of the number of bytes that can be read (or skipped
+ * over) from this input stream without blocking or {@code 0} when
+ * it reaches the end of the input stream.
+ * @exception IOException if an I/O error occurs.
+ */
+ int available() throws IOException;
- /**
- * Reads up to the specified number of bytes from a given position within a
- * stream and return the number of bytes read.
- * This does not change the current offset of the stream and is thread-safe.
- *
- * An implementation may not support positioned read. If the implementation
- * doesn't support positioned read, it throws UnsupportedOperationException.
- *
- * @param position the given position within a stream.
- * @param buffer the buffer into which the data is read.
- * @param offset the start offset in array buffer.
- * @param length the maximum number of bytes to read.
- * @return the total number of bytes read into the buffer, or
- * <code>-1</code> if there is no more data because the end of
- * the stream has been reached.
- * @throws IOException if an I/O error occurs.
- */
- int read(long position, byte[] buffer, int offset, int length)
- throws IOException;
+ /**
+ * Reads up to the specified number of bytes from a given position within a
+ * stream and return the number of bytes read. This does not change the
+ * current offset of the stream and is thread-safe.
+ *
+ * An implementation may not support positioned read. If the implementation
+ * doesn't support positioned read, it throws UnsupportedOperationException.
+ *
+ * @param position the given position within a stream.
+ * @param buffer the buffer into which the data is read.
+ * @param offset the start offset in array buffer.
+ * @param length the maximum number of bytes to read.
+ * @return the total number of bytes read into the buffer, or
+ * <code>-1</code> if there is no more data because the end of the
+ * stream has been reached.
+ * @throws IOException if an I/O error occurs.
+ */
+ int read(long position, byte[] buffer, int offset, int length)
+ throws IOException;
- /**
- * Seeks to the given offset from the start of the stream.
- * The next read() will be from that location.
- *
- * An implementation may not support seek. If the implementation
- * doesn't support seek, it throws UnsupportedOperationException.
- *
- * @param position the offset from the start of the stream.
- * @throws IOException if an I/O error occurs.
- */
- void seek(long position) throws IOException;
+ /**
+ * Seeks to the given offset from the start of the stream. The next read()
+ * will be from that location.
+ *
+ * An implementation may not support seek. If the implementation doesn't
+ * support seek, it throws UnsupportedOperationException.
+ *
+ * @param position the offset from the start of the stream.
+ * @throws IOException if an I/O error occurs.
+ */
+ void seek(long position) throws IOException;
- /**
- * Closes this input and releases any system resources associated
- * with the under layer input.
- *
- * @exception IOException if an I/O error occurs.
- */
- void close() throws IOException;
+ /**
+ * Closes this input and releases any system resources associated with the
+ * under layer input.
+ *
+ * @exception IOException if an I/O error occurs.
+ */
+ void close() throws IOException;
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/stream/input/StreamInput.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/stream/input/StreamInput.java b/src/main/java/org/apache/commons/crypto/stream/input/StreamInput.java
index 20649de..cbbcb9a 100644
--- a/src/main/java/org/apache/commons/crypto/stream/input/StreamInput.java
+++ b/src/main/java/org/apache/commons/crypto/stream/input/StreamInput.java
@@ -22,136 +22,139 @@ import java.io.InputStream;
import java.nio.ByteBuffer;
/**
- * The StreamInput class takes a <code>InputStream</code> object and
- * wraps it as <code>Input</code> object acceptable by <code>CryptoInputStream</code>.
+ * The StreamInput class takes a <code>InputStream</code> object and wraps it as
+ * <code>Input</code> object acceptable by <code>CryptoInputStream</code>.
*/
public class StreamInput implements Input {
- private final byte[] buf;
- private final int bufferSize;
- final InputStream in;
+ private final byte[] buf;
+ private final int bufferSize;
+ final InputStream in;
- /**
- * Constructs a {@link org.apache.commons.crypto.stream.input.StreamInput}.
- *
- * @param inputStream the inputstream object.
- * @param bufferSize the buffersize.
- */
- public StreamInput(InputStream inputStream, int bufferSize) {
- this.in = inputStream;
- this.bufferSize = bufferSize;
- buf = new byte[bufferSize];
- }
+ /**
+ * Constructs a {@link org.apache.commons.crypto.stream.input.StreamInput}.
+ *
+ * @param inputStream the inputstream object.
+ * @param bufferSize the buffersize.
+ */
+ public StreamInput(InputStream inputStream, int bufferSize) {
+ this.in = inputStream;
+ this.bufferSize = bufferSize;
+ buf = new byte[bufferSize];
+ }
- /**
- * Overrides the {@link org.apache.commons.crypto.stream.input.Input#read(ByteBuffer)}.
- * Reads a sequence of bytes from input into the given buffer.
- *
- * @param dst
- * The buffer into which bytes are to be transferred.
- *
- * @return the total number of bytes read into the buffer, or
- * <code>-1</code> if there is no more data because the end of
- * the stream has been reached.
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public int read(ByteBuffer dst) throws IOException {
- int remaining = dst.remaining();
- int read = 0;
- while (remaining > 0) {
- final int n = in.read(buf, 0, Math.min(remaining, bufferSize));
- if (n == -1) {
- if (read == 0) {
- read = -1;
+ /**
+ * Overrides the
+ * {@link org.apache.commons.crypto.stream.input.Input#read(ByteBuffer)}.
+ * Reads a sequence of bytes from input into the given buffer.
+ *
+ * @param dst The buffer into which bytes are to be transferred.
+ *
+ * @return the total number of bytes read into the buffer, or
+ * <code>-1</code> if there is no more data because the end of the
+ * stream has been reached.
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public int read(ByteBuffer dst) throws IOException {
+ int remaining = dst.remaining();
+ int read = 0;
+ while (remaining > 0) {
+ final int n = in.read(buf, 0, Math.min(remaining, bufferSize));
+ if (n == -1) {
+ if (read == 0) {
+ read = -1;
+ }
+ break;
+ } else if (n > 0) {
+ dst.put(buf, 0, n);
+ read += n;
+ remaining -= n;
+ }
}
- break;
- } else if (n > 0) {
- dst.put(buf, 0, n);
- read += n;
- remaining -= n;
- }
+ return read;
}
- return read;
- }
- /**
- * Overrides the {@link org.apache.commons.crypto.stream.input.Input#skip(long)}.
- * Skips over and discards <code>n</code> bytes of data from this input
- * stream.
- *
- * @param n the number of bytes to be skipped.
- * @return the actual number of bytes skipped.
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public long skip(long n) throws IOException {
- return in.skip(n);
- }
+ /**
+ * Overrides the
+ * {@link org.apache.commons.crypto.stream.input.Input#skip(long)}. Skips
+ * over and discards <code>n</code> bytes of data from this input stream.
+ *
+ * @param n the number of bytes to be skipped.
+ * @return the actual number of bytes skipped.
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public long skip(long n) throws IOException {
+ return in.skip(n);
+ }
- /**
- * Overrides the {@link Input#available()}.
- * Returns an estimate of the number of bytes that can be read (or
- * skipped over) from this input stream without blocking by the next
- * invocation of a method for this input stream. The next invocation
- * might be the same thread or another thread. A single read or skip of this
- * many bytes will not block, but may read or skip fewer bytes.
- *
- * @return an estimate of the number of bytes that can be read (or skipped
- * over) from this input stream without blocking or {@code 0} when
- * it reaches the end of the input stream.
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public int available() throws IOException {
- return in.available();
- }
+ /**
+ * Overrides the {@link Input#available()}. Returns an estimate of the
+ * number of bytes that can be read (or skipped over) from this input stream
+ * without blocking by the next invocation of a method for this input
+ * stream. The next invocation might be the same thread or another thread. A
+ * single read or skip of this many bytes will not block, but may read or
+ * skip fewer bytes.
+ *
+ * @return an estimate of the number of bytes that can be read (or skipped
+ * over) from this input stream without blocking or {@code 0} when
+ * it reaches the end of the input stream.
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public int available() throws IOException {
+ return in.available();
+ }
- /**
- * Overrides the {@link org.apache.commons.crypto.stream.input.Input#read(long, byte[], int, int)}.
- * Reads up to <code>len</code> bytes of data from the input stream into
- * an array of bytes. An attempt is made to read as many as
- * <code>len</code> bytes, but a smaller number may be read.
- * The number of bytes actually read is returned as an integer.
- *
- * @param position the given position within a stream.
- * @param buffer the buffer into which the data is read.
- * @param offset the start offset in array buffer.
- * @param length the maximum number of bytes to read.
- * @return the total number of bytes read into the buffer, or
- * <code>-1</code> if there is no more data because the end of
- * the stream has been reached.
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public int read(long position, byte[] buffer, int offset, int length)
- throws IOException {
- throw new UnsupportedOperationException(
- "Positioned read is not supported by this implementation");
- }
+ /**
+ * Overrides the
+ * {@link org.apache.commons.crypto.stream.input.Input#read(long, byte[], int, int)}
+ * . Reads up to <code>len</code> bytes of data from the input stream into
+ * an array of bytes. An attempt is made to read as many as <code>len</code>
+ * bytes, but a smaller number may be read. The number of bytes actually
+ * read is returned as an integer.
+ *
+ * @param position the given position within a stream.
+ * @param buffer the buffer into which the data is read.
+ * @param offset the start offset in array buffer.
+ * @param length the maximum number of bytes to read.
+ * @return the total number of bytes read into the buffer, or
+ * <code>-1</code> if there is no more data because the end of the
+ * stream has been reached.
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public int read(long position, byte[] buffer, int offset, int length)
+ throws IOException {
+ throw new UnsupportedOperationException(
+ "Positioned read is not supported by this implementation");
+ }
- /**
- * Overrides the {@link org.apache.commons.crypto.stream.input.Input#seek(long)}.
- * Seeks to the given offset from the start of the stream.
- * The next read() will be from that location.
- *
- * @param position the offset from the start of the stream.
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public void seek(long position) throws IOException {
- throw new UnsupportedOperationException(
- "Seek is not supported by this implementation");
- }
+ /**
+ * Overrides the
+ * {@link org.apache.commons.crypto.stream.input.Input#seek(long)}. Seeks to
+ * the given offset from the start of the stream. The next read() will be
+ * from that location.
+ *
+ * @param position the offset from the start of the stream.
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public void seek(long position) throws IOException {
+ throw new UnsupportedOperationException(
+ "Seek is not supported by this implementation");
+ }
- /**
- * Overrides the {@link org.apache.commons.crypto.stream.input.Input#seek(long)}.
- * Closes this input and releases any system resources associated
- * with the under layer input.
- *
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public void close() throws IOException {
- in.close();
- }
+ /**
+ * Overrides the
+ * {@link org.apache.commons.crypto.stream.input.Input#seek(long)}. Closes
+ * this input and releases any system resources associated with the under
+ * layer input.
+ *
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public void close() throws IOException {
+ in.close();
+ }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/stream/input/package-info.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/stream/input/package-info.java b/src/main/java/org/apache/commons/crypto/stream/input/package-info.java
index 66e7af5..877eba0 100644
--- a/src/main/java/org/apache/commons/crypto/stream/input/package-info.java
+++ b/src/main/java/org/apache/commons/crypto/stream/input/package-info.java
@@ -19,3 +19,4 @@
* Input classes
*/
package org.apache.commons.crypto.stream.input;
+
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/stream/output/ChannelOutput.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/stream/output/ChannelOutput.java b/src/main/java/org/apache/commons/crypto/stream/output/ChannelOutput.java
index 9805484..a28a21e 100644
--- a/src/main/java/org/apache/commons/crypto/stream/output/ChannelOutput.java
+++ b/src/main/java/org/apache/commons/crypto/stream/output/ChannelOutput.java
@@ -22,57 +22,58 @@ import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
/**
- * The ChannelOutput class takes a <code>WritableByteChannel</code> object and wraps it as
- * <code>Output</code> object acceptable by <code>CryptoOutputStream</code> as the output target.
+ * The ChannelOutput class takes a <code>WritableByteChannel</code> object and
+ * wraps it as <code>Output</code> object acceptable by
+ * <code>CryptoOutputStream</code> as the output target.
*/
public class ChannelOutput implements Output {
- private WritableByteChannel channel;
+ private WritableByteChannel channel;
- /**
- * Constructs a {@link org.apache.commons.crypto.stream.output.ChannelOutput}.
- *
- * @param channel the WritableByteChannel object.
- */
- public ChannelOutput(WritableByteChannel channel) {
- this.channel = channel;
- }
+ /**
+ * Constructs a
+ * {@link org.apache.commons.crypto.stream.output.ChannelOutput}.
+ *
+ * @param channel the WritableByteChannel object.
+ */
+ public ChannelOutput(WritableByteChannel channel) {
+ this.channel = channel;
+ }
- /**
- * Overrides the {@link org.apache.commons.crypto.stream.output.Output#write(ByteBuffer)}.
- * Writes a sequence of bytes to this output from the given buffer.
- *
- * @param src
- * The buffer from which bytes are to be retrieved.
- *
- * @return The number of bytes written, possibly zero.
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public int write(ByteBuffer src) throws IOException {
- return channel.write(src);
- }
+ /**
+ * Overrides the
+ * {@link org.apache.commons.crypto.stream.output.Output#write(ByteBuffer)}.
+ * Writes a sequence of bytes to this output from the given buffer.
+ *
+ * @param src The buffer from which bytes are to be retrieved.
+ *
+ * @return The number of bytes written, possibly zero.
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public int write(ByteBuffer src) throws IOException {
+ return channel.write(src);
+ }
- /**
- * Overrides the {@link Output#flush()}.
- * Flushes this output and forces any buffered output bytes
- * to be written out if the under layer output method support.
- *
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public void flush() throws IOException {
- }
+ /**
+ * Overrides the {@link Output#flush()}. Flushes this output and forces any
+ * buffered output bytes to be written out if the under layer output method
+ * support.
+ *
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public void flush() throws IOException {
+ }
- /**
- * Overrides the {@link Output#close()}.
- * Closes this output and releases any system resources associated
- * with the under layer output.
- *
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public void close() throws IOException {
- channel.close();
- }
+ /**
+ * Overrides the {@link Output#close()}. Closes this output and releases any
+ * system resources associated with the under layer output.
+ *
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public void close() throws IOException {
+ channel.close();
+ }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/stream/output/Output.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/stream/output/Output.java b/src/main/java/org/apache/commons/crypto/stream/output/Output.java
index 34f1610..5dbb835 100644
--- a/src/main/java/org/apache/commons/crypto/stream/output/Output.java
+++ b/src/main/java/org/apache/commons/crypto/stream/output/Output.java
@@ -21,56 +21,57 @@ import java.io.IOException;
import java.nio.ByteBuffer;
/**
- * The Output interface abstract the output target of <code>CryptoOutputStream</code> so that
- * different implementation of output can be used. The implementation Output interface will usually
- * wraps an output mechanism such as <code>OutputStream</code> or <code>WritableByteChannel</code>.
+ * The Output interface abstract the output target of
+ * <code>CryptoOutputStream</code> so that different implementation of output
+ * can be used. The implementation Output interface will usually wraps an output
+ * mechanism such as <code>OutputStream</code> or
+ * <code>WritableByteChannel</code>.
*/
public interface Output {
- /**
- * Writes a sequence of bytes to this output from the given buffer.
- *
- * <p> An attempt is made to write up to <i>r</i> bytes to the channel,
- * where <i>r</i> is the number of bytes remaining in the buffer, that is,
- * <tt>src.remaining()</tt>, at the moment this method is invoked.
- *
- * <p> Suppose that a byte sequence of length <i>n</i> is written, where
- * <tt>0</tt> <tt><=</tt> <i>n</i> <tt><=</tt> <i>r</i>.
- * This byte sequence will be transferred from the buffer starting at index
- * <i>p</i>, where <i>p</i> is the buffer's position at the moment this
- * method is invoked; the index of the last byte written will be
- * <i>p</i> <tt>+</tt> <i>n</i> <tt>-</tt> <tt>1</tt>.
- * Upon return the buffer's position will be equal to
- * <i>p</i> <tt>+</tt> <i>n</i>; its limit will not have changed.
- *
- * @param src
- * The buffer from which bytes are to be retrieved.
- *
- * @return The number of bytes written, possibly zero.
- *
- * @throws IOException
- * If some other I/O error occurs.
- */
- int write(ByteBuffer src) throws IOException;
+ /**
+ * Writes a sequence of bytes to this output from the given buffer.
+ *
+ * <p>
+ * An attempt is made to write up to <i>r</i> bytes to the channel, where
+ * <i>r</i> is the number of bytes remaining in the buffer, that is,
+ * <tt>src.remaining()</tt>, at the moment this method is invoked.
+ *
+ * <p>
+ * Suppose that a byte sequence of length <i>n</i> is written, where
+ * <tt>0</tt> <tt><=</tt> <i>n</i> <tt><=</tt>
+ * <i>r</i>. This byte sequence will be transferred from the buffer
+ * starting at index <i>p</i>, where <i>p</i> is the buffer's position at
+ * the moment this method is invoked; the index of the last byte written
+ * will be <i>p</i> <tt>+</tt> <i>n</i> <tt>-</tt>
+ * <tt>1</tt>. Upon return the buffer's position will be equal to
+ * <i>p</i> <tt>+</tt> <i>n</i>; its limit will not have changed.
+ *
+ * @param src The buffer from which bytes are to be retrieved.
+ *
+ * @return The number of bytes written, possibly zero.
+ *
+ * @throws IOException If some other I/O error occurs.
+ */
+ int write(ByteBuffer src) throws IOException;
- /**
- * Flushes this output and forces any buffered output bytes
- * to be written out if the under layer output method support.
- * The general contract of <code>flush</code> is
- * that calling it is an indication that, if any bytes previously
- * written have been buffered by the implementation of the output
- * stream, such bytes should immediately be written to their
- * intended destination.
- *
- * @throws IOException if an I/O error occurs.
- */
- void flush() throws IOException;
+ /**
+ * Flushes this output and forces any buffered output bytes to be written
+ * out if the under layer output method support. The general contract of
+ * <code>flush</code> is that calling it is an indication that, if any bytes
+ * previously written have been buffered by the implementation of the output
+ * stream, such bytes should immediately be written to their intended
+ * destination.
+ *
+ * @throws IOException if an I/O error occurs.
+ */
+ void flush() throws IOException;
- /**
- * Closes this output and releases any system resources associated
- * with the under layer output.
- *
- * @throws IOException if an I/O error occurs.
- */
- void close() throws IOException;
+ /**
+ * Closes this output and releases any system resources associated with the
+ * under layer output.
+ *
+ * @throws IOException if an I/O error occurs.
+ */
+ void close() throws IOException;
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/stream/output/StreamOutput.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/stream/output/StreamOutput.java b/src/main/java/org/apache/commons/crypto/stream/output/StreamOutput.java
index 8c0e4d7..78c9bab 100644
--- a/src/main/java/org/apache/commons/crypto/stream/output/StreamOutput.java
+++ b/src/main/java/org/apache/commons/crypto/stream/output/StreamOutput.java
@@ -22,76 +22,77 @@ import java.io.OutputStream;
import java.nio.ByteBuffer;
/**
- * The StreamOutput class takes a <code>OutputStream</code> object and wraps it as
- * <code>Output</code> object acceptable by <code>CryptoOutputStream</code> as the output target.
+ * The StreamOutput class takes a <code>OutputStream</code> object and wraps it
+ * as <code>Output</code> object acceptable by <code>CryptoOutputStream</code>
+ * as the output target.
*/
public class StreamOutput implements Output {
- private final byte[] buf;
- private final int bufferSize;
- private final OutputStream out;
+ private final byte[] buf;
+ private final int bufferSize;
+ private final OutputStream out;
- /**
- * Constructs a {@link org.apache.commons.crypto.stream.output.StreamOutput}.
- *
- * @param out the OutputStream object.
- * @param bufferSize the buffersize.
- */
- public StreamOutput(OutputStream out, int bufferSize) {
- this.out = out;
- this.bufferSize = bufferSize;
- buf = new byte[bufferSize];
- }
+ /**
+ * Constructs a {@link org.apache.commons.crypto.stream.output.StreamOutput}
+ * .
+ *
+ * @param out the OutputStream object.
+ * @param bufferSize the buffersize.
+ */
+ public StreamOutput(OutputStream out, int bufferSize) {
+ this.out = out;
+ this.bufferSize = bufferSize;
+ buf = new byte[bufferSize];
+ }
- /**
- * Overrides the {@link org.apache.commons.crypto.stream.output.Output#write(ByteBuffer)}.
- * Writes a sequence of bytes to this output from the given buffer.
- *
- * @param src
- * The buffer from which bytes are to be retrieved.
- *
- * @return The number of bytes written, possibly zero.
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public int write(ByteBuffer src) throws IOException {
- final int len = src.remaining();
+ /**
+ * Overrides the
+ * {@link org.apache.commons.crypto.stream.output.Output#write(ByteBuffer)}.
+ * Writes a sequence of bytes to this output from the given buffer.
+ *
+ * @param src The buffer from which bytes are to be retrieved.
+ *
+ * @return The number of bytes written, possibly zero.
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public int write(ByteBuffer src) throws IOException {
+ final int len = src.remaining();
- int remaining = len;
- while(remaining > 0) {
- final int n = Math.min(remaining, bufferSize);
- src.get(buf, 0, n);
- out.write(buf, 0, n);
- remaining = src.remaining();
- }
+ int remaining = len;
+ while (remaining > 0) {
+ final int n = Math.min(remaining, bufferSize);
+ src.get(buf, 0, n);
+ out.write(buf, 0, n);
+ remaining = src.remaining();
+ }
- return len;
- }
+ return len;
+ }
- /**
- * Overrides the {@link Output#flush()}.
- * Flushes this output and forces any buffered output bytes
- * to be written out if the under layer output method support.
- *
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public void flush() throws IOException {
- out.flush();
- }
+ /**
+ * Overrides the {@link Output#flush()}. Flushes this output and forces any
+ * buffered output bytes to be written out if the under layer output method
+ * support.
+ *
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public void flush() throws IOException {
+ out.flush();
+ }
- /**
- * Overrides the {@link Output#close()}.
- * Closes this output and releases any system resources associated
- * with the under layer output.
- *
- * @throws IOException if an I/O error occurs.
- */
- @Override
- public void close() throws IOException {
- out.close();
- }
+ /**
+ * Overrides the {@link Output#close()}. Closes this output and releases any
+ * system resources associated with the under layer output.
+ *
+ * @throws IOException if an I/O error occurs.
+ */
+ @Override
+ public void close() throws IOException {
+ out.close();
+ }
- protected OutputStream getOut() {
- return out;
- }
+ protected OutputStream getOut() {
+ return out;
+ }
}
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/stream/output/package-info.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/stream/output/package-info.java b/src/main/java/org/apache/commons/crypto/stream/output/package-info.java
index eca3927..c31b85e 100644
--- a/src/main/java/org/apache/commons/crypto/stream/output/package-info.java
+++ b/src/main/java/org/apache/commons/crypto/stream/output/package-info.java
@@ -19,3 +19,4 @@
* Output classes
*/
package org.apache.commons.crypto.stream.output;
+
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/stream/package-info.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/stream/package-info.java b/src/main/java/org/apache/commons/crypto/stream/package-info.java
index 416d78b..6ae28e3 100644
--- a/src/main/java/org/apache/commons/crypto/stream/package-info.java
+++ b/src/main/java/org/apache/commons/crypto/stream/package-info.java
@@ -19,3 +19,4 @@
* Stream classes
*/
package org.apache.commons.crypto.stream;
+
http://git-wip-us.apache.org/repos/asf/commons-crypto/blob/95a8d486/src/main/java/org/apache/commons/crypto/utils/IOUtils.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/crypto/utils/IOUtils.java b/src/main/java/org/apache/commons/crypto/utils/IOUtils.java
index a3ecda4..4b0e6ee 100644
--- a/src/main/java/org/apache/commons/crypto/utils/IOUtils.java
+++ b/src/main/java/org/apache/commons/crypto/utils/IOUtils.java
@@ -28,71 +28,74 @@ import org.apache.commons.logging.Log;
*/
public class IOUtils {
- private IOUtils() {}
+ private IOUtils() {
+ }
- /**
- * Does the readFully based on the Input read.
- *
- * @param in the input stream of bytes.
- * @param buf the buffer to be read.
- * @param off the start offset in array buffer.
- * @param len the maximum number of bytes to read.
- * @throws IOException if an I/O error occurs.
- */
- public static void readFully(InputStream in, byte buf[],
- int off, int len) throws IOException {
- int toRead = len;
- while (toRead > 0) {
- int ret = in.read(buf, off, toRead);
- if (ret < 0) {
- throw new IOException( "Premature EOF from inputStream");
- }
- toRead -= ret;
- off += ret;
+ /**
+ * Does the readFully based on the Input read.
+ *
+ * @param in the input stream of bytes.
+ * @param buf the buffer to be read.
+ * @param off the start offset in array buffer.
+ * @param len the maximum number of bytes to read.
+ * @throws IOException if an I/O error occurs.
+ */
+ public static void readFully(InputStream in, byte buf[], int off, int len)
+ throws IOException {
+ int toRead = len;
+ while (toRead > 0) {
+ int ret = in.read(buf, off, toRead);
+ if (ret < 0) {
+ throw new IOException("Premature EOF from inputStream");
+ }
+ toRead -= ret;
+ off += ret;
+ }
}
- }
- /**
- * Does the readFully based on Input's positioned read.
- * This does not change the current offset of the stream and is thread-safe.
- *
- * @param in the input source.
- * @param position the given position.
- * @param buffer the buffer to be read.
- * @param length the maximum number of bytes to read.
- * @param offset the start offset in array buffer.
- * @throws IOException if an I/O error occurs.
- */
- public static void readFully(Input in, long position,
- byte[] buffer, int offset, int length) throws IOException {
- int nread = 0;
- while (nread < length) {
- int nbytes = in.read(position+nread, buffer, offset+nread, length-nread);
- if (nbytes < 0) {
- throw new IOException("End of stream reached before reading fully.");
- }
- nread += nbytes;
+ /**
+ * Does the readFully based on Input's positioned read. This does not change
+ * the current offset of the stream and is thread-safe.
+ *
+ * @param in the input source.
+ * @param position the given position.
+ * @param buffer the buffer to be read.
+ * @param length the maximum number of bytes to read.
+ * @param offset the start offset in array buffer.
+ * @throws IOException if an I/O error occurs.
+ */
+ public static void readFully(Input in, long position, byte[] buffer,
+ int offset, int length) throws IOException {
+ int nread = 0;
+ while (nread < length) {
+ int nbytes = in.read(position + nread, buffer, offset + nread,
+ length - nread);
+ if (nbytes < 0) {
+ throw new IOException(
+ "End of stream reached before reading fully.");
+ }
+ nread += nbytes;
+ }
}
- }
- /**
- * Closes the Closeable objects and <b>ignore</b> any {@link IOException} or
- * null pointers. Must only be used for cleanup in exception handlers.
- *
- * @param log the log to record problems to at debug level. Can be null.
- * @param closeables the objects to close.
- */
- public static void cleanup(Log log, java.io.Closeable... closeables) {
- for (java.io.Closeable c : closeables) {
- if (c != null) {
- try {
- c.close();
- } catch(Throwable e) {
- if (log != null && log.isDebugEnabled()) {
- log.debug("Exception in closing " + c, e);
- }
+ /**
+ * Closes the Closeable objects and <b>ignore</b> any {@link IOException} or
+ * null pointers. Must only be used for cleanup in exception handlers.
+ *
+ * @param log the log to record problems to at debug level. Can be null.
+ * @param closeables the objects to close.
+ */
+ public static void cleanup(Log log, java.io.Closeable... closeables) {
+ for (java.io.Closeable c : closeables) {
+ if (c != null) {
+ try {
+ c.close();
+ } catch (Throwable e) {
+ if (log != null && log.isDebugEnabled()) {
+ log.debug("Exception in closing " + c, e);
+ }
+ }
+ }
}
- }
}
- }
}