001: /*
002: *
003: *
004: * Copyright 1990-2007 Sun Microsystems, Inc. All Rights Reserved.
005: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
006: *
007: * This program is free software; you can redistribute it and/or
008: * modify it under the terms of the GNU General Public License version
009: * 2 only, as published by the Free Software Foundation.
010: *
011: * This program is distributed in the hope that it will be useful, but
012: * WITHOUT ANY WARRANTY; without even the implied warranty of
013: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
014: * General Public License version 2 for more details (a copy is
015: * included at /legal/license.txt).
016: *
017: * You should have received a copy of the GNU General Public License
018: * version 2 along with this work; if not, write to the Free Software
019: * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
020: * 02110-1301 USA
021: *
022: * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
023: * Clara, CA 95054 or visit www.sun.com if you need additional
024: * information or have any questions.
025: */
026:
027: package com.sun.midp.crypto;
028:
029: /**
030: * Implements an abstract class that generalizes all ciphers. It is
031: * modelled after javax.crypto.Cipher.
032: */
033: public abstract class Cipher {
034: /**
035: * Flag to indicate the current cipher algorithm is unknown.
036: */
037: protected static final int MODE_UNINITIALIZED = 0;
038:
039: /** Used in init to indicate encryption mode. */
040: public static final int ENCRYPT_MODE = 1;
041:
042: /** Used in init to indicate decryption mode. */
043: public static final int DECRYPT_MODE = 2;
044:
045: /** Protected constructor. */
046: protected Cipher() {
047: }
048:
049: /**
050: * Called by the factory method to set the mode and padding parameters.
051: * Need because Class.newInstance does not take args.
052: *
053: * @param mode the chaining mode parsed from the transformation parameter
054: * of getInstance and upper cased
055: * @param padding the paddinge parsed from the transformation parameter of
056: * getInstance and upper cased
057: *
058: * @exception NoSuchPaddingException if <code>transformation</code>
059: * contains a padding scheme that is not available.
060: */
061: protected abstract void setChainingModeAndPadding(String mode,
062: String padding) throws NoSuchPaddingException;
063:
064: /**
065: * Generates a <code>Cipher</code> object that implements the specified
066: * transformation.
067: *
068: * @param transformation the name of the transformation, e.g.,
069: * <i>DES/CBC/PKCS5Padding</i>.
070: * See Appendix A in the
071: * <a href="../../../guide/security/jce/JCERefGuide.html#AppA">
072: * Java Cryptography Extension Reference Guide</a>
073: * for information about standard transformation names.
074: *
075: * @return a cipher that implements the requested transformation
076: *
077: * @exception NoSuchAlgorithmException if the specified transformation is
078: * not available
079: * @exception NoSuchPaddingException if <code>transformation</code>
080: * contains a padding scheme that is not available.
081: */
082: public static final Cipher getInstance(String transformation)
083: throws NoSuchAlgorithmException, NoSuchPaddingException {
084:
085: Cipher cipher = null;
086: String alg = ("" + transformation).toUpperCase().trim();
087: String chainingMode = "";
088: String padding = "";
089:
090: if (alg.indexOf("/") != -1) {
091: int first = alg.indexOf("/");
092: int second = alg.indexOf("/", first + 1);
093: if (second == alg.lastIndexOf('/')) {
094: chainingMode = alg.substring(first + 1, second).trim();
095: padding = alg.substring(second + 1).trim();
096: alg = alg.substring(0, first).trim();
097: }
098: }
099:
100: // We have the generic equivalent of RC4: ARC4 or ARCFOUR.
101: if (alg.equals("RC4") || alg.equals("ARCFOUR")) {
102: alg = "ARC4";
103: }
104:
105: try {
106: Class cipherClass;
107:
108: cipherClass = Class.forName("com.sun.midp.crypto." + alg);
109: cipher = (Cipher) cipherClass.newInstance();
110: } catch (Throwable t) {
111: throw new NoSuchAlgorithmException(transformation);
112: }
113:
114: try {
115: cipher.setChainingModeAndPadding(chainingMode, padding);
116: } catch (IllegalArgumentException iae) {
117: // throw NoSuchAlgorithmException if the chainingMode is invalid
118: // (setChainingModeAndPadding() throws IllegalArgumentException
119: // in this case)
120: throw new NoSuchAlgorithmException(transformation);
121: }
122:
123: return cipher;
124: }
125:
126: /**
127: * Initializes this cipher with a key.
128: *
129: * <p>The cipher is initialized for one of the following operations:
130: * encryption, decryption, depending
131: * on the value of <code>opmode</code>.
132: *
133: * <p>If this cipher requires any algorithm parameters that cannot be
134: * derived from the given <code>key</code>, the underlying cipher
135: * implementation is supposed to generate the required parameters itself
136: * (using provider-specific default or random values) if it is being
137: * initialized for encryption, and raise an
138: * <code>InvalidKeyException</code> if it is being
139: * initialized for decryption.
140: *
141: * <p>Note that when a Cipher object is initialized, it loses all
142: * previously-acquired state. In other words, initializing a Cipher is
143: * equivalent to creating a new instance of that Cipher and initializing
144: * it.
145: *
146: * @param opmode the operation mode of this cipher (this is one of
147: * the following:
148: * <code>ENCRYPT_MODE</code> or <code>DECRYPT_MODE</code>)
149: * @param key the key
150: *
151: * @exception InvalidKeyException if the given key is inappropriate for
152: * initializing this cipher, or if this cipher is being initialized for
153: * decryption and requires algorithm parameters that cannot be
154: * determined from the given key, or if the given key has a keysize that
155: * exceeds the maximum allowable keysize.
156: */
157: public void init(int opmode, Key key) throws InvalidKeyException {
158: try {
159: init(opmode, key, null);
160: } catch (InvalidAlgorithmParameterException e) {
161: throw new InvalidKeyException();
162: }
163: }
164:
165: /**
166: * Initializes this cipher with a key and a set of algorithm
167: * parameters.
168: *
169: * <p>The cipher is initialized for one of the following operations:
170: * encryption or decryption depending
171: * on the value of <code>opmode</code>.
172: *
173: * <p>If this cipher requires any algorithm parameters and
174: * <code>params</code> is null, the underlying cipher implementation is
175: * supposed to generate the required parameters itself (using
176: * provider-specific default or random values) if it is being
177: * initialized for encryption, and raise an
178: * <code>InvalidAlgorithmParameterException</code> if it is being
179: * initialized for decryption.
180: *
181: * <p>Note that when a Cipher object is initialized, it loses all
182: * previously-acquired state. In other words, initializing a Cipher is
183: * equivalent to creating a new instance of that Cipher and initializing
184: * it.
185: *
186: * @param opmode the operation mode of this cipher (this is one of the
187: * following:
188: * <code>ENCRYPT_MODE</code> or <code>DECRYPT_MODE</code>)
189: * @param key the encryption key
190: * @param params the algorithm parameters
191: *
192: * @exception InvalidKeyException if the given key is inappropriate for
193: * initializing this cipher, or its keysize exceeds the maximum allowable
194: * keysize.
195: * @exception InvalidAlgorithmParameterException if the given algorithm
196: * parameters are inappropriate for this cipher,
197: * or this cipher is being initialized for decryption and requires
198: * algorithm parameters and <code>params</code> is null, or the given
199: * algorithm parameters imply a cryptographic strength that would exceed
200: * the legal limits.
201: */
202: public abstract void init(int opmode, Key key,
203: CryptoParameter params) throws InvalidKeyException,
204: InvalidAlgorithmParameterException;
205:
206: /**
207: * Continues a multiple-part encryption or decryption operation
208: * (depending on how this cipher was initialized), processing another data
209: * part.
210: *
211: * <p>The first <code>inputLen</code> bytes in the <code>input</code>
212: * buffer, starting at <code>inputOffset</code> inclusive, are processed,
213: * and the result is stored in the <code>output</code> buffer, starting at
214: * <code>outputOffset</code> inclusive.
215: *
216: * <p>If the <code>output</code> buffer is too small to hold the result,
217: * a <code>ShortBufferException</code> is thrown. In this case, repeat this
218: * call with a larger output buffer.
219: *
220: * <p>If <code>inputLen</code> is zero, this method returns
221: * a length of zero.
222: *
223: * <p>Note: this method should be copy-safe, which means the
224: * <code>input</code> and <code>output</code> buffers can reference
225: * the same byte array and no unprocessed input data is overwritten
226: * when the result is copied into the output buffer.
227: *
228: * @param input the input buffer
229: * @param inputOffset the offset in <code>input</code> where the input
230: * starts
231: * @param inputLen the input length
232: * @param output the buffer for the result
233: * @param outputOffset the offset in <code>output</code> where the result
234: * is stored
235: *
236: * @return the number of bytes stored in <code>output</code>
237: *
238: * @exception IllegalStateException if this cipher is in a wrong state
239: * (e.g., has not been initialized)
240: * @exception ShortBufferException if the given output buffer is too small
241: * to hold the result
242: */
243: public abstract int update(byte[] input, int inputOffset,
244: int inputLen, byte[] output, int outputOffset)
245: throws IllegalStateException, ShortBufferException;
246:
247: /**
248: * Encrypts or decrypts data in a single-part operation, or finishes a
249: * multiple-part operation. The data is encrypted or decrypted,
250: * depending on how this cipher was initialized.
251: *
252: * <p>The first <code>inputLen</code> bytes in the <code>input</code>
253: * buffer, starting at <code>inputOffset</code> inclusive, and any input
254: * bytes that may have been buffered during a previous
255: * <code>update</code> operation, are processed, with padding
256: * (if requested) being applied.
257: * The result is stored in the <code>output</code> buffer, starting at
258: * <code>outputOffset</code> inclusive.
259: *
260: * <p>If the <code>output</code> buffer is too small to hold the result,
261: * a <code>ShortBufferException</code> is thrown. In this case, repeat this
262: * call with a larger output buffer.
263: *
264: * <p>Upon finishing, this method resets this cipher object to the state
265: * it was in when previously initialized via a call to <code>init</code>.
266: * That is, the object is reset and available to encrypt or decrypt
267: * (depending on the operation mode that was specified in the call to
268: * <code>init</code>) more data.
269: *
270: * <p>Note: if any exception is thrown, this cipher object may need to
271: * be reset before it can be used again.
272: *
273: * <p>Note: this method should be copy-safe, which means the
274: * <code>input</code> and <code>output</code> buffers can reference
275: * the same byte array and no unprocessed input data is overwritten
276: * when the result is copied into the output buffer.
277: *
278: * @param input the input buffer
279: * @param inputOffset the offset in <code>input</code> where the input
280: * starts
281: * @param inputLen the input length
282: * @param output the buffer for the result
283: * @param outputOffset the offset in <code>output</code> where the result
284: * is stored
285: *
286: * @return the number of bytes stored in <code>output</code>
287: *
288: * @exception IllegalStateException if this cipher is in a wrong state
289: * (e.g., has not been initialized)
290: * @exception IllegalBlockSizeException if this cipher is a block cipher,
291: * no padding has been requested (only in encryption mode), and the total
292: * input length of the data processed by this cipher is not a multiple of
293: * block size
294: * @exception ShortBufferException if the given output buffer is too small
295: * to hold the result
296: * @exception BadPaddingException if this cipher is in decryption mode,
297: * and (un)padding has been requested, but the decrypted data is not
298: * bounded by the appropriate padding bytes
299: */
300: public abstract int doFinal(byte[] input, int inputOffset,
301: int inputLen, byte[] output, int outputOffset)
302: throws IllegalStateException, ShortBufferException,
303: IllegalBlockSizeException, BadPaddingException;
304:
305: /**
306: * Returns the initialization vector (IV) in a new buffer.
307: * This is useful in the case where a random IV was created.
308: * @return the initialization vector in a new buffer,
309: * or <code>null</code> if the underlying algorithm does
310: * not use an IV, or if the IV has not yet been set.
311: */
312: public byte[] getIV() {
313: return null;
314: }
315: }
|