author | valeriep |
Tue, 08 May 2012 17:57:48 -0700 | |
changeset 12685 | 8a448b5b9006 |
parent 10336 | 0bb1999251f8 |
child 15008 | 6a494f8ba5b5 |
permissions | -rw-r--r-- |
2 | 1 |
/* |
10336
0bb1999251f8
7064075: Security libraries don't build with javac -Xlint:all,-deprecation -Werror
jjg
parents:
5506
diff
changeset
|
2 |
* Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved. |
2 | 3 |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. |
4 |
* |
|
5 |
* This code is free software; you can redistribute it and/or modify it |
|
6 |
* under the terms of the GNU General Public License version 2 only, as |
|
5506 | 7 |
* published by the Free Software Foundation. Oracle designates this |
2 | 8 |
* particular file as subject to the "Classpath" exception as provided |
5506 | 9 |
* by Oracle in the LICENSE file that accompanied this code. |
2 | 10 |
* |
11 |
* This code is distributed in the hope that it will be useful, but WITHOUT |
|
12 |
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
|
13 |
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
|
14 |
* version 2 for more details (a copy is included in the LICENSE file that |
|
15 |
* accompanied this code). |
|
16 |
* |
|
17 |
* You should have received a copy of the GNU General Public License version |
|
18 |
* 2 along with this work; if not, write to the Free Software Foundation, |
|
19 |
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. |
|
20 |
* |
|
5506 | 21 |
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA |
22 |
* or visit www.oracle.com if you need additional information or have any |
|
23 |
* questions. |
|
2 | 24 |
*/ |
25 |
||
26 |
package com.sun.crypto.provider; |
|
27 |
||
28 |
import java.util.Locale; |
|
29 |
||
30 |
import java.security.*; |
|
31 |
import java.security.spec.*; |
|
32 |
import javax.crypto.*; |
|
33 |
import javax.crypto.spec.*; |
|
34 |
import javax.crypto.BadPaddingException; |
|
35 |
||
36 |
/** |
|
37 |
* This class represents the symmetric algorithms in its various modes |
|
38 |
* (<code>ECB</code>, <code>CFB</code>, <code>OFB</code>, <code>CBC</code>, |
|
39 |
* <code>PCBC</code>, <code>CTR</code>, and <code>CTS</code>) and |
|
40 |
* padding schemes (<code>PKCS5Padding</code>, <code>NoPadding</code>, |
|
41 |
* <code>ISO10126Padding</code>). |
|
42 |
* |
|
43 |
* @author Gigi Ankeny |
|
44 |
* @author Jan Luehe |
|
45 |
* @see ElectronicCodeBook |
|
46 |
* @see CipherFeedback |
|
47 |
* @see OutputFeedback |
|
48 |
* @see CipherBlockChaining |
|
49 |
* @see PCBC |
|
50 |
* @see CounterMode |
|
51 |
* @see CipherTextStealing |
|
52 |
*/ |
|
53 |
||
54 |
final class CipherCore { |
|
55 |
||
56 |
/* |
|
57 |
* internal buffer |
|
58 |
*/ |
|
59 |
private byte[] buffer = null; |
|
60 |
||
61 |
/* |
|
62 |
* internal buffer |
|
63 |
*/ |
|
64 |
private int blockSize = 0; |
|
65 |
||
66 |
/* |
|
67 |
* unit size (number of input bytes that can be processed at a time) |
|
68 |
*/ |
|
69 |
private int unitBytes = 0; |
|
70 |
||
71 |
/* |
|
72 |
* index of the content size left in the buffer |
|
73 |
*/ |
|
74 |
private int buffered = 0; |
|
75 |
||
76 |
/* |
|
77 |
* minimum number of bytes in the buffer required for |
|
78 |
* FeedbackCipher.encryptFinal()/decryptFinal() call. |
|
79 |
* update() must buffer this many bytes before before starting |
|
80 |
* to encrypt/decrypt data. |
|
81 |
* currently, only CTS mode has a non-zero value due to its special |
|
82 |
* handling on the last two blocks (the last one may be incomplete). |
|
83 |
*/ |
|
84 |
private int minBytes = 0; |
|
85 |
||
86 |
/* |
|
87 |
* number of bytes needed to make the total input length a multiple |
|
88 |
* of the blocksize (this is used in feedback mode, when the number of |
|
89 |
* input bytes that are processed at a time is different from the block |
|
90 |
* size) |
|
91 |
*/ |
|
92 |
private int diffBlocksize = 0; |
|
93 |
||
94 |
/* |
|
95 |
* padding class |
|
96 |
*/ |
|
97 |
private Padding padding = null; |
|
98 |
||
99 |
/* |
|
100 |
* internal cipher engine |
|
101 |
*/ |
|
102 |
private FeedbackCipher cipher = null; |
|
103 |
||
104 |
/* |
|
105 |
* the cipher mode |
|
106 |
*/ |
|
107 |
private int cipherMode = ECB_MODE; |
|
108 |
||
109 |
/* |
|
110 |
* are we encrypting or decrypting? |
|
111 |
*/ |
|
112 |
private boolean decrypting = false; |
|
113 |
||
114 |
/* |
|
115 |
* Block Mode constants |
|
116 |
*/ |
|
117 |
private static final int ECB_MODE = 0; |
|
118 |
private static final int CBC_MODE = 1; |
|
119 |
private static final int CFB_MODE = 2; |
|
120 |
private static final int OFB_MODE = 3; |
|
121 |
private static final int PCBC_MODE = 4; |
|
122 |
private static final int CTR_MODE = 5; |
|
123 |
private static final int CTS_MODE = 6; |
|
124 |
||
125 |
/** |
|
126 |
* Creates an instance of CipherCore with default ECB mode and |
|
127 |
* PKCS5Padding. |
|
128 |
*/ |
|
129 |
CipherCore(SymmetricCipher impl, int blkSize) { |
|
130 |
blockSize = blkSize; |
|
131 |
unitBytes = blkSize; |
|
132 |
diffBlocksize = blkSize; |
|
133 |
||
134 |
/* |
|
135 |
* The buffer should be usable for all cipher mode and padding |
|
136 |
* schemes. Thus, it has to be at least (blockSize+1) for CTS. |
|
137 |
* In decryption mode, it also hold the possible padding block. |
|
138 |
*/ |
|
139 |
buffer = new byte[blockSize*2]; |
|
140 |
||
141 |
// set mode and padding |
|
142 |
cipher = new ElectronicCodeBook(impl); |
|
143 |
padding = new PKCS5Padding(blockSize); |
|
144 |
} |
|
145 |
||
146 |
/** |
|
147 |
* Sets the mode of this cipher. |
|
148 |
* |
|
149 |
* @param mode the cipher mode |
|
150 |
* |
|
151 |
* @exception NoSuchAlgorithmException if the requested cipher mode does |
|
152 |
* not exist |
|
153 |
*/ |
|
154 |
void setMode(String mode) throws NoSuchAlgorithmException { |
|
155 |
if (mode == null) |
|
156 |
throw new NoSuchAlgorithmException("null mode"); |
|
157 |
||
158 |
String modeUpperCase = mode.toUpperCase(Locale.ENGLISH); |
|
159 |
||
160 |
if (modeUpperCase.equals("ECB")) { |
|
161 |
return; |
|
162 |
} |
|
163 |
||
164 |
SymmetricCipher rawImpl = cipher.getEmbeddedCipher(); |
|
165 |
if (modeUpperCase.equals("CBC")) { |
|
166 |
cipherMode = CBC_MODE; |
|
167 |
cipher = new CipherBlockChaining(rawImpl); |
|
168 |
} |
|
169 |
else if (modeUpperCase.equals("CTS")) { |
|
170 |
cipherMode = CTS_MODE; |
|
171 |
cipher = new CipherTextStealing(rawImpl); |
|
172 |
minBytes = blockSize+1; |
|
173 |
padding = null; |
|
174 |
} |
|
175 |
else if (modeUpperCase.equals("CTR")) { |
|
176 |
cipherMode = CTR_MODE; |
|
177 |
cipher = new CounterMode(rawImpl); |
|
178 |
unitBytes = 1; |
|
179 |
padding = null; |
|
180 |
} |
|
181 |
else if (modeUpperCase.startsWith("CFB")) { |
|
182 |
cipherMode = CFB_MODE; |
|
183 |
unitBytes = getNumOfUnit(mode, "CFB".length(), blockSize); |
|
184 |
cipher = new CipherFeedback(rawImpl, unitBytes); |
|
185 |
} |
|
186 |
else if (modeUpperCase.startsWith("OFB")) { |
|
187 |
cipherMode = OFB_MODE; |
|
188 |
unitBytes = getNumOfUnit(mode, "OFB".length(), blockSize); |
|
189 |
cipher = new OutputFeedback(rawImpl, unitBytes); |
|
190 |
} |
|
191 |
else if (modeUpperCase.equals("PCBC")) { |
|
192 |
cipherMode = PCBC_MODE; |
|
193 |
cipher = new PCBC(rawImpl); |
|
194 |
} |
|
195 |
else { |
|
196 |
throw new NoSuchAlgorithmException("Cipher mode: " + mode |
|
197 |
+ " not found"); |
|
198 |
} |
|
199 |
} |
|
200 |
||
201 |
private static int getNumOfUnit(String mode, int offset, int blockSize) |
|
202 |
throws NoSuchAlgorithmException { |
|
203 |
int result = blockSize; // use blockSize as default value |
|
204 |
if (mode.length() > offset) { |
|
205 |
int numInt; |
|
206 |
try { |
|
207 |
Integer num = Integer.valueOf(mode.substring(offset)); |
|
208 |
numInt = num.intValue(); |
|
209 |
result = numInt >> 3; |
|
210 |
} catch (NumberFormatException e) { |
|
211 |
throw new NoSuchAlgorithmException |
|
212 |
("Algorithm mode: " + mode + " not implemented"); |
|
213 |
} |
|
214 |
if ((numInt % 8 != 0) || (result > blockSize)) { |
|
215 |
throw new NoSuchAlgorithmException |
|
216 |
("Invalid algorithm mode: " + mode); |
|
217 |
} |
|
218 |
} |
|
219 |
return result; |
|
220 |
} |
|
221 |
||
222 |
/** |
|
223 |
* Sets the padding mechanism of this cipher. |
|
224 |
* |
|
225 |
* @param padding the padding mechanism |
|
226 |
* |
|
227 |
* @exception NoSuchPaddingException if the requested padding mechanism |
|
228 |
* does not exist |
|
229 |
*/ |
|
230 |
void setPadding(String paddingScheme) |
|
231 |
throws NoSuchPaddingException |
|
232 |
{ |
|
233 |
if (paddingScheme == null) { |
|
234 |
throw new NoSuchPaddingException("null padding"); |
|
235 |
} |
|
236 |
if (paddingScheme.equalsIgnoreCase("NoPadding")) { |
|
237 |
padding = null; |
|
238 |
} else if (paddingScheme.equalsIgnoreCase("ISO10126Padding")) { |
|
239 |
padding = new ISO10126Padding(blockSize); |
|
240 |
} else if (!paddingScheme.equalsIgnoreCase("PKCS5Padding")) { |
|
241 |
throw new NoSuchPaddingException("Padding: " + paddingScheme |
|
242 |
+ " not implemented"); |
|
243 |
} |
|
244 |
if ((padding != null) && |
|
245 |
((cipherMode == CTR_MODE) || (cipherMode == CTS_MODE))) { |
|
246 |
padding = null; |
|
247 |
throw new NoSuchPaddingException |
|
248 |
((cipherMode == CTR_MODE? "CTR":"CTS") + |
|
249 |
" mode must be used with NoPadding"); |
|
250 |
} |
|
251 |
} |
|
252 |
||
253 |
/** |
|
254 |
* Returns the length in bytes that an output buffer would need to be in |
|
255 |
* order to hold the result of the next <code>update</code> or |
|
256 |
* <code>doFinal</code> operation, given the input length |
|
257 |
* <code>inputLen</code> (in bytes). |
|
258 |
* |
|
259 |
* <p>This call takes into account any unprocessed (buffered) data from a |
|
260 |
* previous <code>update</code> call, and padding. |
|
261 |
* |
|
262 |
* <p>The actual output length of the next <code>update</code> or |
|
263 |
* <code>doFinal</code> call may be smaller than the length returned by |
|
264 |
* this method. |
|
265 |
* |
|
266 |
* @param inputLen the input length (in bytes) |
|
267 |
* |
|
268 |
* @return the required output buffer size (in bytes) |
|
269 |
*/ |
|
270 |
int getOutputSize(int inputLen) { |
|
271 |
int totalLen = buffered + inputLen; |
|
272 |
||
273 |
if (padding == null) |
|
274 |
return totalLen; |
|
275 |
||
276 |
if (decrypting) |
|
277 |
return totalLen; |
|
278 |
||
279 |
if (unitBytes != blockSize) { |
|
280 |
if (totalLen < diffBlocksize) |
|
281 |
return diffBlocksize; |
|
282 |
else |
|
283 |
return (totalLen + blockSize - |
|
284 |
((totalLen - diffBlocksize) % blockSize)); |
|
285 |
} else { |
|
286 |
return totalLen + padding.padLength(totalLen); |
|
287 |
} |
|
288 |
} |
|
289 |
||
290 |
/** |
|
291 |
* Returns the initialization vector (IV) in a new buffer. |
|
292 |
* |
|
293 |
* <p>This is useful in the case where a random IV has been created |
|
294 |
* (see <a href = "#init">init</a>), |
|
295 |
* or in the context of password-based encryption or |
|
296 |
* decryption, where the IV is derived from a user-provided password. |
|
297 |
* |
|
298 |
* @return the initialization vector in a new buffer, or null if the |
|
299 |
* underlying algorithm does not use an IV, or if the IV has not yet |
|
300 |
* been set. |
|
301 |
*/ |
|
302 |
byte[] getIV() { |
|
303 |
byte[] iv = cipher.getIV(); |
|
10336
0bb1999251f8
7064075: Security libraries don't build with javac -Xlint:all,-deprecation -Werror
jjg
parents:
5506
diff
changeset
|
304 |
return (iv == null) ? null : iv.clone(); |
2 | 305 |
} |
306 |
||
307 |
/** |
|
308 |
* Returns the parameters used with this cipher. |
|
309 |
* |
|
310 |
* <p>The returned parameters may be the same that were used to initialize |
|
311 |
* this cipher, or may contain the default set of parameters or a set of |
|
312 |
* randomly generated parameters used by the underlying cipher |
|
313 |
* implementation (provided that the underlying cipher implementation |
|
314 |
* uses a default set of parameters or creates new parameters if it needs |
|
315 |
* parameters but was not initialized with any). |
|
316 |
* |
|
317 |
* @return the parameters used with this cipher, or null if this cipher |
|
318 |
* does not use any parameters. |
|
319 |
*/ |
|
320 |
AlgorithmParameters getParameters(String algName) { |
|
321 |
AlgorithmParameters params = null; |
|
322 |
if (cipherMode == ECB_MODE) return null; |
|
323 |
byte[] iv = getIV(); |
|
324 |
if (iv != null) { |
|
325 |
AlgorithmParameterSpec ivSpec; |
|
326 |
if (algName.equals("RC2")) { |
|
327 |
RC2Crypt rawImpl = (RC2Crypt) cipher.getEmbeddedCipher(); |
|
328 |
ivSpec = new RC2ParameterSpec(rawImpl.getEffectiveKeyBits(), |
|
329 |
iv); |
|
330 |
} else { |
|
331 |
ivSpec = new IvParameterSpec(iv); |
|
332 |
} |
|
333 |
try { |
|
334 |
params = AlgorithmParameters.getInstance(algName, "SunJCE"); |
|
335 |
} catch (NoSuchAlgorithmException nsae) { |
|
336 |
// should never happen |
|
337 |
throw new RuntimeException("Cannot find " + algName + |
|
338 |
" AlgorithmParameters implementation in SunJCE provider"); |
|
339 |
} catch (NoSuchProviderException nspe) { |
|
340 |
// should never happen |
|
341 |
throw new RuntimeException("Cannot find SunJCE provider"); |
|
342 |
} |
|
343 |
try { |
|
344 |
params.init(ivSpec); |
|
345 |
} catch (InvalidParameterSpecException ipse) { |
|
346 |
// should never happen |
|
347 |
throw new RuntimeException("IvParameterSpec not supported"); |
|
348 |
} |
|
349 |
} |
|
350 |
return params; |
|
351 |
} |
|
352 |
||
353 |
/** |
|
354 |
* Initializes this cipher with a key and a source of randomness. |
|
355 |
* |
|
356 |
* <p>The cipher is initialized for one of the following four operations: |
|
357 |
* encryption, decryption, key wrapping or key unwrapping, depending on |
|
358 |
* the value of <code>opmode</code>. |
|
359 |
* |
|
360 |
* <p>If this cipher requires an initialization vector (IV), it will get |
|
361 |
* it from <code>random</code>. |
|
362 |
* This behaviour should only be used in encryption or key wrapping |
|
363 |
* mode, however. |
|
364 |
* When initializing a cipher that requires an IV for decryption or |
|
365 |
* key unwrapping, the IV |
|
366 |
* (same IV that was used for encryption or key wrapping) must be provided |
|
367 |
* explicitly as a |
|
368 |
* parameter, in order to get the correct result. |
|
369 |
* |
|
370 |
* <p>This method also cleans existing buffer and other related state |
|
371 |
* information. |
|
372 |
* |
|
373 |
* @param opmode the operation mode of this cipher (this is one of |
|
374 |
* the following: |
|
375 |
* <code>ENCRYPT_MODE</code>, <code>DECRYPT_MODE</code>, |
|
376 |
* <code>WRAP_MODE</code> or <code>UNWRAP_MODE</code>) |
|
377 |
* @param key the secret key |
|
378 |
* @param random the source of randomness |
|
379 |
* |
|
380 |
* @exception InvalidKeyException if the given key is inappropriate for |
|
381 |
* initializing this cipher |
|
382 |
*/ |
|
383 |
void init(int opmode, Key key, SecureRandom random) |
|
384 |
throws InvalidKeyException { |
|
385 |
try { |
|
386 |
init(opmode, key, (AlgorithmParameterSpec)null, random); |
|
387 |
} catch (InvalidAlgorithmParameterException e) { |
|
388 |
throw new InvalidKeyException(e.getMessage()); |
|
389 |
} |
|
390 |
} |
|
391 |
||
392 |
/** |
|
393 |
* Initializes this cipher with a key, a set of |
|
394 |
* algorithm parameters, and a source of randomness. |
|
395 |
* |
|
396 |
* <p>The cipher is initialized for one of the following four operations: |
|
397 |
* encryption, decryption, key wrapping or key unwrapping, depending on |
|
398 |
* the value of <code>opmode</code>. |
|
399 |
* |
|
400 |
* <p>If this cipher (including its underlying feedback or padding scheme) |
|
401 |
* requires any random bytes, it will get them from <code>random</code>. |
|
402 |
* |
|
403 |
* @param opmode the operation mode of this cipher (this is one of |
|
404 |
* the following: |
|
405 |
* <code>ENCRYPT_MODE</code>, <code>DECRYPT_MODE</code>, |
|
406 |
* <code>WRAP_MODE</code> or <code>UNWRAP_MODE</code>) |
|
407 |
* @param key the encryption key |
|
408 |
* @param params the algorithm parameters |
|
409 |
* @param random the source of randomness |
|
410 |
* |
|
411 |
* @exception InvalidKeyException if the given key is inappropriate for |
|
412 |
* initializing this cipher |
|
413 |
* @exception InvalidAlgorithmParameterException if the given algorithm |
|
414 |
* parameters are inappropriate for this cipher |
|
415 |
*/ |
|
416 |
void init(int opmode, Key key, AlgorithmParameterSpec params, |
|
417 |
SecureRandom random) |
|
418 |
throws InvalidKeyException, InvalidAlgorithmParameterException { |
|
419 |
decrypting = (opmode == Cipher.DECRYPT_MODE) |
|
420 |
|| (opmode == Cipher.UNWRAP_MODE); |
|
421 |
||
422 |
byte[] keyBytes = getKeyBytes(key); |
|
423 |
||
424 |
byte[] ivBytes; |
|
425 |
if (params == null) { |
|
426 |
ivBytes = null; |
|
427 |
} else if (params instanceof IvParameterSpec) { |
|
428 |
ivBytes = ((IvParameterSpec)params).getIV(); |
|
429 |
if ((ivBytes == null) || (ivBytes.length != blockSize)) { |
|
430 |
throw new InvalidAlgorithmParameterException |
|
431 |
("Wrong IV length: must be " + blockSize + |
|
432 |
" bytes long"); |
|
433 |
} |
|
434 |
} else if (params instanceof RC2ParameterSpec) { |
|
435 |
ivBytes = ((RC2ParameterSpec)params).getIV(); |
|
436 |
if ((ivBytes != null) && (ivBytes.length != blockSize)) { |
|
437 |
throw new InvalidAlgorithmParameterException |
|
438 |
("Wrong IV length: must be " + blockSize + |
|
439 |
" bytes long"); |
|
440 |
} |
|
441 |
} else { |
|
442 |
throw new InvalidAlgorithmParameterException("Wrong parameter " |
|
443 |
+ "type: IV " |
|
444 |
+ "expected"); |
|
445 |
} |
|
446 |
||
447 |
if (cipherMode == ECB_MODE) { |
|
448 |
if (ivBytes != null) { |
|
449 |
throw new InvalidAlgorithmParameterException |
|
450 |
("ECB mode cannot use IV"); |
|
451 |
} |
|
452 |
} else if (ivBytes == null) { |
|
453 |
if (decrypting) { |
|
454 |
throw new InvalidAlgorithmParameterException("Parameters " |
|
455 |
+ "missing"); |
|
456 |
} |
|
457 |
if (random == null) { |
|
458 |
random = SunJCE.RANDOM; |
|
459 |
} |
|
460 |
ivBytes = new byte[blockSize]; |
|
461 |
random.nextBytes(ivBytes); |
|
462 |
} |
|
463 |
||
464 |
buffered = 0; |
|
465 |
diffBlocksize = blockSize; |
|
466 |
||
467 |
String algorithm = key.getAlgorithm(); |
|
468 |
||
469 |
cipher.init(decrypting, algorithm, keyBytes, ivBytes); |
|
470 |
} |
|
471 |
||
472 |
void init(int opmode, Key key, AlgorithmParameters params, |
|
473 |
SecureRandom random) |
|
474 |
throws InvalidKeyException, InvalidAlgorithmParameterException { |
|
475 |
IvParameterSpec ivSpec = null; |
|
476 |
if (params != null) { |
|
477 |
try { |
|
10336
0bb1999251f8
7064075: Security libraries don't build with javac -Xlint:all,-deprecation -Werror
jjg
parents:
5506
diff
changeset
|
478 |
ivSpec = params.getParameterSpec(IvParameterSpec.class); |
2 | 479 |
} catch (InvalidParameterSpecException ipse) { |
480 |
throw new InvalidAlgorithmParameterException("Wrong parameter " |
|
481 |
+ "type: IV " |
|
482 |
+ "expected"); |
|
483 |
} |
|
484 |
} |
|
485 |
init(opmode, key, ivSpec, random); |
|
486 |
} |
|
487 |
||
488 |
/** |
|
489 |
* Return the key bytes of the specified key. Throw an InvalidKeyException |
|
490 |
* if the key is not usable. |
|
491 |
*/ |
|
492 |
static byte[] getKeyBytes(Key key) throws InvalidKeyException { |
|
493 |
if (key == null) { |
|
494 |
throw new InvalidKeyException("No key given"); |
|
495 |
} |
|
496 |
// note: key.getFormat() may return null |
|
497 |
if (!"RAW".equalsIgnoreCase(key.getFormat())) { |
|
498 |
throw new InvalidKeyException("Wrong format: RAW bytes needed"); |
|
499 |
} |
|
500 |
byte[] keyBytes = key.getEncoded(); |
|
501 |
if (keyBytes == null) { |
|
502 |
throw new InvalidKeyException("RAW key bytes missing"); |
|
503 |
} |
|
504 |
return keyBytes; |
|
505 |
} |
|
506 |
||
507 |
/** |
|
508 |
* Continues a multiple-part encryption or decryption operation |
|
509 |
* (depending on how this cipher was initialized), processing another data |
|
510 |
* part. |
|
511 |
* |
|
512 |
* <p>The first <code>inputLen</code> bytes in the <code>input</code> |
|
513 |
* buffer, starting at <code>inputOffset</code>, are processed, and the |
|
514 |
* result is stored in a new buffer. |
|
515 |
* |
|
516 |
* @param input the input buffer |
|
517 |
* @param inputOffset the offset in <code>input</code> where the input |
|
518 |
* starts |
|
519 |
* @param inputLen the input length |
|
520 |
* |
|
521 |
* @return the new buffer with the result |
|
522 |
* |
|
523 |
* @exception IllegalStateException if this cipher is in a wrong state |
|
524 |
* (e.g., has not been initialized) |
|
525 |
*/ |
|
526 |
byte[] update(byte[] input, int inputOffset, int inputLen) { |
|
527 |
byte[] output = null; |
|
528 |
byte[] out = null; |
|
529 |
try { |
|
530 |
output = new byte[getOutputSize(inputLen)]; |
|
531 |
int len = update(input, inputOffset, inputLen, output, |
|
532 |
0); |
|
533 |
if (len == output.length) { |
|
534 |
out = output; |
|
535 |
} else { |
|
536 |
out = new byte[len]; |
|
537 |
System.arraycopy(output, 0, out, 0, len); |
|
538 |
} |
|
539 |
} catch (ShortBufferException e) { |
|
540 |
// never thrown |
|
541 |
} |
|
542 |
return out; |
|
543 |
} |
|
544 |
||
545 |
/** |
|
546 |
* Continues a multiple-part encryption or decryption operation |
|
547 |
* (depending on how this cipher was initialized), processing another data |
|
548 |
* part. |
|
549 |
* |
|
550 |
* <p>The first <code>inputLen</code> bytes in the <code>input</code> |
|
551 |
* buffer, starting at <code>inputOffset</code>, are processed, and the |
|
552 |
* result is stored in the <code>output</code> buffer, starting at |
|
553 |
* <code>outputOffset</code>. |
|
554 |
* |
|
555 |
* @param input the input buffer |
|
556 |
* @param inputOffset the offset in <code>input</code> where the input |
|
557 |
* starts |
|
558 |
* @param inputLen the input length |
|
559 |
* @param output the buffer for the result |
|
560 |
* @param outputOffset the offset in <code>output</code> where the result |
|
561 |
* is stored |
|
562 |
* |
|
563 |
* @return the number of bytes stored in <code>output</code> |
|
564 |
* |
|
565 |
* @exception ShortBufferException if the given output buffer is too small |
|
566 |
* to hold the result |
|
567 |
*/ |
|
568 |
int update(byte[] input, int inputOffset, int inputLen, byte[] output, |
|
569 |
int outputOffset) throws ShortBufferException { |
|
570 |
// figure out how much can be sent to crypto function |
|
571 |
int len = buffered + inputLen - minBytes; |
|
572 |
if (padding != null && decrypting) { |
|
573 |
// do not include the padding bytes when decrypting |
|
574 |
len -= blockSize; |
|
575 |
} |
|
576 |
// do not count the trailing bytes which do not make up a unit |
|
577 |
len = (len > 0 ? (len - (len%unitBytes)) : 0); |
|
578 |
||
579 |
// check output buffer capacity |
|
580 |
if ((output == null) || ((output.length - outputOffset) < len)) { |
|
581 |
throw new ShortBufferException("Output buffer must be " |
|
582 |
+ "(at least) " + len |
|
583 |
+ " bytes long"); |
|
584 |
} |
|
585 |
if (len != 0) { |
|
586 |
// there is some work to do |
|
587 |
byte[] in = new byte[len]; |
|
588 |
||
589 |
int inputConsumed = len - buffered; |
|
590 |
int bufferedConsumed = buffered; |
|
591 |
if (inputConsumed < 0) { |
|
592 |
inputConsumed = 0; |
|
593 |
bufferedConsumed = len; |
|
594 |
} |
|
595 |
||
596 |
if (buffered != 0) { |
|
597 |
System.arraycopy(buffer, 0, in, 0, bufferedConsumed); |
|
598 |
} |
|
599 |
if (inputConsumed > 0) { |
|
600 |
System.arraycopy(input, inputOffset, in, |
|
601 |
bufferedConsumed, inputConsumed); |
|
602 |
} |
|
603 |
||
604 |
if (decrypting) { |
|
605 |
cipher.decrypt(in, 0, len, output, outputOffset); |
|
606 |
} else { |
|
607 |
cipher.encrypt(in, 0, len, output, outputOffset); |
|
608 |
} |
|
609 |
||
610 |
// Let's keep track of how many bytes are needed to make |
|
611 |
// the total input length a multiple of blocksize when |
|
612 |
// padding is applied |
|
613 |
if (unitBytes != blockSize) { |
|
614 |
if (len < diffBlocksize) |
|
615 |
diffBlocksize -= len; |
|
616 |
else |
|
617 |
diffBlocksize = blockSize - |
|
618 |
((len - diffBlocksize) % blockSize); |
|
619 |
} |
|
620 |
||
621 |
inputLen -= inputConsumed; |
|
622 |
inputOffset += inputConsumed; |
|
623 |
outputOffset += len; |
|
624 |
buffered -= bufferedConsumed; |
|
625 |
if (buffered > 0) { |
|
626 |
System.arraycopy(buffer, bufferedConsumed, buffer, 0, |
|
627 |
buffered); |
|
628 |
} |
|
629 |
} |
|
630 |
// left over again |
|
631 |
if (inputLen > 0) { |
|
632 |
System.arraycopy(input, inputOffset, buffer, buffered, |
|
633 |
inputLen); |
|
634 |
} |
|
635 |
buffered += inputLen; |
|
636 |
return len; |
|
637 |
} |
|
638 |
||
639 |
/** |
|
640 |
* Encrypts or decrypts data in a single-part operation, |
|
641 |
* or finishes a multiple-part operation. |
|
642 |
* The data is encrypted or decrypted, depending on how this cipher was |
|
643 |
* initialized. |
|
644 |
* |
|
645 |
* <p>The first <code>inputLen</code> bytes in the <code>input</code> |
|
646 |
* buffer, starting at <code>inputOffset</code>, and any input bytes that |
|
647 |
* may have been buffered during a previous <code>update</code> operation, |
|
648 |
* are processed, with padding (if requested) being applied. |
|
649 |
* The result is stored in a new buffer. |
|
650 |
* |
|
651 |
* <p>The cipher is reset to its initial state (uninitialized) after this |
|
652 |
* call. |
|
653 |
* |
|
654 |
* @param input the input buffer |
|
655 |
* @param inputOffset the offset in <code>input</code> where the input |
|
656 |
* starts |
|
657 |
* @param inputLen the input length |
|
658 |
* |
|
659 |
* @return the new buffer with the result |
|
660 |
* |
|
661 |
* @exception IllegalBlockSizeException if this cipher is a block cipher, |
|
662 |
* no padding has been requested (only in encryption mode), and the total |
|
663 |
* input length of the data processed by this cipher is not a multiple of |
|
664 |
* block size |
|
665 |
* @exception BadPaddingException if this cipher is in decryption mode, |
|
666 |
* and (un)padding has been requested, but the decrypted data is not |
|
667 |
* bounded by the appropriate padding bytes |
|
668 |
*/ |
|
669 |
byte[] doFinal(byte[] input, int inputOffset, int inputLen) |
|
670 |
throws IllegalBlockSizeException, BadPaddingException { |
|
671 |
byte[] output = null; |
|
672 |
byte[] out = null; |
|
673 |
try { |
|
674 |
output = new byte[getOutputSize(inputLen)]; |
|
675 |
int len = doFinal(input, inputOffset, inputLen, output, 0); |
|
676 |
if (len < output.length) { |
|
677 |
out = new byte[len]; |
|
678 |
if (len != 0) |
|
679 |
System.arraycopy(output, 0, out, 0, len); |
|
680 |
} else { |
|
681 |
out = output; |
|
682 |
} |
|
683 |
} catch (ShortBufferException e) { |
|
684 |
// never thrown |
|
685 |
} |
|
686 |
return out; |
|
687 |
} |
|
688 |
||
689 |
/** |
|
690 |
* Encrypts or decrypts data in a single-part operation, |
|
691 |
* or finishes a multiple-part operation. |
|
692 |
* The data is encrypted or decrypted, depending on how this cipher was |
|
693 |
* initialized. |
|
694 |
* |
|
695 |
* <p>The first <code>inputLen</code> bytes in the <code>input</code> |
|
696 |
* buffer, starting at <code>inputOffset</code>, and any input bytes that |
|
697 |
* may have been buffered during a previous <code>update</code> operation, |
|
698 |
* are processed, with padding (if requested) being applied. |
|
699 |
* The result is stored in the <code>output</code> buffer, starting at |
|
700 |
* <code>outputOffset</code>. |
|
701 |
* |
|
702 |
* <p>The cipher is reset to its initial state (uninitialized) after this |
|
703 |
* call. |
|
704 |
* |
|
705 |
* @param input the input buffer |
|
706 |
* @param inputOffset the offset in <code>input</code> where the input |
|
707 |
* starts |
|
708 |
* @param inputLen the input length |
|
709 |
* @param output the buffer for the result |
|
710 |
* @param outputOffset the offset in <code>output</code> where the result |
|
711 |
* is stored |
|
712 |
* |
|
713 |
* @return the number of bytes stored in <code>output</code> |
|
714 |
* |
|
715 |
* @exception IllegalBlockSizeException if this cipher is a block cipher, |
|
716 |
* no padding has been requested (only in encryption mode), and the total |
|
717 |
* input length of the data processed by this cipher is not a multiple of |
|
718 |
* block size |
|
719 |
* @exception ShortBufferException if the given output buffer is too small |
|
720 |
* to hold the result |
|
721 |
* @exception BadPaddingException if this cipher is in decryption mode, |
|
722 |
* and (un)padding has been requested, but the decrypted data is not |
|
723 |
* bounded by the appropriate padding bytes |
|
724 |
*/ |
|
725 |
int doFinal(byte[] input, int inputOffset, int inputLen, byte[] output, |
|
726 |
int outputOffset) |
|
727 |
throws IllegalBlockSizeException, ShortBufferException, |
|
728 |
BadPaddingException { |
|
729 |
||
730 |
// calculate the total input length |
|
731 |
int totalLen = buffered + inputLen; |
|
732 |
int paddedLen = totalLen; |
|
733 |
int paddingLen = 0; |
|
734 |
||
735 |
// will the total input length be a multiple of blockSize? |
|
736 |
if (unitBytes != blockSize) { |
|
737 |
if (totalLen < diffBlocksize) { |
|
738 |
paddingLen = diffBlocksize - totalLen; |
|
739 |
} else { |
|
740 |
paddingLen = blockSize - |
|
741 |
((totalLen - diffBlocksize) % blockSize); |
|
742 |
} |
|
743 |
} else if (padding != null) { |
|
744 |
paddingLen = padding.padLength(totalLen); |
|
745 |
} |
|
746 |
||
747 |
if ((paddingLen > 0) && (paddingLen != blockSize) && |
|
748 |
(padding != null) && decrypting) { |
|
749 |
throw new IllegalBlockSizeException |
|
750 |
("Input length must be multiple of " + blockSize + |
|
751 |
" when decrypting with padded cipher"); |
|
752 |
} |
|
753 |
||
754 |
// if encrypting and padding not null, add padding |
|
755 |
if (!decrypting && padding != null) |
|
756 |
paddedLen += paddingLen; |
|
757 |
||
758 |
// check output buffer capacity. |
|
759 |
// if we are decrypting with padding applied, we can perform this |
|
760 |
// check only after we have determined how many padding bytes there |
|
761 |
// are. |
|
762 |
if (output == null) { |
|
763 |
throw new ShortBufferException("Output buffer is null"); |
|
764 |
} |
|
765 |
int outputCapacity = output.length - outputOffset; |
|
766 |
if (((!decrypting) || (padding == null)) && |
|
767 |
(outputCapacity < paddedLen) || |
|
768 |
(decrypting && (outputCapacity < (paddedLen - blockSize)))) { |
|
769 |
throw new ShortBufferException("Output buffer too short: " |
|
770 |
+ outputCapacity + " bytes given, " |
|
771 |
+ paddedLen + " bytes needed"); |
|
772 |
} |
|
773 |
||
774 |
// prepare the final input avoiding copying if possible |
|
775 |
byte[] finalBuf = input; |
|
776 |
int finalOffset = inputOffset; |
|
777 |
if ((buffered != 0) || (!decrypting && padding != null)) { |
|
778 |
finalOffset = 0; |
|
779 |
finalBuf = new byte[paddedLen]; |
|
780 |
if (buffered != 0) { |
|
781 |
System.arraycopy(buffer, 0, finalBuf, 0, buffered); |
|
782 |
} |
|
783 |
if (inputLen != 0) { |
|
784 |
System.arraycopy(input, inputOffset, finalBuf, |
|
785 |
buffered, inputLen); |
|
786 |
} |
|
787 |
if (!decrypting && padding != null) { |
|
788 |
padding.padWithLen(finalBuf, totalLen, paddingLen); |
|
789 |
} |
|
790 |
} |
|
791 |
||
792 |
if (decrypting) { |
|
793 |
// if the size of specified output buffer is less than |
|
794 |
// the length of the cipher text, then the current |
|
795 |
// content of cipher has to be preserved in order for |
|
796 |
// users to retry the call with a larger buffer in the |
|
797 |
// case of ShortBufferException. |
|
798 |
if (outputCapacity < paddedLen) { |
|
799 |
cipher.save(); |
|
800 |
} |
|
801 |
// create temporary output buffer so that only "real" |
|
802 |
// data bytes are passed to user's output buffer. |
|
803 |
byte[] outWithPadding = new byte[totalLen]; |
|
804 |
totalLen = finalNoPadding(finalBuf, finalOffset, outWithPadding, |
|
805 |
0, totalLen); |
|
806 |
||
807 |
if (padding != null) { |
|
808 |
int padStart = padding.unpad(outWithPadding, 0, totalLen); |
|
809 |
if (padStart < 0) { |
|
810 |
throw new BadPaddingException("Given final block not " |
|
811 |
+ "properly padded"); |
|
812 |
} |
|
813 |
totalLen = padStart; |
|
814 |
} |
|
815 |
if ((output.length - outputOffset) < totalLen) { |
|
816 |
// restore so users can retry with a larger buffer |
|
817 |
cipher.restore(); |
|
818 |
throw new ShortBufferException("Output buffer too short: " |
|
819 |
+ (output.length-outputOffset) |
|
820 |
+ " bytes given, " + totalLen |
|
821 |
+ " bytes needed"); |
|
822 |
} |
|
823 |
for (int i = 0; i < totalLen; i++) { |
|
824 |
output[outputOffset + i] = outWithPadding[i]; |
|
825 |
} |
|
826 |
} else { // encrypting |
|
827 |
totalLen = finalNoPadding(finalBuf, finalOffset, output, |
|
828 |
outputOffset, paddedLen); |
|
829 |
} |
|
830 |
||
831 |
buffered = 0; |
|
832 |
diffBlocksize = blockSize; |
|
833 |
if (cipherMode != ECB_MODE) { |
|
10336
0bb1999251f8
7064075: Security libraries don't build with javac -Xlint:all,-deprecation -Werror
jjg
parents:
5506
diff
changeset
|
834 |
cipher.reset(); |
2 | 835 |
} |
836 |
return totalLen; |
|
837 |
} |
|
838 |
||
839 |
private int finalNoPadding(byte[] in, int inOff, byte[] out, int outOff, |
|
840 |
int len) |
|
841 |
throws IllegalBlockSizeException |
|
842 |
{ |
|
843 |
if (in == null || len == 0) |
|
844 |
return 0; |
|
845 |
||
846 |
if ((cipherMode != CFB_MODE) && (cipherMode != OFB_MODE) |
|
847 |
&& ((len % unitBytes) != 0) && (cipherMode != CTS_MODE)) { |
|
848 |
if (padding != null) { |
|
849 |
throw new IllegalBlockSizeException |
|
850 |
("Input length (with padding) not multiple of " + |
|
851 |
unitBytes + " bytes"); |
|
852 |
} else { |
|
853 |
throw new IllegalBlockSizeException |
|
854 |
("Input length not multiple of " + unitBytes |
|
855 |
+ " bytes"); |
|
856 |
} |
|
857 |
} |
|
858 |
||
859 |
if (decrypting) { |
|
860 |
cipher.decryptFinal(in, inOff, len, out, outOff); |
|
861 |
} else { |
|
862 |
cipher.encryptFinal(in, inOff, len, out, outOff); |
|
863 |
} |
|
864 |
||
865 |
return len; |
|
866 |
} |
|
867 |
||
868 |
// Note: Wrap() and Unwrap() are the same in |
|
869 |
// each of SunJCE CipherSpi implementation classes. |
|
870 |
// They are duplicated due to export control requirements: |
|
871 |
// All CipherSpi implementation must be final. |
|
872 |
/** |
|
873 |
* Wrap a key. |
|
874 |
* |
|
875 |
* @param key the key to be wrapped. |
|
876 |
* |
|
877 |
* @return the wrapped key. |
|
878 |
* |
|
879 |
* @exception IllegalBlockSizeException if this cipher is a block |
|
880 |
* cipher, no padding has been requested, and the length of the |
|
881 |
* encoding of the key to be wrapped is not a |
|
882 |
* multiple of the block size. |
|
883 |
* |
|
884 |
* @exception InvalidKeyException if it is impossible or unsafe to |
|
885 |
* wrap the key with this cipher (e.g., a hardware protected key is |
|
886 |
* being passed to a software only cipher). |
|
887 |
*/ |
|
888 |
byte[] wrap(Key key) |
|
889 |
throws IllegalBlockSizeException, InvalidKeyException { |
|
890 |
byte[] result = null; |
|
891 |
||
892 |
try { |
|
893 |
byte[] encodedKey = key.getEncoded(); |
|
894 |
if ((encodedKey == null) || (encodedKey.length == 0)) { |
|
895 |
throw new InvalidKeyException("Cannot get an encoding of " + |
|
896 |
"the key to be wrapped"); |
|
897 |
} |
|
898 |
result = doFinal(encodedKey, 0, encodedKey.length); |
|
899 |
} catch (BadPaddingException e) { |
|
900 |
// Should never happen |
|
901 |
} |
|
902 |
return result; |
|
903 |
} |
|
904 |
||
905 |
/** |
|
906 |
* Unwrap a previously wrapped key. |
|
907 |
* |
|
908 |
* @param wrappedKey the key to be unwrapped. |
|
909 |
* |
|
910 |
* @param wrappedKeyAlgorithm the algorithm the wrapped key is for. |
|
911 |
* |
|
912 |
* @param wrappedKeyType the type of the wrapped key. |
|
913 |
* This is one of <code>Cipher.SECRET_KEY</code>, |
|
914 |
* <code>Cipher.PRIVATE_KEY</code>, or <code>Cipher.PUBLIC_KEY</code>. |
|
915 |
* |
|
916 |
* @return the unwrapped key. |
|
917 |
* |
|
918 |
* @exception NoSuchAlgorithmException if no installed providers |
|
919 |
* can create keys of type <code>wrappedKeyType</code> for the |
|
920 |
* <code>wrappedKeyAlgorithm</code>. |
|
921 |
* |
|
922 |
* @exception InvalidKeyException if <code>wrappedKey</code> does not |
|
923 |
* represent a wrapped key of type <code>wrappedKeyType</code> for |
|
924 |
* the <code>wrappedKeyAlgorithm</code>. |
|
925 |
*/ |
|
926 |
Key unwrap(byte[] wrappedKey, String wrappedKeyAlgorithm, |
|
927 |
int wrappedKeyType) |
|
928 |
throws InvalidKeyException, NoSuchAlgorithmException { |
|
929 |
byte[] encodedKey; |
|
930 |
try { |
|
931 |
encodedKey = doFinal(wrappedKey, 0, wrappedKey.length); |
|
932 |
} catch (BadPaddingException ePadding) { |
|
933 |
throw new InvalidKeyException("The wrapped key is not padded " + |
|
934 |
"correctly"); |
|
935 |
} catch (IllegalBlockSizeException eBlockSize) { |
|
936 |
throw new InvalidKeyException("The wrapped key does not have " + |
|
937 |
"the correct length"); |
|
938 |
} |
|
939 |
return ConstructKeys.constructKey(encodedKey, wrappedKeyAlgorithm, |
|
940 |
wrappedKeyType); |
|
941 |
} |
|
942 |
} |