0N/A/*
2362N/A * Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
0N/A */
0N/A
0N/Apackage com.sun.crypto.provider;
0N/A
0N/Aimport java.util.Locale;
0N/A
0N/Aimport java.security.*;
0N/Aimport java.security.spec.*;
0N/Aimport javax.crypto.*;
0N/Aimport javax.crypto.spec.*;
0N/Aimport javax.crypto.BadPaddingException;
0N/A
0N/A/**
0N/A * This class represents the symmetric algorithms in its various modes
0N/A * (<code>ECB</code>, <code>CFB</code>, <code>OFB</code>, <code>CBC</code>,
0N/A * <code>PCBC</code>, <code>CTR</code>, and <code>CTS</code>) and
0N/A * padding schemes (<code>PKCS5Padding</code>, <code>NoPadding</code>,
0N/A * <code>ISO10126Padding</code>).
0N/A *
0N/A * @author Gigi Ankeny
0N/A * @author Jan Luehe
0N/A * @see ElectronicCodeBook
0N/A * @see CipherFeedback
0N/A * @see OutputFeedback
0N/A * @see CipherBlockChaining
0N/A * @see PCBC
0N/A * @see CounterMode
0N/A * @see CipherTextStealing
0N/A */
0N/A
0N/Afinal class CipherCore {
0N/A
0N/A /*
0N/A * internal buffer
0N/A */
0N/A private byte[] buffer = null;
0N/A
0N/A /*
0N/A * internal buffer
0N/A */
0N/A private int blockSize = 0;
0N/A
0N/A /*
0N/A * unit size (number of input bytes that can be processed at a time)
0N/A */
0N/A private int unitBytes = 0;
0N/A
0N/A /*
0N/A * index of the content size left in the buffer
0N/A */
0N/A private int buffered = 0;
0N/A
0N/A /*
0N/A * minimum number of bytes in the buffer required for
0N/A * FeedbackCipher.encryptFinal()/decryptFinal() call.
0N/A * update() must buffer this many bytes before before starting
0N/A * to encrypt/decrypt data.
0N/A * currently, only CTS mode has a non-zero value due to its special
0N/A * handling on the last two blocks (the last one may be incomplete).
0N/A */
0N/A private int minBytes = 0;
0N/A
0N/A /*
0N/A * number of bytes needed to make the total input length a multiple
0N/A * of the blocksize (this is used in feedback mode, when the number of
0N/A * input bytes that are processed at a time is different from the block
0N/A * size)
0N/A */
0N/A private int diffBlocksize = 0;
0N/A
0N/A /*
0N/A * padding class
0N/A */
0N/A private Padding padding = null;
0N/A
0N/A /*
0N/A * internal cipher engine
0N/A */
0N/A private FeedbackCipher cipher = null;
0N/A
0N/A /*
0N/A * the cipher mode
0N/A */
0N/A private int cipherMode = ECB_MODE;
0N/A
0N/A /*
0N/A * are we encrypting or decrypting?
0N/A */
0N/A private boolean decrypting = false;
0N/A
0N/A /*
0N/A * Block Mode constants
0N/A */
0N/A private static final int ECB_MODE = 0;
0N/A private static final int CBC_MODE = 1;
0N/A private static final int CFB_MODE = 2;
0N/A private static final int OFB_MODE = 3;
0N/A private static final int PCBC_MODE = 4;
0N/A private static final int CTR_MODE = 5;
0N/A private static final int CTS_MODE = 6;
0N/A
0N/A /**
0N/A * Creates an instance of CipherCore with default ECB mode and
0N/A * PKCS5Padding.
0N/A */
0N/A CipherCore(SymmetricCipher impl, int blkSize) {
0N/A blockSize = blkSize;
0N/A unitBytes = blkSize;
0N/A diffBlocksize = blkSize;
0N/A
0N/A /*
0N/A * The buffer should be usable for all cipher mode and padding
0N/A * schemes. Thus, it has to be at least (blockSize+1) for CTS.
0N/A * In decryption mode, it also hold the possible padding block.
0N/A */
0N/A buffer = new byte[blockSize*2];
0N/A
0N/A // set mode and padding
0N/A cipher = new ElectronicCodeBook(impl);
0N/A padding = new PKCS5Padding(blockSize);
0N/A }
0N/A
0N/A /**
0N/A * Sets the mode of this cipher.
0N/A *
0N/A * @param mode the cipher mode
0N/A *
0N/A * @exception NoSuchAlgorithmException if the requested cipher mode does
0N/A * not exist
0N/A */
0N/A void setMode(String mode) throws NoSuchAlgorithmException {
0N/A if (mode == null)
0N/A throw new NoSuchAlgorithmException("null mode");
0N/A
0N/A String modeUpperCase = mode.toUpperCase(Locale.ENGLISH);
0N/A
0N/A if (modeUpperCase.equals("ECB")) {
0N/A return;
0N/A }
0N/A
0N/A SymmetricCipher rawImpl = cipher.getEmbeddedCipher();
0N/A if (modeUpperCase.equals("CBC")) {
0N/A cipherMode = CBC_MODE;
0N/A cipher = new CipherBlockChaining(rawImpl);
0N/A }
0N/A else if (modeUpperCase.equals("CTS")) {
0N/A cipherMode = CTS_MODE;
0N/A cipher = new CipherTextStealing(rawImpl);
0N/A minBytes = blockSize+1;
0N/A padding = null;
0N/A }
0N/A else if (modeUpperCase.equals("CTR")) {
0N/A cipherMode = CTR_MODE;
0N/A cipher = new CounterMode(rawImpl);
0N/A unitBytes = 1;
0N/A padding = null;
0N/A }
0N/A else if (modeUpperCase.startsWith("CFB")) {
0N/A cipherMode = CFB_MODE;
0N/A unitBytes = getNumOfUnit(mode, "CFB".length(), blockSize);
0N/A cipher = new CipherFeedback(rawImpl, unitBytes);
0N/A }
0N/A else if (modeUpperCase.startsWith("OFB")) {
0N/A cipherMode = OFB_MODE;
0N/A unitBytes = getNumOfUnit(mode, "OFB".length(), blockSize);
0N/A cipher = new OutputFeedback(rawImpl, unitBytes);
0N/A }
0N/A else if (modeUpperCase.equals("PCBC")) {
0N/A cipherMode = PCBC_MODE;
0N/A cipher = new PCBC(rawImpl);
0N/A }
0N/A else {
0N/A throw new NoSuchAlgorithmException("Cipher mode: " + mode
0N/A + " not found");
0N/A }
0N/A }
0N/A
0N/A private static int getNumOfUnit(String mode, int offset, int blockSize)
0N/A throws NoSuchAlgorithmException {
0N/A int result = blockSize; // use blockSize as default value
0N/A if (mode.length() > offset) {
0N/A int numInt;
0N/A try {
0N/A Integer num = Integer.valueOf(mode.substring(offset));
0N/A numInt = num.intValue();
0N/A result = numInt >> 3;
0N/A } catch (NumberFormatException e) {
0N/A throw new NoSuchAlgorithmException
0N/A ("Algorithm mode: " + mode + " not implemented");
0N/A }
0N/A if ((numInt % 8 != 0) || (result > blockSize)) {
0N/A throw new NoSuchAlgorithmException
0N/A ("Invalid algorithm mode: " + mode);
0N/A }
0N/A }
0N/A return result;
0N/A }
0N/A
0N/A /**
0N/A * Sets the padding mechanism of this cipher.
0N/A *
0N/A * @param padding the padding mechanism
0N/A *
0N/A * @exception NoSuchPaddingException if the requested padding mechanism
0N/A * does not exist
0N/A */
0N/A void setPadding(String paddingScheme)
0N/A throws NoSuchPaddingException
0N/A {
0N/A if (paddingScheme == null) {
0N/A throw new NoSuchPaddingException("null padding");
0N/A }
0N/A if (paddingScheme.equalsIgnoreCase("NoPadding")) {
0N/A padding = null;
0N/A } else if (paddingScheme.equalsIgnoreCase("ISO10126Padding")) {
0N/A padding = new ISO10126Padding(blockSize);
0N/A } else if (!paddingScheme.equalsIgnoreCase("PKCS5Padding")) {
0N/A throw new NoSuchPaddingException("Padding: " + paddingScheme
0N/A + " not implemented");
0N/A }
0N/A if ((padding != null) &&
0N/A ((cipherMode == CTR_MODE) || (cipherMode == CTS_MODE))) {
0N/A padding = null;
0N/A throw new NoSuchPaddingException
0N/A ((cipherMode == CTR_MODE? "CTR":"CTS") +
0N/A " mode must be used with NoPadding");
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns the length in bytes that an output buffer would need to be in
0N/A * order to hold the result of the next <code>update</code> or
0N/A * <code>doFinal</code> operation, given the input length
0N/A * <code>inputLen</code> (in bytes).
0N/A *
0N/A * <p>This call takes into account any unprocessed (buffered) data from a
0N/A * previous <code>update</code> call, and padding.
0N/A *
0N/A * <p>The actual output length of the next <code>update</code> or
0N/A * <code>doFinal</code> call may be smaller than the length returned by
0N/A * this method.
0N/A *
0N/A * @param inputLen the input length (in bytes)
0N/A *
0N/A * @return the required output buffer size (in bytes)
0N/A */
0N/A int getOutputSize(int inputLen) {
0N/A int totalLen = buffered + inputLen;
0N/A
0N/A if (padding == null)
0N/A return totalLen;
0N/A
0N/A if (decrypting)
0N/A return totalLen;
0N/A
0N/A if (unitBytes != blockSize) {
0N/A if (totalLen < diffBlocksize)
0N/A return diffBlocksize;
0N/A else
0N/A return (totalLen + blockSize -
0N/A ((totalLen - diffBlocksize) % blockSize));
0N/A } else {
0N/A return totalLen + padding.padLength(totalLen);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns the initialization vector (IV) in a new buffer.
0N/A *
0N/A * <p>This is useful in the case where a random IV has been created
0N/A * (see <a href = "#init">init</a>),
0N/A * or in the context of password-based encryption or
0N/A * decryption, where the IV is derived from a user-provided password.
0N/A *
0N/A * @return the initialization vector in a new buffer, or null if the
0N/A * underlying algorithm does not use an IV, or if the IV has not yet
0N/A * been set.
0N/A */
0N/A byte[] getIV() {
0N/A byte[] iv = cipher.getIV();
0N/A return (iv == null) ? null : (byte[])iv.clone();
0N/A }
0N/A
0N/A /**
0N/A * Returns the parameters used with this cipher.
0N/A *
0N/A * <p>The returned parameters may be the same that were used to initialize
0N/A * this cipher, or may contain the default set of parameters or a set of
0N/A * randomly generated parameters used by the underlying cipher
0N/A * implementation (provided that the underlying cipher implementation
0N/A * uses a default set of parameters or creates new parameters if it needs
0N/A * parameters but was not initialized with any).
0N/A *
0N/A * @return the parameters used with this cipher, or null if this cipher
0N/A * does not use any parameters.
0N/A */
0N/A AlgorithmParameters getParameters(String algName) {
0N/A AlgorithmParameters params = null;
0N/A if (cipherMode == ECB_MODE) return null;
0N/A byte[] iv = getIV();
0N/A if (iv != null) {
0N/A AlgorithmParameterSpec ivSpec;
0N/A if (algName.equals("RC2")) {
0N/A RC2Crypt rawImpl = (RC2Crypt) cipher.getEmbeddedCipher();
0N/A ivSpec = new RC2ParameterSpec(rawImpl.getEffectiveKeyBits(),
0N/A iv);
0N/A } else {
0N/A ivSpec = new IvParameterSpec(iv);
0N/A }
0N/A try {
0N/A params = AlgorithmParameters.getInstance(algName, "SunJCE");
0N/A } catch (NoSuchAlgorithmException nsae) {
0N/A // should never happen
0N/A throw new RuntimeException("Cannot find " + algName +
0N/A " AlgorithmParameters implementation in SunJCE provider");
0N/A } catch (NoSuchProviderException nspe) {
0N/A // should never happen
0N/A throw new RuntimeException("Cannot find SunJCE provider");
0N/A }
0N/A try {
0N/A params.init(ivSpec);
0N/A } catch (InvalidParameterSpecException ipse) {
0N/A // should never happen
0N/A throw new RuntimeException("IvParameterSpec not supported");
0N/A }
0N/A }
0N/A return params;
0N/A }
0N/A
0N/A /**
0N/A * Initializes this cipher with a key and a source of randomness.
0N/A *
0N/A * <p>The cipher is initialized for one of the following four operations:
0N/A * encryption, decryption, key wrapping or key unwrapping, depending on
0N/A * the value of <code>opmode</code>.
0N/A *
0N/A * <p>If this cipher requires an initialization vector (IV), it will get
0N/A * it from <code>random</code>.
0N/A * This behaviour should only be used in encryption or key wrapping
0N/A * mode, however.
0N/A * When initializing a cipher that requires an IV for decryption or
0N/A * key unwrapping, the IV
0N/A * (same IV that was used for encryption or key wrapping) must be provided
0N/A * explicitly as a
0N/A * parameter, in order to get the correct result.
0N/A *
0N/A * <p>This method also cleans existing buffer and other related state
0N/A * information.
0N/A *
0N/A * @param opmode the operation mode of this cipher (this is one of
0N/A * the following:
0N/A * <code>ENCRYPT_MODE</code>, <code>DECRYPT_MODE</code>,
0N/A * <code>WRAP_MODE</code> or <code>UNWRAP_MODE</code>)
0N/A * @param key the secret key
0N/A * @param random the source of randomness
0N/A *
0N/A * @exception InvalidKeyException if the given key is inappropriate for
0N/A * initializing this cipher
0N/A */
0N/A void init(int opmode, Key key, SecureRandom random)
0N/A throws InvalidKeyException {
0N/A try {
0N/A init(opmode, key, (AlgorithmParameterSpec)null, random);
0N/A } catch (InvalidAlgorithmParameterException e) {
0N/A throw new InvalidKeyException(e.getMessage());
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Initializes this cipher with a key, a set of
0N/A * algorithm parameters, and a source of randomness.
0N/A *
0N/A * <p>The cipher is initialized for one of the following four operations:
0N/A * encryption, decryption, key wrapping or key unwrapping, depending on
0N/A * the value of <code>opmode</code>.
0N/A *
0N/A * <p>If this cipher (including its underlying feedback or padding scheme)
0N/A * requires any random bytes, it will get them from <code>random</code>.
0N/A *
0N/A * @param opmode the operation mode of this cipher (this is one of
0N/A * the following:
0N/A * <code>ENCRYPT_MODE</code>, <code>DECRYPT_MODE</code>,
0N/A * <code>WRAP_MODE</code> or <code>UNWRAP_MODE</code>)
0N/A * @param key the encryption key
0N/A * @param params the algorithm parameters
0N/A * @param random the source of randomness
0N/A *
0N/A * @exception InvalidKeyException if the given key is inappropriate for
0N/A * initializing this cipher
0N/A * @exception InvalidAlgorithmParameterException if the given algorithm
0N/A * parameters are inappropriate for this cipher
0N/A */
0N/A void init(int opmode, Key key, AlgorithmParameterSpec params,
0N/A SecureRandom random)
0N/A throws InvalidKeyException, InvalidAlgorithmParameterException {
0N/A decrypting = (opmode == Cipher.DECRYPT_MODE)
0N/A || (opmode == Cipher.UNWRAP_MODE);
0N/A
0N/A byte[] keyBytes = getKeyBytes(key);
0N/A
0N/A byte[] ivBytes;
0N/A if (params == null) {
0N/A ivBytes = null;
0N/A } else if (params instanceof IvParameterSpec) {
0N/A ivBytes = ((IvParameterSpec)params).getIV();
0N/A if ((ivBytes == null) || (ivBytes.length != blockSize)) {
0N/A throw new InvalidAlgorithmParameterException
0N/A ("Wrong IV length: must be " + blockSize +
0N/A " bytes long");
0N/A }
0N/A } else if (params instanceof RC2ParameterSpec) {
0N/A ivBytes = ((RC2ParameterSpec)params).getIV();
0N/A if ((ivBytes != null) && (ivBytes.length != blockSize)) {
0N/A throw new InvalidAlgorithmParameterException
0N/A ("Wrong IV length: must be " + blockSize +
0N/A " bytes long");
0N/A }
0N/A } else {
0N/A throw new InvalidAlgorithmParameterException("Wrong parameter "
0N/A + "type: IV "
0N/A + "expected");
0N/A }
0N/A
0N/A if (cipherMode == ECB_MODE) {
0N/A if (ivBytes != null) {
0N/A throw new InvalidAlgorithmParameterException
0N/A ("ECB mode cannot use IV");
0N/A }
0N/A } else if (ivBytes == null) {
0N/A if (decrypting) {
0N/A throw new InvalidAlgorithmParameterException("Parameters "
0N/A + "missing");
0N/A }
0N/A if (random == null) {
0N/A random = SunJCE.RANDOM;
0N/A }
0N/A ivBytes = new byte[blockSize];
0N/A random.nextBytes(ivBytes);
0N/A }
0N/A
0N/A buffered = 0;
0N/A diffBlocksize = blockSize;
0N/A
0N/A String algorithm = key.getAlgorithm();
0N/A
0N/A cipher.init(decrypting, algorithm, keyBytes, ivBytes);
0N/A }
0N/A
0N/A void init(int opmode, Key key, AlgorithmParameters params,
0N/A SecureRandom random)
0N/A throws InvalidKeyException, InvalidAlgorithmParameterException {
0N/A IvParameterSpec ivSpec = null;
0N/A if (params != null) {
0N/A try {
0N/A ivSpec = (IvParameterSpec)params.getParameterSpec
0N/A (IvParameterSpec.class);
0N/A } catch (InvalidParameterSpecException ipse) {
0N/A throw new InvalidAlgorithmParameterException("Wrong parameter "
0N/A + "type: IV "
0N/A + "expected");
0N/A }
0N/A }
0N/A init(opmode, key, ivSpec, random);
0N/A }
0N/A
0N/A /**
0N/A * Return the key bytes of the specified key. Throw an InvalidKeyException
0N/A * if the key is not usable.
0N/A */
0N/A static byte[] getKeyBytes(Key key) throws InvalidKeyException {
0N/A if (key == null) {
0N/A throw new InvalidKeyException("No key given");
0N/A }
0N/A // note: key.getFormat() may return null
0N/A if (!"RAW".equalsIgnoreCase(key.getFormat())) {
0N/A throw new InvalidKeyException("Wrong format: RAW bytes needed");
0N/A }
0N/A byte[] keyBytes = key.getEncoded();
0N/A if (keyBytes == null) {
0N/A throw new InvalidKeyException("RAW key bytes missing");
0N/A }
0N/A return keyBytes;
0N/A }
0N/A
0N/A /**
0N/A * Continues a multiple-part encryption or decryption operation
0N/A * (depending on how this cipher was initialized), processing another data
0N/A * part.
0N/A *
0N/A * <p>The first <code>inputLen</code> bytes in the <code>input</code>
0N/A * buffer, starting at <code>inputOffset</code>, are processed, and the
0N/A * result is stored in a new buffer.
0N/A *
0N/A * @param input the input buffer
0N/A * @param inputOffset the offset in <code>input</code> where the input
0N/A * starts
0N/A * @param inputLen the input length
0N/A *
0N/A * @return the new buffer with the result
0N/A *
0N/A * @exception IllegalStateException if this cipher is in a wrong state
0N/A * (e.g., has not been initialized)
0N/A */
0N/A byte[] update(byte[] input, int inputOffset, int inputLen) {
0N/A byte[] output = null;
0N/A byte[] out = null;
0N/A try {
0N/A output = new byte[getOutputSize(inputLen)];
0N/A int len = update(input, inputOffset, inputLen, output,
0N/A 0);
0N/A if (len == output.length) {
0N/A out = output;
0N/A } else {
0N/A out = new byte[len];
0N/A System.arraycopy(output, 0, out, 0, len);
0N/A }
0N/A } catch (ShortBufferException e) {
0N/A // never thrown
0N/A }
0N/A return out;
0N/A }
0N/A
0N/A /**
0N/A * Continues a multiple-part encryption or decryption operation
0N/A * (depending on how this cipher was initialized), processing another data
0N/A * part.
0N/A *
0N/A * <p>The first <code>inputLen</code> bytes in the <code>input</code>
0N/A * buffer, starting at <code>inputOffset</code>, are processed, and the
0N/A * result is stored in the <code>output</code> buffer, starting at
0N/A * <code>outputOffset</code>.
0N/A *
0N/A * @param input the input buffer
0N/A * @param inputOffset the offset in <code>input</code> where the input
0N/A * starts
0N/A * @param inputLen the input length
0N/A * @param output the buffer for the result
0N/A * @param outputOffset the offset in <code>output</code> where the result
0N/A * is stored
0N/A *
0N/A * @return the number of bytes stored in <code>output</code>
0N/A *
0N/A * @exception ShortBufferException if the given output buffer is too small
0N/A * to hold the result
0N/A */
0N/A int update(byte[] input, int inputOffset, int inputLen, byte[] output,
0N/A int outputOffset) throws ShortBufferException {
0N/A // figure out how much can be sent to crypto function
0N/A int len = buffered + inputLen - minBytes;
0N/A if (padding != null && decrypting) {
0N/A // do not include the padding bytes when decrypting
0N/A len -= blockSize;
0N/A }
0N/A // do not count the trailing bytes which do not make up a unit
0N/A len = (len > 0 ? (len - (len%unitBytes)) : 0);
0N/A
0N/A // check output buffer capacity
0N/A if ((output == null) || ((output.length - outputOffset) < len)) {
0N/A throw new ShortBufferException("Output buffer must be "
0N/A + "(at least) " + len
0N/A + " bytes long");
0N/A }
0N/A if (len != 0) {
0N/A // there is some work to do
0N/A byte[] in = new byte[len];
0N/A
0N/A int inputConsumed = len - buffered;
0N/A int bufferedConsumed = buffered;
0N/A if (inputConsumed < 0) {
0N/A inputConsumed = 0;
0N/A bufferedConsumed = len;
0N/A }
0N/A
0N/A if (buffered != 0) {
0N/A System.arraycopy(buffer, 0, in, 0, bufferedConsumed);
0N/A }
0N/A if (inputConsumed > 0) {
0N/A System.arraycopy(input, inputOffset, in,
0N/A bufferedConsumed, inputConsumed);
0N/A }
0N/A
0N/A if (decrypting) {
0N/A cipher.decrypt(in, 0, len, output, outputOffset);
0N/A } else {
0N/A cipher.encrypt(in, 0, len, output, outputOffset);
0N/A }
0N/A
0N/A // Let's keep track of how many bytes are needed to make
0N/A // the total input length a multiple of blocksize when
0N/A // padding is applied
0N/A if (unitBytes != blockSize) {
0N/A if (len < diffBlocksize)
0N/A diffBlocksize -= len;
0N/A else
0N/A diffBlocksize = blockSize -
0N/A ((len - diffBlocksize) % blockSize);
0N/A }
0N/A
0N/A inputLen -= inputConsumed;
0N/A inputOffset += inputConsumed;
0N/A outputOffset += len;
0N/A buffered -= bufferedConsumed;
0N/A if (buffered > 0) {
0N/A System.arraycopy(buffer, bufferedConsumed, buffer, 0,
0N/A buffered);
0N/A }
0N/A }
0N/A // left over again
0N/A if (inputLen > 0) {
0N/A System.arraycopy(input, inputOffset, buffer, buffered,
0N/A inputLen);
0N/A }
0N/A buffered += inputLen;
0N/A return len;
0N/A }
0N/A
0N/A /**
0N/A * Encrypts or decrypts data in a single-part operation,
0N/A * or finishes a multiple-part operation.
0N/A * The data is encrypted or decrypted, depending on how this cipher was
0N/A * initialized.
0N/A *
0N/A * <p>The first <code>inputLen</code> bytes in the <code>input</code>
0N/A * buffer, starting at <code>inputOffset</code>, and any input bytes that
0N/A * may have been buffered during a previous <code>update</code> operation,
0N/A * are processed, with padding (if requested) being applied.
0N/A * The result is stored in a new buffer.
0N/A *
0N/A * <p>The cipher is reset to its initial state (uninitialized) after this
0N/A * call.
0N/A *
0N/A * @param input the input buffer
0N/A * @param inputOffset the offset in <code>input</code> where the input
0N/A * starts
0N/A * @param inputLen the input length
0N/A *
0N/A * @return the new buffer with the result
0N/A *
0N/A * @exception IllegalBlockSizeException if this cipher is a block cipher,
0N/A * no padding has been requested (only in encryption mode), and the total
0N/A * input length of the data processed by this cipher is not a multiple of
0N/A * block size
0N/A * @exception BadPaddingException if this cipher is in decryption mode,
0N/A * and (un)padding has been requested, but the decrypted data is not
0N/A * bounded by the appropriate padding bytes
0N/A */
0N/A byte[] doFinal(byte[] input, int inputOffset, int inputLen)
0N/A throws IllegalBlockSizeException, BadPaddingException {
0N/A byte[] output = null;
0N/A byte[] out = null;
0N/A try {
0N/A output = new byte[getOutputSize(inputLen)];
0N/A int len = doFinal(input, inputOffset, inputLen, output, 0);
0N/A if (len < output.length) {
0N/A out = new byte[len];
0N/A if (len != 0)
0N/A System.arraycopy(output, 0, out, 0, len);
0N/A } else {
0N/A out = output;
0N/A }
0N/A } catch (ShortBufferException e) {
0N/A // never thrown
0N/A }
0N/A return out;
0N/A }
0N/A
0N/A /**
0N/A * Encrypts or decrypts data in a single-part operation,
0N/A * or finishes a multiple-part operation.
0N/A * The data is encrypted or decrypted, depending on how this cipher was
0N/A * initialized.
0N/A *
0N/A * <p>The first <code>inputLen</code> bytes in the <code>input</code>
0N/A * buffer, starting at <code>inputOffset</code>, and any input bytes that
0N/A * may have been buffered during a previous <code>update</code> operation,
0N/A * are processed, with padding (if requested) being applied.
0N/A * The result is stored in the <code>output</code> buffer, starting at
0N/A * <code>outputOffset</code>.
0N/A *
0N/A * <p>The cipher is reset to its initial state (uninitialized) after this
0N/A * call.
0N/A *
0N/A * @param input the input buffer
0N/A * @param inputOffset the offset in <code>input</code> where the input
0N/A * starts
0N/A * @param inputLen the input length
0N/A * @param output the buffer for the result
0N/A * @param outputOffset the offset in <code>output</code> where the result
0N/A * is stored
0N/A *
0N/A * @return the number of bytes stored in <code>output</code>
0N/A *
0N/A * @exception IllegalBlockSizeException if this cipher is a block cipher,
0N/A * no padding has been requested (only in encryption mode), and the total
0N/A * input length of the data processed by this cipher is not a multiple of
0N/A * block size
0N/A * @exception ShortBufferException if the given output buffer is too small
0N/A * to hold the result
0N/A * @exception BadPaddingException if this cipher is in decryption mode,
0N/A * and (un)padding has been requested, but the decrypted data is not
0N/A * bounded by the appropriate padding bytes
0N/A */
0N/A int doFinal(byte[] input, int inputOffset, int inputLen, byte[] output,
0N/A int outputOffset)
0N/A throws IllegalBlockSizeException, ShortBufferException,
0N/A BadPaddingException {
0N/A
0N/A // calculate the total input length
0N/A int totalLen = buffered + inputLen;
0N/A int paddedLen = totalLen;
0N/A int paddingLen = 0;
0N/A
0N/A // will the total input length be a multiple of blockSize?
0N/A if (unitBytes != blockSize) {
0N/A if (totalLen < diffBlocksize) {
0N/A paddingLen = diffBlocksize - totalLen;
0N/A } else {
0N/A paddingLen = blockSize -
0N/A ((totalLen - diffBlocksize) % blockSize);
0N/A }
0N/A } else if (padding != null) {
0N/A paddingLen = padding.padLength(totalLen);
0N/A }
0N/A
0N/A if ((paddingLen > 0) && (paddingLen != blockSize) &&
0N/A (padding != null) && decrypting) {
0N/A throw new IllegalBlockSizeException
0N/A ("Input length must be multiple of " + blockSize +
0N/A " when decrypting with padded cipher");
0N/A }
0N/A
0N/A // if encrypting and padding not null, add padding
0N/A if (!decrypting && padding != null)
0N/A paddedLen += paddingLen;
0N/A
0N/A // check output buffer capacity.
0N/A // if we are decrypting with padding applied, we can perform this
0N/A // check only after we have determined how many padding bytes there
0N/A // are.
0N/A if (output == null) {
0N/A throw new ShortBufferException("Output buffer is null");
0N/A }
0N/A int outputCapacity = output.length - outputOffset;
0N/A if (((!decrypting) || (padding == null)) &&
0N/A (outputCapacity < paddedLen) ||
0N/A (decrypting && (outputCapacity < (paddedLen - blockSize)))) {
0N/A throw new ShortBufferException("Output buffer too short: "
0N/A + outputCapacity + " bytes given, "
0N/A + paddedLen + " bytes needed");
0N/A }
0N/A
0N/A // prepare the final input avoiding copying if possible
0N/A byte[] finalBuf = input;
0N/A int finalOffset = inputOffset;
0N/A if ((buffered != 0) || (!decrypting && padding != null)) {
0N/A finalOffset = 0;
0N/A finalBuf = new byte[paddedLen];
0N/A if (buffered != 0) {
0N/A System.arraycopy(buffer, 0, finalBuf, 0, buffered);
0N/A }
0N/A if (inputLen != 0) {
0N/A System.arraycopy(input, inputOffset, finalBuf,
0N/A buffered, inputLen);
0N/A }
0N/A if (!decrypting && padding != null) {
0N/A padding.padWithLen(finalBuf, totalLen, paddingLen);
0N/A }
0N/A }
0N/A
0N/A if (decrypting) {
0N/A // if the size of specified output buffer is less than
0N/A // the length of the cipher text, then the current
0N/A // content of cipher has to be preserved in order for
0N/A // users to retry the call with a larger buffer in the
0N/A // case of ShortBufferException.
0N/A if (outputCapacity < paddedLen) {
0N/A cipher.save();
0N/A }
0N/A // create temporary output buffer so that only "real"
0N/A // data bytes are passed to user's output buffer.
0N/A byte[] outWithPadding = new byte[totalLen];
0N/A totalLen = finalNoPadding(finalBuf, finalOffset, outWithPadding,
0N/A 0, totalLen);
0N/A
0N/A if (padding != null) {
0N/A int padStart = padding.unpad(outWithPadding, 0, totalLen);
0N/A if (padStart < 0) {
0N/A throw new BadPaddingException("Given final block not "
0N/A + "properly padded");
0N/A }
0N/A totalLen = padStart;
0N/A }
0N/A if ((output.length - outputOffset) < totalLen) {
0N/A // restore so users can retry with a larger buffer
0N/A cipher.restore();
0N/A throw new ShortBufferException("Output buffer too short: "
0N/A + (output.length-outputOffset)
0N/A + " bytes given, " + totalLen
0N/A + " bytes needed");
0N/A }
0N/A for (int i = 0; i < totalLen; i++) {
0N/A output[outputOffset + i] = outWithPadding[i];
0N/A }
0N/A } else { // encrypting
0N/A totalLen = finalNoPadding(finalBuf, finalOffset, output,
0N/A outputOffset, paddedLen);
0N/A }
0N/A
0N/A buffered = 0;
0N/A diffBlocksize = blockSize;
0N/A if (cipherMode != ECB_MODE) {
0N/A ((FeedbackCipher)cipher).reset();
0N/A }
0N/A return totalLen;
0N/A }
0N/A
0N/A private int finalNoPadding(byte[] in, int inOff, byte[] out, int outOff,
0N/A int len)
0N/A throws IllegalBlockSizeException
0N/A {
0N/A if (in == null || len == 0)
0N/A return 0;
0N/A
0N/A if ((cipherMode != CFB_MODE) && (cipherMode != OFB_MODE)
0N/A && ((len % unitBytes) != 0) && (cipherMode != CTS_MODE)) {
0N/A if (padding != null) {
0N/A throw new IllegalBlockSizeException
0N/A ("Input length (with padding) not multiple of " +
0N/A unitBytes + " bytes");
0N/A } else {
0N/A throw new IllegalBlockSizeException
0N/A ("Input length not multiple of " + unitBytes
0N/A + " bytes");
0N/A }
0N/A }
0N/A
0N/A if (decrypting) {
0N/A cipher.decryptFinal(in, inOff, len, out, outOff);
0N/A } else {
0N/A cipher.encryptFinal(in, inOff, len, out, outOff);
0N/A }
0N/A
0N/A return len;
0N/A }
0N/A
0N/A // Note: Wrap() and Unwrap() are the same in
0N/A // each of SunJCE CipherSpi implementation classes.
0N/A // They are duplicated due to export control requirements:
0N/A // All CipherSpi implementation must be final.
0N/A /**
0N/A * Wrap a key.
0N/A *
0N/A * @param key the key to be wrapped.
0N/A *
0N/A * @return the wrapped key.
0N/A *
0N/A * @exception IllegalBlockSizeException if this cipher is a block
0N/A * cipher, no padding has been requested, and the length of the
0N/A * encoding of the key to be wrapped is not a
0N/A * multiple of the block size.
0N/A *
0N/A * @exception InvalidKeyException if it is impossible or unsafe to
0N/A * wrap the key with this cipher (e.g., a hardware protected key is
0N/A * being passed to a software only cipher).
0N/A */
0N/A byte[] wrap(Key key)
0N/A throws IllegalBlockSizeException, InvalidKeyException {
0N/A byte[] result = null;
0N/A
0N/A try {
0N/A byte[] encodedKey = key.getEncoded();
0N/A if ((encodedKey == null) || (encodedKey.length == 0)) {
0N/A throw new InvalidKeyException("Cannot get an encoding of " +
0N/A "the key to be wrapped");
0N/A }
0N/A result = doFinal(encodedKey, 0, encodedKey.length);
0N/A } catch (BadPaddingException e) {
0N/A // Should never happen
0N/A }
0N/A return result;
0N/A }
0N/A
0N/A /**
0N/A * Unwrap a previously wrapped key.
0N/A *
0N/A * @param wrappedKey the key to be unwrapped.
0N/A *
0N/A * @param wrappedKeyAlgorithm the algorithm the wrapped key is for.
0N/A *
0N/A * @param wrappedKeyType the type of the wrapped key.
0N/A * This is one of <code>Cipher.SECRET_KEY</code>,
0N/A * <code>Cipher.PRIVATE_KEY</code>, or <code>Cipher.PUBLIC_KEY</code>.
0N/A *
0N/A * @return the unwrapped key.
0N/A *
0N/A * @exception NoSuchAlgorithmException if no installed providers
0N/A * can create keys of type <code>wrappedKeyType</code> for the
0N/A * <code>wrappedKeyAlgorithm</code>.
0N/A *
0N/A * @exception InvalidKeyException if <code>wrappedKey</code> does not
0N/A * represent a wrapped key of type <code>wrappedKeyType</code> for
0N/A * the <code>wrappedKeyAlgorithm</code>.
0N/A */
0N/A Key unwrap(byte[] wrappedKey, String wrappedKeyAlgorithm,
0N/A int wrappedKeyType)
0N/A throws InvalidKeyException, NoSuchAlgorithmException {
0N/A byte[] encodedKey;
0N/A try {
0N/A encodedKey = doFinal(wrappedKey, 0, wrappedKey.length);
0N/A } catch (BadPaddingException ePadding) {
0N/A throw new InvalidKeyException("The wrapped key is not padded " +
0N/A "correctly");
0N/A } catch (IllegalBlockSizeException eBlockSize) {
0N/A throw new InvalidKeyException("The wrapped key does not have " +
0N/A "the correct length");
0N/A }
0N/A return ConstructKeys.constructKey(encodedKey, wrappedKeyAlgorithm,
0N/A wrappedKeyType);
0N/A }
0N/A}