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 <cheng.a...@intel.com> Authored: Wed May 4 04:05:27 2016 +0800 Committer: Ferdinand Xu <cheng.a...@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; +