1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This code is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License version 2 only, as
8  * published by the Free Software Foundation.  Oracle designates this
9  * particular file as subject to the "Classpath" exception as provided
10  * by Oracle in the LICENSE file that accompanied this code.
11  *
12  * This code is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15  * version 2 for more details (a copy is included in the LICENSE file that
16  * accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License version
19  * 2 along with this work; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21  *
22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23  * or visit www.oracle.com if you need additional information or have any
24  * questions.
25  */
26 
27 package javax.crypto;
28 
29 import java.util.*;
30 import java.util.concurrent.ConcurrentHashMap;
31 import java.util.concurrent.ConcurrentMap;
32 import java.util.regex.*;
33 
34 import static java.util.Locale.ENGLISH;
35 
36 import java.security.*;
37 import java.security.Provider.Service;
38 import java.security.spec.AlgorithmParameterSpec;
39 import java.security.spec.InvalidParameterSpecException;
40 import java.security.cert.Certificate;
41 import java.security.cert.X509Certificate;
42 
43 import javax.crypto.spec.*;
44 
45 import java.nio.ByteBuffer;
46 import java.nio.ReadOnlyBufferException;
47 
48 import sun.security.util.Debug;
49 import sun.security.jca.*;
50 import sun.security.jca.GetInstance.Instance;
51 
52 /**
53  * This class provides the functionality of a cryptographic cipher for
54  * encryption and decryption. It forms the core of the Java Cryptographic
55  * Extension (JCE) framework.
56  *
57  * <p>In order to create a Cipher object, the application calls the
58  * Cipher's <code>getInstance</code> method, and passes the name of the
59  * requested <i>transformation</i> to it. Optionally, the name of a provider
60  * may be specified.
61  *
62  * <p>A <i>transformation</i> is a string that describes the operation (or
63  * set of operations) to be performed on the given input, to produce some
64  * output. A transformation always includes the name of a cryptographic
65  * algorithm (e.g., <i>DES</i>), and may be followed by a feedback mode and
66  * padding scheme.
67  *
68  * <p> A transformation is of the form:<p>
69  *
70  * <ul>
71  * <li>"<i>algorithm/mode/padding</i>" or
72  * <p>
73  * <li>"<i>algorithm</i>"
74  * </ul>
75  *
76  * <P> (in the latter case,
77  * provider-specific default values for the mode and padding scheme are used).
78  * For example, the following is a valid transformation:<p>
79  *
80  * <pre>
81  *     Cipher c = Cipher.getInstance("<i>DES/CBC/PKCS5Padding</i>");
82  * </pre>
83  *
84  * Using modes such as <code>CFB</code> and <code>OFB</code>, block
85  * ciphers can encrypt data in units smaller than the cipher's actual
86  * block size.  When requesting such a mode, you may optionally specify
87  * the number of bits to be processed at a time by appending this number
88  * to the mode name as shown in the "<code>DES/CFB8/NoPadding</code>" and
89  * "<code>DES/OFB32/PKCS5Padding</code>" transformations. If no such
90  * number is specified, a provider-specific default is used. (For
91  * example, the SunJCE provider uses a default of 64 bits for DES.)
92  * Thus, block ciphers can be turned into byte-oriented stream ciphers by
93  * using an 8 bit mode such as CFB8 or OFB8.
94  * <p>
95  * Modes such as Authenticated Encryption with Associated Data (AEAD)
96  * provide authenticity assurances for both confidential data and
97  * Additional Associated Data (AAD) that is not encrypted.  (Please see
98  * <a href="http://www.ietf.org/rfc/rfc5116.txt"> RFC 5116 </a> for more
99  * information on AEAD and AEAD algorithms such as GCM/CCM.) Both
100  * confidential and AAD data can be used when calculating the
101  * authentication tag (similar to a {@link Mac}).  This tag is appended
102  * to the ciphertext during encryption, and is verified on decryption.
103  * <p>
104  * AEAD modes such as GCM/CCM perform all AAD authenticity calculations
105  * before starting the ciphertext authenticity calculations.  To avoid
106  * implementations having to internally buffer ciphertext, all AAD data
107  * must be supplied to GCM/CCM implementations (via the {@code
108  * updateAAD} methods) <b>before</b> the ciphertext is processed (via
109  * the {@code update} and {@code doFinal} methods).
110  *
111  * <pre>
112  *     GCMParameterSpec s = new GCMParameterSpec(...);
113  *     cipher.init(..., s);
114  *
115  *     // If the GCMParameterSpec is needed again
116  *     cipher.getParameters().getParameterSpec(GCMParameterSpec.class));
117  *
118  *     cipher.updateAAD(...);  // AAD
119  *     cipher.update(...);     // Multi-part update
120  *     cipher.doFinal(...);    // conclusion of operation
121  * </pre>
122  * <p> Android provides the following <code>Cipher</code> transformations:
123  * <table>
124  *     <thead>
125  *         <tr>
126  *             <th>Name</th>
127  *             <th>Supported (API Levels)</th>
128  *         </tr>
129  *     </thead>
130  *         <tr>
131  *             <td>AES/CBC/ISO10126Padding</td>
132  *             <td>1+</td>
133  *         </tr>
134  *         <tr>
135  *             <td>AES/CBC/NoPadding</td>
136  *             <td>1+</td>
137  *         </tr>
138  *         <tr>
139  *             <td>AES/CBC/PKCS5Padding</td>
140  *             <td>1+</td>
141  *         </tr>
142  *         <tr>
143  *             <td>AES/CFB/ISO10126Padding</td>
144  *             <td>1+</td>
145  *         </tr>
146  *         <tr>
147  *             <td>AES/CFB/NoPadding</td>
148  *             <td>1+</td>
149  *         </tr>
150  *         <tr>
151  *             <td>AES/CFB/PKCS5Padding</td>
152  *             <td>1+</td>
153  *         </tr>
154  *         <tr>
155  *             <td>AES/CTR/ISO10126Padding</td>
156  *             <td>1+</td>
157  *         </tr>
158  *         <tr>
159  *             <td>AES/CTR/NoPadding</td>
160  *             <td>1+</td>
161  *         </tr>
162  *         <tr>
163  *             <td>AES/CTR/PKCS5Padding</td>
164  *             <td>1+</td>
165  *         </tr>
166  *         <tr>
167  *             <td>AES/CTS/ISO10126Padding</td>
168  *             <td>1+</td>
169  *         </tr>
170  *         <tr>
171  *             <td>AES/CTS/NoPadding</td>
172  *             <td>1+</td>
173  *         </tr>
174  *         <tr>
175  *             <td>AES/CTS/PKCS5Padding</td>
176  *             <td>1+</td>
177  *         </tr>
178  *         <tr>
179  *             <td>AES/ECB/ISO10126Padding</td>
180  *             <td>1+</td>
181  *         </tr>
182  *         <tr>
183  *             <td>AES/ECB/NoPadding</td>
184  *             <td>1+</td>
185  *         </tr>
186  *         <tr>
187  *             <td>AES/ECB/PKCS5Padding</td>
188  *             <td>1+</td>
189  *         </tr>
190  *         <tr>
191  *             <td>AES/OFB/ISO10126Padding</td>
192  *             <td>1+</td>
193  *         </tr>
194  *         <tr>
195  *             <td>AES/OFB/NoPadding</td>
196  *             <td>1+</td>
197  *         </tr>
198  *         <tr>
199  *             <td>AES/OFB/PKCS5Padding</td>
200  *             <td>1+</td>
201  *         </tr>
202  *         <tr>
203  *             <td>ARCFOUR/ECB/NoPadding</td>
204  *             <td>10+</td>
205  *         </tr>
206  *         <tr>
207  *             <td>BLOWFISH/CBC/ISO10126Padding</td>
208  *             <td>10+</td>
209  *         </tr>
210  *         <tr>
211  *             <td>BLOWFISH/CBC/NoPadding</td>
212  *             <td>10+</td>
213  *         </tr>
214  *         <tr>
215  *             <td>BLOWFISH/CBC/PKCS5Padding</td>
216  *             <td>10+</td>
217  *         </tr>
218  *         <tr>
219  *             <td>BLOWFISH/CFB/ISO10126Padding</td>
220  *             <td>10+</td>
221  *         </tr>
222  *         <tr>
223  *             <td>BLOWFISH/CFB/NoPadding</td>
224  *             <td>10+</td>
225  *         </tr>
226  *         <tr>
227  *             <td>BLOWFISH/CFB/PKCS5Padding</td>
228  *             <td>10+</td>
229  *         </tr>
230  *         <tr>
231  *             <td>BLOWFISH/CTR/ISO10126Padding</td>
232  *             <td>10+</td>
233  *         </tr>
234  *         <tr>
235  *             <td>BLOWFISH/CTR/NoPadding</td>
236  *             <td>10+</td>
237  *         </tr>
238  *         <tr>
239  *             <td>BLOWFISH/CTR/PKCS5Padding</td>
240  *             <td>10+</td>
241  *         </tr>
242  *         <tr>
243  *             <td>BLOWFISH/CTS/ISO10126Padding</td>
244  *             <td>10+</td>
245  *         </tr>
246  *         <tr>
247  *             <td>BLOWFISH/CTS/NoPadding</td>
248  *             <td>10+</td>
249  *         </tr>
250  *         <tr>
251  *             <td>BLOWFISH/CTS/PKCS5Padding</td>
252  *             <td>10+</td>
253  *         </tr>
254  *         <tr>
255  *             <td>BLOWFISH/ECB/ISO10126Padding</td>
256  *             <td>10+</td>
257  *         </tr>
258  *         <tr>
259  *             <td>BLOWFISH/ECB/NoPadding</td>
260  *             <td>10+</td>
261  *         </tr>
262  *         <tr>
263  *             <td>BLOWFISH/ECB/PKCS5Padding</td>
264  *             <td>10+</td>
265  *         </tr>
266  *         <tr>
267  *             <td>BLOWFISH/OFB/ISO10126Padding</td>
268  *             <td>10+</td>
269  *         </tr>
270  *         <tr>
271  *             <td>BLOWFISH/OFB/NoPadding</td>
272  *             <td>10+</td>
273  *         </tr>
274  *         <tr>
275  *             <td>BLOWFISH/OFB/PKCS5Padding</td>
276  *             <td>10+</td>
277  *         </tr>
278  *         <tr>
279  *             <td>DES/CBC/ISO10126Padding</td>
280  *             <td>1+</td>
281  *         </tr>
282  *         <tr>
283  *             <td>DES/CBC/NoPadding</td>
284  *             <td>1+</td>
285  *         </tr>
286  *         <tr>
287  *             <td>DES/CBC/PKCS5Padding</td>
288  *             <td>1+</td>
289  *         </tr>
290  *         <tr>
291  *             <td>DES/CFB/ISO10126Padding</td>
292  *             <td>1+</td>
293  *         </tr>
294  *         <tr>
295  *             <td>DES/CFB/NoPadding</td>
296  *             <td>1+</td>
297  *         </tr>
298  *         <tr>
299  *             <td>DES/CFB/PKCS5Padding</td>
300  *             <td>1+</td>
301  *         </tr>
302  *         <tr>
303  *             <td>DES/CTR/ISO10126Padding</td>
304  *             <td>1+</td>
305  *         </tr>
306  *         <tr>
307  *             <td>DES/CTR/NoPadding</td>
308  *             <td>1+</td>
309  *         </tr>
310  *         <tr>
311  *             <td>DES/CTR/PKCS5Padding</td>
312  *             <td>1+</td>
313  *         </tr>
314  *         <tr>
315  *             <td>DES/CTS/ISO10126Padding</td>
316  *             <td>1+</td>
317  *         </tr>
318  *         <tr>
319  *             <td>DES/CTS/NoPadding</td>
320  *             <td>1+</td>
321  *         </tr>
322  *         <tr>
323  *             <td>DES/CTS/PKCS5Padding</td>
324  *             <td>1+</td>
325  *         </tr>
326  *         <tr>
327  *             <td>DES/ECB/ISO10126Padding</td>
328  *             <td>1+</td>
329  *         </tr>
330  *         <tr>
331  *             <td>DES/ECB/NoPadding</td>
332  *             <td>1+</td>
333  *         </tr>
334  *         <tr>
335  *             <td>DES/ECB/PKCS5Padding</td>
336  *             <td>1+</td>
337  *         </tr>
338  *         <tr>
339  *             <td>DES/OFB/ISO10126Padding</td>
340  *             <td>1+</td>
341  *         </tr>
342  *         <tr>
343  *             <td>DES/OFB/NoPadding</td>
344  *             <td>1+</td>
345  *         </tr>
346  *         <tr>
347  *             <td>DES/OFB/PKCS5Padding</td>
348  *             <td>1+</td>
349  *         </tr>
350  *         <tr>
351  *             <td>DESede/CBC/ISO10126Padding</td>
352  *             <td>1+</td>
353  *         </tr>
354  *         <tr>
355  *             <td>DESede/CBC/NoPadding</td>
356  *             <td>1+</td>
357  *         </tr>
358  *         <tr>
359  *             <td>DESede/CBC/PKCS5Padding</td>
360  *             <td>1+</td>
361  *         </tr>
362  *         <tr>
363  *             <td>DESede/CFB/ISO10126Padding</td>
364  *             <td>1+</td>
365  *         </tr>
366  *         <tr>
367  *             <td>DESede/CFB/NoPadding</td>
368  *             <td>1+</td>
369  *         </tr>
370  *         <tr>
371  *             <td>DESede/CFB/PKCS5Padding</td>
372  *             <td>1+</td>
373  *         </tr>
374  *         <tr>
375  *             <td>DESede/CTR/ISO10126Padding</td>
376  *             <td>1+</td>
377  *         </tr>
378  *         <tr>
379  *             <td>DESede/CTR/NoPadding</td>
380  *             <td>1+</td>
381  *         </tr>
382  *         <tr>
383  *             <td>DESede/CTR/PKCS5Padding</td>
384  *             <td>1+</td>
385  *         </tr>
386  *         <tr>
387  *             <td>DESede/CTS/ISO10126Padding</td>
388  *             <td>1+</td>
389  *         </tr>
390  *         <tr>
391  *             <td>DESede/CTS/NoPadding</td>
392  *             <td>1+</td>
393  *         </tr>
394  *         <tr>
395  *             <td>DESede/CTS/PKCS5Padding</td>
396  *             <td>1+</td>
397  *         </tr>
398  *         <tr>
399  *             <td>DESede/ECB/ISO10126Padding</td>
400  *             <td>1+</td>
401  *         </tr>
402  *         <tr>
403  *             <td>DESede/ECB/NoPadding</td>
404  *             <td>1+</td>
405  *         </tr>
406  *         <tr>
407  *             <td>DESede/ECB/PKCS5Padding</td>
408  *             <td>1+</td>
409  *         </tr>
410  *         <tr>
411  *             <td>DESede/OFB/ISO10126Padding</td>
412  *             <td>1+</td>
413  *         </tr>
414  *         <tr>
415  *             <td>DESede/OFB/NoPadding</td>
416  *             <td>1+</td>
417  *         </tr>
418  *         <tr>
419  *             <td>DESede/OFB/PKCS5Padding</td>
420  *             <td>1+</td>
421  *         </tr>
422  *         <tr>
423  *             <td>PBEwithMD5andDES/CBC/ISO10126Padding</td>
424  *             <td>1+</td>
425  *         </tr>
426  *         <tr>
427  *             <td>PBEwithMD5andDES/CBC/NoPadding</td>
428  *             <td>1+</td>
429  *         </tr>
430  *         <tr>
431  *             <td>PBEwithMD5andDES/CBC/PKCS5Padding</td>
432  *             <td>1+</td>
433  *         </tr>
434  *         <tr>
435  *             <td>PBEwithMD5andDES/CFB/ISO10126Padding</td>
436  *             <td>1+</td>
437  *         </tr>
438  *         <tr>
439  *             <td>PBEwithMD5andDES/CFB/NoPadding</td>
440  *             <td>1+</td>
441  *         </tr>
442  *         <tr>
443  *             <td>PBEwithMD5andDES/CFB/PKCS5Padding</td>
444  *             <td>1+</td>
445  *         </tr>
446  *         <tr>
447  *             <td>PBEwithMD5andDES/CTR/ISO10126Padding</td>
448  *             <td>1+</td>
449  *         </tr>
450  *         <tr>
451  *             <td>PBEwithMD5andDES/CTR/NoPadding</td>
452  *             <td>1+</td>
453  *         </tr>
454  *         <tr>
455  *             <td>PBEwithMD5andDES/CTR/PKCS5Padding</td>
456  *             <td>1+</td>
457  *         </tr>
458  *         <tr>
459  *             <td>PBEwithMD5andDES/CTS/ISO10126Padding</td>
460  *             <td>1+</td>
461  *         </tr>
462  *         <tr>
463  *             <td>PBEwithMD5andDES/CTS/NoPadding</td>
464  *             <td>1+</td>
465  *         </tr>
466  *         <tr>
467  *             <td>PBEwithMD5andDES/CTS/PKCS5Padding</td>
468  *             <td>1+</td>
469  *         </tr>
470  *         <tr>
471  *             <td>PBEwithMD5andDES/ECB/ISO10126Padding</td>
472  *             <td>1+</td>
473  *         </tr>
474  *         <tr>
475  *             <td>PBEwithMD5andDES/ECB/NoPadding</td>
476  *             <td>1+</td>
477  *         </tr>
478  *         <tr>
479  *             <td>PBEwithMD5andDES/ECB/PKCS5Padding</td>
480  *             <td>1+</td>
481  *         </tr>
482  *         <tr>
483  *             <td>PBEwithMD5andDES/OFB/ISO10126Padding</td>
484  *             <td>1+</td>
485  *         </tr>
486  *         <tr>
487  *             <td>PBEwithMD5andDES/OFB/NoPadding</td>
488  *             <td>1+</td>
489  *         </tr>
490  *         <tr>
491  *             <td>PBEwithMD5andDES/OFB/PKCS5Padding</td>
492  *             <td>1+</td>
493  *         </tr>
494  *         <tr>
495  *             <td>PBEwithSHA1andDESede/CBC/ISO10126Padding</td>
496  *             <td>1+</td>
497  *         </tr>
498  *         <tr>
499  *             <td>PBEwithSHA1andDESede/CBC/NoPadding</td>
500  *             <td>1+</td>
501  *         </tr>
502  *         <tr>
503  *             <td>PBEwithSHA1andDESede/CBC/PKCS5Padding</td>
504  *             <td>1+</td>
505  *         </tr>
506  *         <tr>
507  *             <td>PBEwithSHA1andDESede/CFB/ISO10126Padding</td>
508  *             <td>1+</td>
509  *         </tr>
510  *         <tr>
511  *             <td>PBEwithSHA1andDESede/CFB/NoPadding</td>
512  *             <td>1+</td>
513  *         </tr>
514  *         <tr>
515  *             <td>PBEwithSHA1andDESede/CFB/PKCS5Padding</td>
516  *             <td>1+</td>
517  *         </tr>
518  *         <tr>
519  *             <td>PBEwithSHA1andDESede/CTR/ISO10126Padding</td>
520  *             <td>1+</td>
521  *         </tr>
522  *         <tr>
523  *             <td>PBEwithSHA1andDESede/CTR/NoPadding</td>
524  *             <td>1+</td>
525  *         </tr>
526  *         <tr>
527  *             <td>PBEwithSHA1andDESede/CTR/PKCS5Padding</td>
528  *             <td>1+</td>
529  *         </tr>
530  *         <tr>
531  *             <td>PBEwithSHA1andDESede/CTS/ISO10126Padding</td>
532  *             <td>1+</td>
533  *         </tr>
534  *         <tr>
535  *             <td>PBEwithSHA1andDESede/CTS/NoPadding</td>
536  *             <td>1+</td>
537  *         </tr>
538  *         <tr>
539  *             <td>PBEwithSHA1andDESede/CTS/PKCS5Padding</td>
540  *             <td>1+</td>
541  *         </tr>
542  *         <tr>
543  *             <td>PBEwithSHA1andDESede/ECB/ISO10126Padding</td>
544  *             <td>1+</td>
545  *         </tr>
546  *         <tr>
547  *             <td>PBEwithSHA1andDESede/ECB/NoPadding</td>
548  *             <td>1+</td>
549  *         </tr>
550  *         <tr>
551  *             <td>PBEwithSHA1andDESede/ECB/PKCS5Padding</td>
552  *             <td>1+</td>
553  *         </tr>
554  *         <tr>
555  *             <td>PBEwithSHA1andDESede/OFB/ISO10126Padding</td>
556  *             <td>1+</td>
557  *         </tr>
558  *         <tr>
559  *             <td>PBEwithSHA1andDESede/OFB/NoPadding</td>
560  *             <td>1+</td>
561  *         </tr>
562  *         <tr>
563  *             <td>PBEwithSHA1andDESede/OFB/PKCS5Padding</td>
564  *             <td>1+</td>
565  *         </tr>
566  *         <tr>
567  *             <td>RC4/ECB/NoPadding</td>
568  *             <td>10+</td>
569  *         </tr>
570  *         <tr>
571  *             <td>RSA/ECB/NoPadding</td>
572  *             <td>1+</td>
573  *         </tr>
574  *         <tr>
575  *             <td>RSA/ECB/OAEPPadding</td>
576  *             <td>1+</td>
577  *         </tr>
578  *         <tr>
579  *             <td>RSA/ECB/OAEPwithSHA-1andMGF1Padding</td>
580  *             <td>10+</td>
581  *         </tr>
582  *         <tr>
583  *             <td>RSA/ECB/OAEPwithSHA-256andMGF1Padding</td>
584  *             <td>10+</td>
585  *         </tr>
586  *         <tr>
587  *             <td>RSA/ECB/PKCS1Padding</td>
588  *             <td>1+</td>
589  *         </tr>
590  *         <tr>
591  *             <td>RSA/NONE/NoPadding</td>
592  *             <td>1+</td>
593  *         </tr>
594  *         <tr>
595  *             <td>RSA/NONE/OAEPPadding</td>
596  *             <td>1+</td>
597  *         </tr>
598  *         <tr>
599  *             <td>RSA/NONE/OAEPwithSHA-1andMGF1Padding</td>
600  *             <td>10+</td>
601  *         </tr>
602  *         <tr>
603  *             <td>RSA/NONE/OAEPwithSHA-256andMGF1Padding</td>
604  *             <td>10+</td>
605  *         </tr>
606  *         <tr>
607  *             <td>RSA/NONE/PKCS1Padding</td>
608  *             <td>1+</td>
609  *         </tr>
610  *     </tbody>
611  *     </tbody>
612  * </table>
613  *
614  * These transformations are described in the
615  * <a href="{@docRoot}openjdk-redirect.html?v=8&path=/technotes/guides/security/StandardNames.html#Cipher">
616  * Cipher section</a> of the
617  * Java Cryptography Architecture Standard Algorithm Name Documentation.
618  *
619  * @author Jan Luehe
620  * @see KeyGenerator
621  * @see SecretKey
622  * @since 1.4
623  */
624 
625 public class Cipher {
626 
627     private static final Debug debug =
628                         Debug.getInstance("jca", "Cipher");
629 
630     /**
631      * Constant used to initialize cipher to encryption mode.
632      */
633     public static final int ENCRYPT_MODE = 1;
634 
635     /**
636      * Constant used to initialize cipher to decryption mode.
637      */
638     public static final int DECRYPT_MODE = 2;
639 
640     /**
641      * Constant used to initialize cipher to key-wrapping mode.
642      */
643     public static final int WRAP_MODE = 3;
644 
645     /**
646      * Constant used to initialize cipher to key-unwrapping mode.
647      */
648     public static final int UNWRAP_MODE = 4;
649 
650     /**
651      * Constant used to indicate the to-be-unwrapped key is a "public key".
652      */
653     public static final int PUBLIC_KEY = 1;
654 
655     /**
656      * Constant used to indicate the to-be-unwrapped key is a "private key".
657      */
658     public static final int PRIVATE_KEY = 2;
659 
660     /**
661      * Constant used to indicate the to-be-unwrapped key is a "secret key".
662      */
663     public static final int SECRET_KEY = 3;
664 
665     // The provider
666     private Provider provider;
667 
668     // The provider implementation (delegate)
669     private CipherSpi spi;
670 
671     // The transformation
672     final private String transformation;
673 
674     // The tokenized version of transformation
675     final private String[] tokenizedTransformation;
676 
677     // The exemption mechanism that needs to be enforced
678     private ExemptionMechanism exmech;
679 
680     // Flag which indicates whether or not this cipher has been initialized
681     private boolean initialized = false;
682 
683     // The operation mode - store the operation mode after the
684     // cipher has been initialized.
685     private int opmode = 0;
686 
687     // The OID for the KeyUsage extension in an X.509 v3 certificate
688     private static final String KEY_USAGE_EXTENSION_OID = "2.5.29.15";
689 
690     private final SpiAndProviderUpdater spiAndProviderUpdater;
691 
692 
693     /**
694      * Creates a Cipher object.
695      *
696      * @param cipherSpi the delegate
697      * @param provider the provider
698      * @param transformation the transformation
699      */
Cipher(CipherSpi cipherSpi, Provider provider, String transformation)700     protected Cipher(CipherSpi cipherSpi,
701                      Provider provider,
702                      String transformation) {
703         if (cipherSpi == null) {
704             throw new NullPointerException("cipherSpi == null");
705         }
706         if (!(cipherSpi instanceof NullCipherSpi) && provider == null) {
707             throw new NullPointerException("provider == null");
708         }
709 
710         this.spi = cipherSpi;
711         this.provider = provider;
712         this.transformation = transformation;
713         this.tokenizedTransformation = null;
714 
715         this.spiAndProviderUpdater =
716             new SpiAndProviderUpdater(provider, cipherSpi);
717     }
718 
Cipher(CipherSpi cipherSpi, Provider provider, String transformation, String[] tokenizedTransformation)719     private Cipher(CipherSpi cipherSpi,
720                    Provider provider,
721                    String transformation,
722                    String[] tokenizedTransformation) {
723         this.spi = cipherSpi;
724         this.provider = provider;
725         this.transformation = transformation;
726         this.tokenizedTransformation = tokenizedTransformation;
727 
728         this.spiAndProviderUpdater =
729             new SpiAndProviderUpdater(provider, cipherSpi);
730     }
731 
tokenizeTransformation(String transformation)732     private static String[] tokenizeTransformation(String transformation)
733             throws NoSuchAlgorithmException {
734         if (transformation == null || transformation.isEmpty()) {
735             throw new NoSuchAlgorithmException("No transformation given");
736         }
737         /*
738          * array containing the components of a Cipher transformation:
739          *
740          * index 0: algorithm component (e.g., DES)
741          * index 1: feedback component (e.g., CFB)
742          * index 2: padding component (e.g., PKCS5Padding)
743          */
744         String[] parts = new String[3];
745         int count = 0;
746         StringTokenizer parser = new StringTokenizer(transformation, "/");
747         try {
748             while (parser.hasMoreTokens() && count < 3) {
749                 parts[count++] = parser.nextToken().trim();
750             }
751             if (count == 0 || count == 2 || parser.hasMoreTokens()) {
752                 throw new NoSuchAlgorithmException("Invalid transformation"
753                                                + " format:" +
754                                                transformation);
755             }
756         } catch (NoSuchElementException e) {
757             throw new NoSuchAlgorithmException("Invalid transformation " +
758                                            "format:" + transformation);
759         }
760         if ((parts[0] == null) || (parts[0].length() == 0)) {
761             throw new NoSuchAlgorithmException("Invalid transformation:" +
762                                    "algorithm not specified-"
763                                    + transformation);
764         }
765         return parts;
766     }
767 
768     /**
769      * Returns a <code>Cipher</code> object that implements the specified
770      * transformation.
771      *
772      * <p> This method traverses the list of registered security Providers,
773      * starting with the most preferred Provider.
774      * A new Cipher object encapsulating the
775      * CipherSpi implementation from the first
776      * Provider that supports the specified algorithm is returned.
777      *
778      * <p> Note that the list of registered providers may be retrieved via
779      * the {@link Security#getProviders() Security.getProviders()} method.
780      *
781      * @param transformation the name of the transformation, e.g.,
782      * <i>DES/CBC/PKCS5Padding</i>.
783      * See the Cipher section in the <a href=
784      *   "{@docRoot}openjdk-redirect.html?v=8&path=/technotes/guides/security/StandardNames.html#Cipher">
785      * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
786      * for information about standard transformation names.
787      *
788      * @return a cipher that implements the requested transformation.
789      *
790      * @exception NoSuchAlgorithmException if <code>transformation</code>
791      *          is null, empty, in an invalid format,
792      *          or if no Provider supports a CipherSpi implementation for the
793      *          specified algorithm.
794      *
795      * @exception NoSuchPaddingException if <code>transformation</code>
796      *          contains a padding scheme that is not available.
797      *
798      * @see java.security.Provider
799      */
getInstance(String transformation)800     public static final Cipher getInstance(String transformation)
801             throws NoSuchAlgorithmException, NoSuchPaddingException
802     {
803         return createCipher(transformation, null);
804     }
805 
806     /**
807      * Returns a <code>Cipher</code> object that implements the specified
808      * transformation.
809      *
810      * <p> A new Cipher object encapsulating the
811      * CipherSpi implementation from the specified provider
812      * is returned.  The specified provider must be registered
813      * in the security provider list.
814      *
815      * <p> Note that the list of registered providers may be retrieved via
816      * the {@link Security#getProviders() Security.getProviders()} method.
817      *
818      * @param transformation the name of the transformation,
819      * e.g., <i>DES/CBC/PKCS5Padding</i>.
820      * See the Cipher section in the <a href=
821      *   "{@docRoot}openjdk-redirect.html?v=8&path=/technotes/guides/security/StandardNames.html#Cipher">
822      * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
823      * for information about standard transformation names.
824      *
825      * @param provider the name of the provider.
826      *
827      * @return a cipher that implements the requested transformation.
828      *
829      * @exception NoSuchAlgorithmException if <code>transformation</code>
830      *          is null, empty, in an invalid format,
831      *          or if a CipherSpi implementation for the specified algorithm
832      *          is not available from the specified provider.
833      *
834      * @exception NoSuchProviderException if the specified provider is not
835      *          registered in the security provider list.
836      *
837      * @exception NoSuchPaddingException if <code>transformation</code>
838      *          contains a padding scheme that is not available.
839      *
840      * @exception IllegalArgumentException if the <code>provider</code>
841      *          is null or empty.
842      *
843      * @see java.security.Provider
844      */
getInstance(String transformation, String provider)845     public static final Cipher getInstance(String transformation,
846                                            String provider)
847             throws NoSuchAlgorithmException, NoSuchProviderException,
848             NoSuchPaddingException
849     {
850         if ((provider == null) || (provider.length() == 0)) {
851             throw new IllegalArgumentException("Missing provider");
852         }
853         Provider p = Security.getProvider(provider);
854         if (p == null) {
855             throw new NoSuchProviderException("No such provider: " +
856                                               provider);
857         }
858         return createCipher(transformation, p);
859     }
860 
861     /**
862      * Returns a <code>Cipher</code> object that implements the specified
863      * transformation.
864      *
865      * <p> A new Cipher object encapsulating the
866      * CipherSpi implementation from the specified Provider
867      * object is returned.  Note that the specified Provider object
868      * does not have to be registered in the provider list.
869      *
870      * @param transformation the name of the transformation,
871      * e.g., <i>DES/CBC/PKCS5Padding</i>.
872      * See the Cipher section in the <a href=
873      *   "{@docRoot}openjdk-redirect.html?v=8&path=/technotes/guides/security/StandardNames.html#Cipher">
874      * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
875      * for information about standard transformation names.
876      *
877      * @param provider the provider.
878      *
879      * @return a cipher that implements the requested transformation.
880      *
881      * @exception NoSuchAlgorithmException if <code>transformation</code>
882      *          is null, empty, in an invalid format,
883      *          or if a CipherSpi implementation for the specified algorithm
884      *          is not available from the specified Provider object.
885      *
886      * @exception NoSuchPaddingException if <code>transformation</code>
887      *          contains a padding scheme that is not available.
888      *
889      * @exception IllegalArgumentException if the <code>provider</code>
890      *          is null.
891      *
892      * @see java.security.Provider
893      */
getInstance(String transformation, Provider provider)894     public static final Cipher getInstance(String transformation,
895                                            Provider provider)
896             throws NoSuchAlgorithmException, NoSuchPaddingException
897     {
898         if (provider == null) {
899             throw new IllegalArgumentException("Missing provider");
900         }
901         return createCipher(transformation, provider);
902     }
903 
createCipher(String transformation, Provider provider)904     static final Cipher createCipher(String transformation, Provider provider)
905         throws NoSuchAlgorithmException, NoSuchPaddingException {
906         String[] tokenizedTransformation = tokenizeTransformation(transformation);
907 
908         CipherSpiAndProvider cipherSpiAndProvider = null;
909         try {
910             cipherSpiAndProvider =
911                 tryCombinations(null /*params*/, provider, tokenizedTransformation);
912         } catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
913             // Shouldn't happen.
914             throw new IllegalStateException("Key/Algorithm excepton despite not passing one", e);
915         }
916 
917         if (cipherSpiAndProvider == null) {
918             if (provider == null) {
919                 throw new NoSuchAlgorithmException("No provider found for " + transformation);
920             } else {
921                 throw new NoSuchAlgorithmException("Provider " + provider.getName()
922                         + " does not provide " + transformation);
923             }
924         }
925 
926         // exceptions and stuff
927         return new Cipher(null, provider, transformation, tokenizedTransformation);
928     }
929 
930     /**
931      * Choose the Spi from the first provider available. Used if
932      * delayed provider selection is not possible because init()
933      * is not the first method called.
934      */
updateProviderIfNeeded()935     void updateProviderIfNeeded() {
936         try {
937             spiAndProviderUpdater.updateAndGetSpiAndProvider(null, spi, provider);
938         } catch (Exception lastException) {
939             ProviderException e = new ProviderException
940                     ("Could not construct CipherSpi instance");
941             if (lastException != null) {
942                 e.initCause(lastException);
943             }
944             throw e;
945         }
946     }
947 
chooseProvider(InitType initType, int opmode, Key key, AlgorithmParameterSpec paramSpec, AlgorithmParameters params, SecureRandom random)948     private void chooseProvider(InitType initType, int opmode, Key key,
949             AlgorithmParameterSpec paramSpec,
950             AlgorithmParameters params, SecureRandom random)
951             throws InvalidKeyException, InvalidAlgorithmParameterException {
952 
953         try {
954             final InitParams initParams = new InitParams(initType, opmode, key, random,
955                                                          paramSpec, params);
956             spiAndProviderUpdater.updateAndGetSpiAndProvider(initParams, spi, provider);
957         } catch (Exception lastException) {
958             // no working provider found, fail
959             if (lastException instanceof InvalidKeyException) {
960                 throw (InvalidKeyException)lastException;
961             }
962             if (lastException instanceof InvalidAlgorithmParameterException) {
963                 throw (InvalidAlgorithmParameterException)lastException;
964             }
965             if (lastException instanceof RuntimeException) {
966                 throw (RuntimeException)lastException;
967             }
968             String kName = (key != null) ? key.getClass().getName() : "(null)";
969             throw new InvalidKeyException
970                 ("No installed provider supports this key: "
971                 + kName, lastException);
972         }
973     }
974 
975     /**
976      * Returns the provider of this <code>Cipher</code> object.
977      *
978      * @return the provider of this <code>Cipher</code> object
979      */
getProvider()980     public final Provider getProvider() {
981         updateProviderIfNeeded();
982         return this.provider;
983     }
984 
985     /**
986      * Returns the algorithm name of this <code>Cipher</code> object.
987      *
988      * <p>This is the same name that was specified in one of the
989      * <code>getInstance</code> calls that created this <code>Cipher</code>
990      * object..
991      *
992      * @return the algorithm name of this <code>Cipher</code> object.
993      */
getAlgorithm()994     public final String getAlgorithm() {
995         return this.transformation;
996     }
997 
998     /**
999      * Returns the block size (in bytes).
1000      *
1001      * @return the block size (in bytes), or 0 if the underlying algorithm is
1002      * not a block cipher
1003      */
getBlockSize()1004     public final int getBlockSize() {
1005         updateProviderIfNeeded();
1006         return spi.engineGetBlockSize();
1007     }
1008 
1009     /**
1010      * Returns the length in bytes that an output buffer would need to be in
1011      * order to hold the result of the next <code>update</code> or
1012      * <code>doFinal</code> operation, given the input length
1013      * <code>inputLen</code> (in bytes).
1014      *
1015      * <p>This call takes into account any unprocessed (buffered) data from a
1016      * previous <code>update</code> call, padding, and AEAD tagging.
1017      *
1018      * <p>The actual output length of the next <code>update</code> or
1019      * <code>doFinal</code> call may be smaller than the length returned by
1020      * this method.
1021      *
1022      * @param inputLen the input length (in bytes)
1023      *
1024      * @return the required output buffer size (in bytes)
1025      *
1026      * @exception IllegalStateException if this cipher is in a wrong state
1027      * (e.g., has not yet been initialized)
1028      */
getOutputSize(int inputLen)1029     public final int getOutputSize(int inputLen) {
1030 
1031         if (!initialized && !(this instanceof NullCipher)) {
1032             throw new IllegalStateException("Cipher not initialized");
1033         }
1034         if (inputLen < 0) {
1035             throw new IllegalArgumentException("Input size must be equal " +
1036                                                "to or greater than zero");
1037         }
1038         updateProviderIfNeeded();
1039         return spi.engineGetOutputSize(inputLen);
1040     }
1041 
1042     /**
1043      * Returns the initialization vector (IV) in a new buffer.
1044      *
1045      * <p>This is useful in the case where a random IV was created,
1046      * or in the context of password-based encryption or
1047      * decryption, where the IV is derived from a user-supplied password.
1048      *
1049      * @return the initialization vector in a new buffer, or null if the
1050      * underlying algorithm does not use an IV, or if the IV has not yet
1051      * been set.
1052      */
getIV()1053     public final byte[] getIV() {
1054         updateProviderIfNeeded();
1055         return spi.engineGetIV();
1056     }
1057 
1058     /**
1059      * Returns the parameters used with this cipher.
1060      *
1061      * <p>The returned parameters may be the same that were used to initialize
1062      * this cipher, or may contain a combination of default and random
1063      * parameter values used by the underlying cipher implementation if this
1064      * cipher requires algorithm parameters but was not initialized with any.
1065      *
1066      * @return the parameters used with this cipher, or null if this cipher
1067      * does not use any parameters.
1068      */
getParameters()1069     public final AlgorithmParameters getParameters() {
1070         updateProviderIfNeeded();
1071         return spi.engineGetParameters();
1072     }
1073 
1074     /**
1075      * Returns the exemption mechanism object used with this cipher.
1076      *
1077      * @return the exemption mechanism object used with this cipher, or
1078      * null if this cipher does not use any exemption mechanism.
1079      */
getExemptionMechanism()1080     public final ExemptionMechanism getExemptionMechanism() {
1081         updateProviderIfNeeded();
1082         return exmech;
1083     }
1084 
1085     // check if opmode is one of the defined constants
1086     // throw InvalidParameterExeption if not
checkOpmode(int opmode)1087     private static void checkOpmode(int opmode) {
1088         if ((opmode < ENCRYPT_MODE) || (opmode > UNWRAP_MODE)) {
1089             throw new InvalidParameterException("Invalid operation mode");
1090         }
1091     }
1092 
1093     /**
1094      * Initializes this cipher with a key.
1095      *
1096      * <p>The cipher is initialized for one of the following four operations:
1097      * encryption, decryption, key wrapping or key unwrapping, depending
1098      * on the value of <code>opmode</code>.
1099      *
1100      * <p>If this cipher requires any algorithm parameters that cannot be
1101      * derived from the given <code>key</code>, the underlying cipher
1102      * implementation is supposed to generate the required parameters itself
1103      * (using provider-specific default or random values) if it is being
1104      * initialized for encryption or key wrapping, and raise an
1105      * <code>InvalidKeyException</code> if it is being
1106      * initialized for decryption or key unwrapping.
1107      * The generated parameters can be retrieved using
1108      * {@link #getParameters() getParameters} or
1109      * {@link #getIV() getIV} (if the parameter is an IV).
1110      *
1111      * <p>If this cipher requires algorithm parameters that cannot be
1112      * derived from the input parameters, and there are no reasonable
1113      * provider-specific default values, initialization will
1114      * necessarily fail.
1115      *
1116      * <p>If this cipher (including its underlying feedback or padding scheme)
1117      * requires any random bytes (e.g., for parameter generation), it will get
1118      * them using the {@link SecureRandom <code>SecureRandom</code>}
1119      * implementation of the highest-priority
1120      * installed provider as the source of randomness.
1121      * (If none of the installed providers supply an implementation of
1122      * SecureRandom, a system-provided source of randomness will be used.)
1123      *
1124      * <p>Note that when a Cipher object is initialized, it loses all
1125      * previously-acquired state. In other words, initializing a Cipher is
1126      * equivalent to creating a new instance of that Cipher and initializing
1127      * it.
1128      *
1129      * @param opmode the operation mode of this cipher (this is one of
1130      * the following:
1131      * <code>ENCRYPT_MODE</code>, <code>DECRYPT_MODE</code>,
1132      * <code>WRAP_MODE</code> or <code>UNWRAP_MODE</code>)
1133      * @param key the key
1134      *
1135      * @exception InvalidKeyException if the given key is inappropriate for
1136      * initializing this cipher, or requires
1137      * algorithm parameters that cannot be
1138      * determined from the given key, or if the given key has a keysize that
1139      * exceeds the maximum allowable keysize (as determined from the
1140      * configured jurisdiction policy files).
1141      */
init(int opmode, Key key)1142     public final void init(int opmode, Key key) throws InvalidKeyException {
1143         init(opmode, key, JceSecurity.RANDOM);
1144     }
1145 
1146     /**
1147      * Initializes this cipher with a key and a source of randomness.
1148      *
1149      * <p>The cipher is initialized for one of the following four operations:
1150      * encryption, decryption, key wrapping or  key unwrapping, depending
1151      * on the value of <code>opmode</code>.
1152      *
1153      * <p>If this cipher requires any algorithm parameters that cannot be
1154      * derived from the given <code>key</code>, the underlying cipher
1155      * implementation is supposed to generate the required parameters itself
1156      * (using provider-specific default or random values) if it is being
1157      * initialized for encryption or key wrapping, and raise an
1158      * <code>InvalidKeyException</code> if it is being
1159      * initialized for decryption or key unwrapping.
1160      * The generated parameters can be retrieved using
1161      * {@link #getParameters() getParameters} or
1162      * {@link #getIV() getIV} (if the parameter is an IV).
1163      *
1164      * <p>If this cipher requires algorithm parameters that cannot be
1165      * derived from the input parameters, and there are no reasonable
1166      * provider-specific default values, initialization will
1167      * necessarily fail.
1168      *
1169      * <p>If this cipher (including its underlying feedback or padding scheme)
1170      * requires any random bytes (e.g., for parameter generation), it will get
1171      * them from <code>random</code>.
1172      *
1173      * <p>Note that when a Cipher object is initialized, it loses all
1174      * previously-acquired state. In other words, initializing a Cipher is
1175      * equivalent to creating a new instance of that Cipher and initializing
1176      * it.
1177      *
1178      * @param opmode the operation mode of this cipher (this is one of the
1179      * following:
1180      * <code>ENCRYPT_MODE</code>, <code>DECRYPT_MODE</code>,
1181      * <code>WRAP_MODE</code> or <code>UNWRAP_MODE</code>)
1182      * @param key the encryption key
1183      * @param random the source of randomness
1184      *
1185      * @exception InvalidKeyException if the given key is inappropriate for
1186      * initializing this cipher, or requires
1187      * algorithm parameters that cannot be
1188      * determined from the given key, or if the given key has a keysize that
1189      * exceeds the maximum allowable keysize (as determined from the
1190      * configured jurisdiction policy files).
1191      */
init(int opmode, Key key, SecureRandom random)1192     public final void init(int opmode, Key key, SecureRandom random)
1193             throws InvalidKeyException
1194     {
1195         initialized = false;
1196         checkOpmode(opmode);
1197 
1198         try {
1199             chooseProvider(InitType.KEY, opmode, key, null, null, random);
1200         } catch (InvalidAlgorithmParameterException e) {
1201             // should never occur
1202             throw new InvalidKeyException(e);
1203         }
1204 
1205         initialized = true;
1206         this.opmode = opmode;
1207     }
1208 
1209     /**
1210      * Initializes this cipher with a key and a set of algorithm
1211      * parameters.
1212      *
1213      * <p>The cipher is initialized for one of the following four operations:
1214      * encryption, decryption, key wrapping or  key unwrapping, depending
1215      * on the value of <code>opmode</code>.
1216      *
1217      * <p>If this cipher requires any algorithm parameters and
1218      * <code>params</code> is null, the underlying cipher implementation is
1219      * supposed to generate the required parameters itself (using
1220      * provider-specific default or random values) if it is being
1221      * initialized for encryption or key wrapping, and raise an
1222      * <code>InvalidAlgorithmParameterException</code> if it is being
1223      * initialized for decryption or key unwrapping.
1224      * The generated parameters can be retrieved using
1225      * {@link #getParameters() getParameters} or
1226      * {@link #getIV() getIV} (if the parameter is an IV).
1227      *
1228      * <p>If this cipher requires algorithm parameters that cannot be
1229      * derived from the input parameters, and there are no reasonable
1230      * provider-specific default values, initialization will
1231      * necessarily fail.
1232      *
1233      * <p>If this cipher (including its underlying feedback or padding scheme)
1234      * requires any random bytes (e.g., for parameter generation), it will get
1235      * them using the {@link SecureRandom <code>SecureRandom</code>}
1236      * implementation of the highest-priority
1237      * installed provider as the source of randomness.
1238      * (If none of the installed providers supply an implementation of
1239      * SecureRandom, a system-provided source of randomness will be used.)
1240      *
1241      * <p>Note that when a Cipher object is initialized, it loses all
1242      * previously-acquired state. In other words, initializing a Cipher is
1243      * equivalent to creating a new instance of that Cipher and initializing
1244      * it.
1245      *
1246      * @param opmode the operation mode of this cipher (this is one of the
1247      * following:
1248      * <code>ENCRYPT_MODE</code>, <code>DECRYPT_MODE</code>,
1249      * <code>WRAP_MODE</code> or <code>UNWRAP_MODE</code>)
1250      * @param key the encryption key
1251      * @param params the algorithm parameters
1252      *
1253      * @exception InvalidKeyException if the given key is inappropriate for
1254      * initializing this cipher, or its keysize exceeds the maximum allowable
1255      * keysize (as determined from the configured jurisdiction policy files).
1256      * @exception InvalidAlgorithmParameterException if the given algorithm
1257      * parameters are inappropriate for this cipher,
1258      * or this cipher requires
1259      * algorithm parameters and <code>params</code> is null, or the given
1260      * algorithm parameters imply a cryptographic strength that would exceed
1261      * the legal limits (as determined from the configured jurisdiction
1262      * policy files).
1263      */
init(int opmode, Key key, AlgorithmParameterSpec params)1264     public final void init(int opmode, Key key, AlgorithmParameterSpec params)
1265             throws InvalidKeyException, InvalidAlgorithmParameterException
1266     {
1267         init(opmode, key, params, JceSecurity.RANDOM);
1268     }
1269 
1270     /**
1271      * Initializes this cipher with a key, a set of algorithm
1272      * parameters, and a source of randomness.
1273      *
1274      * <p>The cipher is initialized for one of the following four operations:
1275      * encryption, decryption, key wrapping or  key unwrapping, depending
1276      * on the value of <code>opmode</code>.
1277      *
1278      * <p>If this cipher requires any algorithm parameters and
1279      * <code>params</code> is null, the underlying cipher implementation is
1280      * supposed to generate the required parameters itself (using
1281      * provider-specific default or random values) if it is being
1282      * initialized for encryption or key wrapping, and raise an
1283      * <code>InvalidAlgorithmParameterException</code> if it is being
1284      * initialized for decryption or key unwrapping.
1285      * The generated parameters can be retrieved using
1286      * {@link #getParameters() getParameters} or
1287      * {@link #getIV() getIV} (if the parameter is an IV).
1288      *
1289      * <p>If this cipher requires algorithm parameters that cannot be
1290      * derived from the input parameters, and there are no reasonable
1291      * provider-specific default values, initialization will
1292      * necessarily fail.
1293      *
1294      * <p>If this cipher (including its underlying feedback or padding scheme)
1295      * requires any random bytes (e.g., for parameter generation), it will get
1296      * them from <code>random</code>.
1297      *
1298      * <p>Note that when a Cipher object is initialized, it loses all
1299      * previously-acquired state. In other words, initializing a Cipher is
1300      * equivalent to creating a new instance of that Cipher and initializing
1301      * it.
1302      *
1303      * @param opmode the operation mode of this cipher (this is one of the
1304      * following:
1305      * <code>ENCRYPT_MODE</code>, <code>DECRYPT_MODE</code>,
1306      * <code>WRAP_MODE</code> or <code>UNWRAP_MODE</code>)
1307      * @param key the encryption key
1308      * @param params the algorithm parameters
1309      * @param random the source of randomness
1310      *
1311      * @exception InvalidKeyException if the given key is inappropriate for
1312      * initializing this cipher, or its keysize exceeds the maximum allowable
1313      * keysize (as determined from the configured jurisdiction policy files).
1314      * @exception InvalidAlgorithmParameterException if the given algorithm
1315      * parameters are inappropriate for this cipher,
1316      * or this cipher requires
1317      * algorithm parameters and <code>params</code> is null, or the given
1318      * algorithm parameters imply a cryptographic strength that would exceed
1319      * the legal limits (as determined from the configured jurisdiction
1320      * policy files).
1321      */
init(int opmode, Key key, AlgorithmParameterSpec params, SecureRandom random)1322     public final void init(int opmode, Key key, AlgorithmParameterSpec params,
1323                            SecureRandom random)
1324             throws InvalidKeyException, InvalidAlgorithmParameterException
1325     {
1326         initialized = false;
1327         checkOpmode(opmode);
1328 
1329         chooseProvider(InitType.ALGORITHM_PARAM_SPEC, opmode, key, params, null, random);
1330 
1331         initialized = true;
1332         this.opmode = opmode;
1333     }
1334 
1335     /**
1336      * Initializes this cipher with a key and a set of algorithm
1337      * parameters.
1338      *
1339      * <p>The cipher is initialized for one of the following four operations:
1340      * encryption, decryption, key wrapping or  key unwrapping, depending
1341      * on the value of <code>opmode</code>.
1342      *
1343      * <p>If this cipher requires any algorithm parameters and
1344      * <code>params</code> is null, the underlying cipher implementation is
1345      * supposed to generate the required parameters itself (using
1346      * provider-specific default or random values) if it is being
1347      * initialized for encryption or key wrapping, and raise an
1348      * <code>InvalidAlgorithmParameterException</code> if it is being
1349      * initialized for decryption or key unwrapping.
1350      * The generated parameters can be retrieved using
1351      * {@link #getParameters() getParameters} or
1352      * {@link #getIV() getIV} (if the parameter is an IV).
1353      *
1354      * <p>If this cipher requires algorithm parameters that cannot be
1355      * derived from the input parameters, and there are no reasonable
1356      * provider-specific default values, initialization will
1357      * necessarily fail.
1358      *
1359      * <p>If this cipher (including its underlying feedback or padding scheme)
1360      * requires any random bytes (e.g., for parameter generation), it will get
1361      * them using the {@link SecureRandom <code>SecureRandom</code>}
1362      * implementation of the highest-priority
1363      * installed provider as the source of randomness.
1364      * (If none of the installed providers supply an implementation of
1365      * SecureRandom, a system-provided source of randomness will be used.)
1366      *
1367      * <p>Note that when a Cipher object is initialized, it loses all
1368      * previously-acquired state. In other words, initializing a Cipher is
1369      * equivalent to creating a new instance of that Cipher and initializing
1370      * it.
1371      *
1372      * @param opmode the operation mode of this cipher (this is one of the
1373      * following: <code>ENCRYPT_MODE</code>,
1374      * <code>DECRYPT_MODE</code>, <code>WRAP_MODE</code>
1375      * or <code>UNWRAP_MODE</code>)
1376      * @param key the encryption key
1377      * @param params the algorithm parameters
1378      *
1379      * @exception InvalidKeyException if the given key is inappropriate for
1380      * initializing this cipher, or its keysize exceeds the maximum allowable
1381      * keysize (as determined from the configured jurisdiction policy files).
1382      * @exception InvalidAlgorithmParameterException if the given algorithm
1383      * parameters are inappropriate for this cipher,
1384      * or this cipher requires
1385      * algorithm parameters and <code>params</code> is null, or the given
1386      * algorithm parameters imply a cryptographic strength that would exceed
1387      * the legal limits (as determined from the configured jurisdiction
1388      * policy files).
1389      */
init(int opmode, Key key, AlgorithmParameters params)1390     public final void init(int opmode, Key key, AlgorithmParameters params)
1391             throws InvalidKeyException, InvalidAlgorithmParameterException
1392     {
1393         init(opmode, key, params, JceSecurity.RANDOM);
1394     }
1395 
1396     /**
1397      * Initializes this cipher with a key, a set of algorithm
1398      * parameters, and a source of randomness.
1399      *
1400      * <p>The cipher is initialized for one of the following four operations:
1401      * encryption, decryption, key wrapping or  key unwrapping, depending
1402      * on the value of <code>opmode</code>.
1403      *
1404      * <p>If this cipher requires any algorithm parameters and
1405      * <code>params</code> is null, the underlying cipher implementation is
1406      * supposed to generate the required parameters itself (using
1407      * provider-specific default or random values) if it is being
1408      * initialized for encryption or key wrapping, and raise an
1409      * <code>InvalidAlgorithmParameterException</code> if it is being
1410      * initialized for decryption or key unwrapping.
1411      * The generated parameters can be retrieved using
1412      * {@link #getParameters() getParameters} or
1413      * {@link #getIV() getIV} (if the parameter is an IV).
1414      *
1415      * <p>If this cipher requires algorithm parameters that cannot be
1416      * derived from the input parameters, and there are no reasonable
1417      * provider-specific default values, initialization will
1418      * necessarily fail.
1419      *
1420      * <p>If this cipher (including its underlying feedback or padding scheme)
1421      * requires any random bytes (e.g., for parameter generation), it will get
1422      * them from <code>random</code>.
1423      *
1424      * <p>Note that when a Cipher object is initialized, it loses all
1425      * previously-acquired state. In other words, initializing a Cipher is
1426      * equivalent to creating a new instance of that Cipher and initializing
1427      * it.
1428      *
1429      * @param opmode the operation mode of this cipher (this is one of the
1430      * following: <code>ENCRYPT_MODE</code>,
1431      * <code>DECRYPT_MODE</code>, <code>WRAP_MODE</code>
1432      * or <code>UNWRAP_MODE</code>)
1433      * @param key the encryption key
1434      * @param params the algorithm parameters
1435      * @param random the source of randomness
1436      *
1437      * @exception InvalidKeyException if the given key is inappropriate for
1438      * initializing this cipher, or its keysize exceeds the maximum allowable
1439      * keysize (as determined from the configured jurisdiction policy files).
1440      * @exception InvalidAlgorithmParameterException if the given algorithm
1441      * parameters are inappropriate for this cipher,
1442      * or this cipher requires
1443      * algorithm parameters and <code>params</code> is null, or the given
1444      * algorithm parameters imply a cryptographic strength that would exceed
1445      * the legal limits (as determined from the configured jurisdiction
1446      * policy files).
1447      */
init(int opmode, Key key, AlgorithmParameters params, SecureRandom random)1448     public final void init(int opmode, Key key, AlgorithmParameters params,
1449                            SecureRandom random)
1450             throws InvalidKeyException, InvalidAlgorithmParameterException
1451     {
1452         initialized = false;
1453         checkOpmode(opmode);
1454 
1455         chooseProvider(InitType.ALGORITHM_PARAMS, opmode, key, null, params, random);
1456 
1457         initialized = true;
1458         this.opmode = opmode;
1459     }
1460 
1461     /**
1462      * Initializes this cipher with the public key from the given certificate.
1463      * <p> The cipher is initialized for one of the following four operations:
1464      * encryption, decryption, key wrapping or  key unwrapping, depending
1465      * on the value of <code>opmode</code>.
1466      *
1467      * <p>If the certificate is of type X.509 and has a <i>key usage</i>
1468      * extension field marked as critical, and the value of the <i>key usage</i>
1469      * extension field implies that the public key in
1470      * the certificate and its corresponding private key are not
1471      * supposed to be used for the operation represented by the value
1472      * of <code>opmode</code>,
1473      * an <code>InvalidKeyException</code>
1474      * is thrown.
1475      *
1476      * <p> If this cipher requires any algorithm parameters that cannot be
1477      * derived from the public key in the given certificate, the underlying
1478      * cipher
1479      * implementation is supposed to generate the required parameters itself
1480      * (using provider-specific default or random values) if it is being
1481      * initialized for encryption or key wrapping, and raise an <code>
1482      * InvalidKeyException</code> if it is being initialized for decryption or
1483      * key unwrapping.
1484      * The generated parameters can be retrieved using
1485      * {@link #getParameters() getParameters} or
1486      * {@link #getIV() getIV} (if the parameter is an IV).
1487      *
1488      * <p>If this cipher requires algorithm parameters that cannot be
1489      * derived from the input parameters, and there are no reasonable
1490      * provider-specific default values, initialization will
1491      * necessarily fail.
1492      *
1493      * <p>If this cipher (including its underlying feedback or padding scheme)
1494      * requires any random bytes (e.g., for parameter generation), it will get
1495      * them using the
1496      * <code>SecureRandom</code>
1497      * implementation of the highest-priority
1498      * installed provider as the source of randomness.
1499      * (If none of the installed providers supply an implementation of
1500      * SecureRandom, a system-provided source of randomness will be used.)
1501      *
1502      * <p>Note that when a Cipher object is initialized, it loses all
1503      * previously-acquired state. In other words, initializing a Cipher is
1504      * equivalent to creating a new instance of that Cipher and initializing
1505      * it.
1506      *
1507      * @param opmode the operation mode of this cipher (this is one of the
1508      * following:
1509      * <code>ENCRYPT_MODE</code>, <code>DECRYPT_MODE</code>,
1510      * <code>WRAP_MODE</code> or <code>UNWRAP_MODE</code>)
1511      * @param certificate the certificate
1512      *
1513      * @exception InvalidKeyException if the public key in the given
1514      * certificate is inappropriate for initializing this cipher, or this
1515      * cipher requires algorithm parameters that cannot be determined from the
1516      * public key in the given certificate, or the keysize of the public key
1517      * in the given certificate has a keysize that exceeds the maximum
1518      * allowable keysize (as determined by the configured jurisdiction policy
1519      * files).
1520      */
init(int opmode, Certificate certificate)1521     public final void init(int opmode, Certificate certificate)
1522             throws InvalidKeyException
1523     {
1524         init(opmode, certificate, JceSecurity.RANDOM);
1525     }
1526 
1527     /**
1528      * Initializes this cipher with the public key from the given certificate
1529      * and
1530      * a source of randomness.
1531      *
1532      * <p>The cipher is initialized for one of the following four operations:
1533      * encryption, decryption, key wrapping
1534      * or key unwrapping, depending on
1535      * the value of <code>opmode</code>.
1536      *
1537      * <p>If the certificate is of type X.509 and has a <i>key usage</i>
1538      * extension field marked as critical, and the value of the <i>key usage</i>
1539      * extension field implies that the public key in
1540      * the certificate and its corresponding private key are not
1541      * supposed to be used for the operation represented by the value of
1542      * <code>opmode</code>,
1543      * an <code>InvalidKeyException</code>
1544      * is thrown.
1545      *
1546      * <p>If this cipher requires any algorithm parameters that cannot be
1547      * derived from the public key in the given <code>certificate</code>,
1548      * the underlying cipher
1549      * implementation is supposed to generate the required parameters itself
1550      * (using provider-specific default or random values) if it is being
1551      * initialized for encryption or key wrapping, and raise an
1552      * <code>InvalidKeyException</code> if it is being
1553      * initialized for decryption or key unwrapping.
1554      * The generated parameters can be retrieved using
1555      * {@link #getParameters() getParameters} or
1556      * {@link #getIV() getIV} (if the parameter is an IV).
1557      *
1558      * <p>If this cipher requires algorithm parameters that cannot be
1559      * derived from the input parameters, and there are no reasonable
1560      * provider-specific default values, initialization will
1561      * necessarily fail.
1562      *
1563      * <p>If this cipher (including its underlying feedback or padding scheme)
1564      * requires any random bytes (e.g., for parameter generation), it will get
1565      * them from <code>random</code>.
1566      *
1567      * <p>Note that when a Cipher object is initialized, it loses all
1568      * previously-acquired state. In other words, initializing a Cipher is
1569      * equivalent to creating a new instance of that Cipher and initializing
1570      * it.
1571      *
1572      * @param opmode the operation mode of this cipher (this is one of the
1573      * following:
1574      * <code>ENCRYPT_MODE</code>, <code>DECRYPT_MODE</code>,
1575      * <code>WRAP_MODE</code> or <code>UNWRAP_MODE</code>)
1576      * @param certificate the certificate
1577      * @param random the source of randomness
1578      *
1579      * @exception InvalidKeyException if the public key in the given
1580      * certificate is inappropriate for initializing this cipher, or this
1581      * cipher
1582      * requires algorithm parameters that cannot be determined from the
1583      * public key in the given certificate, or the keysize of the public key
1584      * in the given certificate has a keysize that exceeds the maximum
1585      * allowable keysize (as determined by the configured jurisdiction policy
1586      * files).
1587      */
init(int opmode, Certificate certificate, SecureRandom random)1588     public final void init(int opmode, Certificate certificate,
1589                            SecureRandom random)
1590             throws InvalidKeyException {
1591         initialized = false;
1592         checkOpmode(opmode);
1593 
1594         // Check key usage if the certificate is of
1595         // type X.509.
1596         if (certificate instanceof java.security.cert.X509Certificate) {
1597             // Check whether the cert has a key usage extension
1598             // marked as a critical extension.
1599             X509Certificate cert = (X509Certificate) certificate;
1600             Set critSet = cert.getCriticalExtensionOIDs();
1601 
1602             if (critSet != null && !critSet.isEmpty()
1603                     && critSet.contains(KEY_USAGE_EXTENSION_OID)) {
1604                 boolean[] keyUsageInfo = cert.getKeyUsage();
1605                 // keyUsageInfo[2] is for keyEncipherment;
1606                 // keyUsageInfo[3] is for dataEncipherment.
1607                 if ((keyUsageInfo != null) &&
1608                         (((opmode == Cipher.ENCRYPT_MODE) &&
1609                                 (keyUsageInfo.length > 3) &&
1610                                 (keyUsageInfo[3] == false)) ||
1611                                 ((opmode == Cipher.WRAP_MODE) &&
1612                                         (keyUsageInfo.length > 2) &&
1613                                         (keyUsageInfo[2] == false)))) {
1614                     throw new InvalidKeyException("Wrong key usage");
1615                 }
1616             }
1617         }
1618 
1619         PublicKey publicKey =
1620                 (certificate == null ? null : certificate.getPublicKey());
1621 
1622         try {
1623             chooseProvider(InitType.KEY, opmode, (Key) publicKey, null, null, random);
1624         } catch (InvalidAlgorithmParameterException e) {
1625             // should never occur
1626             throw new InvalidKeyException(e);
1627         }
1628 
1629         initialized = true;
1630         this.opmode = opmode;
1631     }
1632 
1633     /**
1634      * Ensures that Cipher is in a valid state for update() and doFinal()
1635      * calls - should be initialized and in ENCRYPT_MODE or DECRYPT_MODE.
1636      * @throws IllegalStateException if Cipher object is not in valid state.
1637      */
checkCipherState()1638     private void checkCipherState() {
1639         if (!(this instanceof NullCipher)) {
1640             if (!initialized) {
1641                 throw new IllegalStateException("Cipher not initialized");
1642             }
1643             if ((opmode != Cipher.ENCRYPT_MODE) &&
1644                 (opmode != Cipher.DECRYPT_MODE)) {
1645                 throw new IllegalStateException("Cipher not initialized " +
1646                                                 "for encryption/decryption");
1647             }
1648         }
1649     }
1650 
1651     /**
1652      * Continues a multiple-part encryption or decryption operation
1653      * (depending on how this cipher was initialized), processing another data
1654      * part.
1655      *
1656      * <p>The bytes in the <code>input</code> buffer are processed, and the
1657      * result is stored in a new buffer.
1658      *
1659      * <p>If <code>input</code> has a length of zero, this method returns
1660      * <code>null</code>.
1661      *
1662      * @param input the input buffer
1663      *
1664      * @return the new buffer with the result, or null if the underlying
1665      * cipher is a block cipher and the input data is too short to result in a
1666      * new block.
1667      *
1668      * @exception IllegalStateException if this cipher is in a wrong state
1669      * (e.g., has not been initialized)
1670      */
update(byte[] input)1671     public final byte[] update(byte[] input) {
1672         checkCipherState();
1673 
1674         // Input sanity check
1675         if (input == null) {
1676             throw new IllegalArgumentException("Null input buffer");
1677         }
1678 
1679         updateProviderIfNeeded();
1680         if (input.length == 0) {
1681             return null;
1682         }
1683         return spi.engineUpdate(input, 0, input.length);
1684     }
1685 
1686     /**
1687      * Continues a multiple-part encryption or decryption operation
1688      * (depending on how this cipher was initialized), processing another data
1689      * part.
1690      *
1691      * <p>The first <code>inputLen</code> bytes in the <code>input</code>
1692      * buffer, starting at <code>inputOffset</code> inclusive, are processed,
1693      * and the result is stored in a new buffer.
1694      *
1695      * <p>If <code>inputLen</code> is zero, this method returns
1696      * <code>null</code>.
1697      *
1698      * @param input the input buffer
1699      * @param inputOffset the offset in <code>input</code> where the input
1700      * starts
1701      * @param inputLen the input length
1702      *
1703      * @return the new buffer with the result, or null if the underlying
1704      * cipher is a block cipher and the input data is too short to result in a
1705      * new block.
1706      *
1707      * @exception IllegalStateException if this cipher is in a wrong state
1708      * (e.g., has not been initialized)
1709      */
update(byte[] input, int inputOffset, int inputLen)1710     public final byte[] update(byte[] input, int inputOffset, int inputLen) {
1711         checkCipherState();
1712 
1713         // Input sanity check
1714         if (input == null || inputOffset < 0
1715             || inputLen > (input.length - inputOffset) || inputLen < 0) {
1716             throw new IllegalArgumentException("Bad arguments");
1717         }
1718 
1719         updateProviderIfNeeded();
1720         if (inputLen == 0) {
1721             return null;
1722         }
1723         return spi.engineUpdate(input, inputOffset, inputLen);
1724     }
1725 
1726     /**
1727      * Continues a multiple-part encryption or decryption operation
1728      * (depending on how this cipher was initialized), processing another data
1729      * part.
1730      *
1731      * <p>The first <code>inputLen</code> bytes in the <code>input</code>
1732      * buffer, starting at <code>inputOffset</code> inclusive, are processed,
1733      * and the result is stored in the <code>output</code> buffer.
1734      *
1735      * <p>If the <code>output</code> buffer is too small to hold the result,
1736      * a <code>ShortBufferException</code> is thrown. In this case, repeat this
1737      * call with a larger output buffer. Use
1738      * {@link #getOutputSize(int) getOutputSize} to determine how big
1739      * the output buffer should be.
1740      *
1741      * <p>If <code>inputLen</code> is zero, this method returns
1742      * a length of zero.
1743      *
1744      * <p>Note: this method should be copy-safe, which means the
1745      * <code>input</code> and <code>output</code> buffers can reference
1746      * the same byte array and no unprocessed input data is overwritten
1747      * when the result is copied into the output buffer.
1748      *
1749      * @param input the input buffer
1750      * @param inputOffset the offset in <code>input</code> where the input
1751      * starts
1752      * @param inputLen the input length
1753      * @param output the buffer for the result
1754      *
1755      * @return the number of bytes stored in <code>output</code>
1756      *
1757      * @exception IllegalStateException if this cipher is in a wrong state
1758      * (e.g., has not been initialized)
1759      * @exception ShortBufferException if the given output buffer is too small
1760      * to hold the result
1761      */
update(byte[] input, int inputOffset, int inputLen, byte[] output)1762     public final int update(byte[] input, int inputOffset, int inputLen,
1763                             byte[] output)
1764             throws ShortBufferException {
1765         checkCipherState();
1766 
1767         // Input sanity check
1768         if (input == null || inputOffset < 0
1769             || inputLen > (input.length - inputOffset) || inputLen < 0) {
1770             throw new IllegalArgumentException("Bad arguments");
1771         }
1772 
1773         updateProviderIfNeeded();
1774         if (inputLen == 0) {
1775             return 0;
1776         }
1777         return spi.engineUpdate(input, inputOffset, inputLen,
1778                                       output, 0);
1779     }
1780 
1781     /**
1782      * Continues a multiple-part encryption or decryption operation
1783      * (depending on how this cipher was initialized), processing another data
1784      * part.
1785      *
1786      * <p>The first <code>inputLen</code> bytes in the <code>input</code>
1787      * buffer, starting at <code>inputOffset</code> inclusive, are processed,
1788      * and the result is stored in the <code>output</code> buffer, starting at
1789      * <code>outputOffset</code> inclusive.
1790      *
1791      * <p>If the <code>output</code> buffer is too small to hold the result,
1792      * a <code>ShortBufferException</code> is thrown. In this case, repeat this
1793      * call with a larger output buffer. Use
1794      * {@link #getOutputSize(int) getOutputSize} to determine how big
1795      * the output buffer should be.
1796      *
1797      * <p>If <code>inputLen</code> is zero, this method returns
1798      * a length of zero.
1799      *
1800      * <p>Note: this method should be copy-safe, which means the
1801      * <code>input</code> and <code>output</code> buffers can reference
1802      * the same byte array and no unprocessed input data is overwritten
1803      * when the result is copied into the output buffer.
1804      *
1805      * @param input the input buffer
1806      * @param inputOffset the offset in <code>input</code> where the input
1807      * starts
1808      * @param inputLen the input length
1809      * @param output the buffer for the result
1810      * @param outputOffset the offset in <code>output</code> where the result
1811      * is stored
1812      *
1813      * @return the number of bytes stored in <code>output</code>
1814      *
1815      * @exception IllegalStateException if this cipher is in a wrong state
1816      * (e.g., has not been initialized)
1817      * @exception ShortBufferException if the given output buffer is too small
1818      * to hold the result
1819      */
update(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset)1820     public final int update(byte[] input, int inputOffset, int inputLen,
1821                             byte[] output, int outputOffset)
1822             throws ShortBufferException {
1823         checkCipherState();
1824 
1825         // Input sanity check
1826         if (input == null || inputOffset < 0
1827             || inputLen > (input.length - inputOffset) || inputLen < 0
1828             || outputOffset < 0) {
1829             throw new IllegalArgumentException("Bad arguments");
1830         }
1831 
1832         updateProviderIfNeeded();
1833         if (inputLen == 0) {
1834             return 0;
1835         }
1836         return spi.engineUpdate(input, inputOffset, inputLen,
1837                                       output, outputOffset);
1838     }
1839 
1840     /**
1841      * Continues a multiple-part encryption or decryption operation
1842      * (depending on how this cipher was initialized), processing another data
1843      * part.
1844      *
1845      * <p>All <code>input.remaining()</code> bytes starting at
1846      * <code>input.position()</code> are processed. The result is stored
1847      * in the output buffer.
1848      * Upon return, the input buffer's position will be equal
1849      * to its limit; its limit will not have changed. The output buffer's
1850      * position will have advanced by n, where n is the value returned
1851      * by this method; the output buffer's limit will not have changed.
1852      *
1853      * <p>If <code>output.remaining()</code> bytes are insufficient to
1854      * hold the result, a <code>ShortBufferException</code> is thrown.
1855      * In this case, repeat this call with a larger output buffer. Use
1856      * {@link #getOutputSize(int) getOutputSize} to determine how big
1857      * the output buffer should be.
1858      *
1859      * <p>Note: this method should be copy-safe, which means the
1860      * <code>input</code> and <code>output</code> buffers can reference
1861      * the same block of memory and no unprocessed input data is overwritten
1862      * when the result is copied into the output buffer.
1863      *
1864      * @param input the input ByteBuffer
1865      * @param output the output ByteByffer
1866      *
1867      * @return the number of bytes stored in <code>output</code>
1868      *
1869      * @exception IllegalStateException if this cipher is in a wrong state
1870      * (e.g., has not been initialized)
1871      * @exception IllegalArgumentException if input and output are the
1872      *   same object
1873      * @exception ReadOnlyBufferException if the output buffer is read-only
1874      * @exception ShortBufferException if there is insufficient space in the
1875      * output buffer
1876      * @since 1.5
1877      */
update(ByteBuffer input, ByteBuffer output)1878     public final int update(ByteBuffer input, ByteBuffer output)
1879             throws ShortBufferException {
1880         checkCipherState();
1881 
1882         if ((input == null) || (output == null)) {
1883             throw new IllegalArgumentException("Buffers must not be null");
1884         }
1885         if (input == output) {
1886             throw new IllegalArgumentException("Input and output buffers must "
1887                 + "not be the same object, consider using buffer.duplicate()");
1888         }
1889         if (output.isReadOnly()) {
1890             throw new ReadOnlyBufferException();
1891         }
1892 
1893         updateProviderIfNeeded();
1894         return spi.engineUpdate(input, output);
1895     }
1896 
1897     /**
1898      * Finishes a multiple-part encryption or decryption operation, depending
1899      * on how this cipher was initialized.
1900      *
1901      * <p>Input data that may have been buffered during a previous
1902      * <code>update</code> operation is processed, with padding (if requested)
1903      * being applied.
1904      * If an AEAD mode such as GCM/CCM is being used, the authentication
1905      * tag is appended in the case of encryption, or verified in the
1906      * case of decryption.
1907      * The result is stored in a new buffer.
1908      *
1909      * <p>Upon finishing, this method resets this cipher object to the state
1910      * it was in when previously initialized via a call to <code>init</code>.
1911      * That is, the object is reset and available to encrypt or decrypt
1912      * (depending on the operation mode that was specified in the call to
1913      * <code>init</code>) more data.
1914      *
1915      * <p>Note: if any exception is thrown, this cipher object may need to
1916      * be reset before it can be used again.
1917      *
1918      * @return the new buffer with the result
1919      *
1920      * @exception IllegalStateException if this cipher is in a wrong state
1921      * (e.g., has not been initialized)
1922      * @exception IllegalBlockSizeException if this cipher is a block cipher,
1923      * no padding has been requested (only in encryption mode), and the total
1924      * input length of the data processed by this cipher is not a multiple of
1925      * block size; or if this encryption algorithm is unable to
1926      * process the input data provided.
1927      * @exception BadPaddingException if this cipher is in decryption mode,
1928      * and (un)padding has been requested, but the decrypted data is not
1929      * bounded by the appropriate padding bytes
1930      * @exception AEADBadTagException if this cipher is decrypting in an
1931      * AEAD mode (such as GCM/CCM), and the received authentication tag
1932      * does not match the calculated value
1933      */
doFinal()1934     public final byte[] doFinal()
1935             throws IllegalBlockSizeException, BadPaddingException {
1936         checkCipherState();
1937 
1938         updateProviderIfNeeded();
1939         return spi.engineDoFinal(null, 0, 0);
1940     }
1941 
1942     /**
1943      * Finishes a multiple-part encryption or decryption operation, depending
1944      * on how this cipher was initialized.
1945      *
1946      * <p>Input data that may have been buffered during a previous
1947      * <code>update</code> operation is processed, with padding (if requested)
1948      * being applied.
1949      * If an AEAD mode such as GCM/CCM is being used, the authentication
1950      * tag is appended in the case of encryption, or verified in the
1951      * case of decryption.
1952      * The result is stored in the <code>output</code> buffer, starting at
1953      * <code>outputOffset</code> inclusive.
1954      *
1955      * <p>If the <code>output</code> buffer is too small to hold the result,
1956      * a <code>ShortBufferException</code> is thrown. In this case, repeat this
1957      * call with a larger output buffer. Use
1958      * {@link #getOutputSize(int) getOutputSize} to determine how big
1959      * the output buffer should be.
1960      *
1961      * <p>Upon finishing, this method resets this cipher object to the state
1962      * it was in when previously initialized via a call to <code>init</code>.
1963      * That is, the object is reset and available to encrypt or decrypt
1964      * (depending on the operation mode that was specified in the call to
1965      * <code>init</code>) more data.
1966      *
1967      * <p>Note: if any exception is thrown, this cipher object may need to
1968      * be reset before it can be used again.
1969      *
1970      * @param output the buffer for the result
1971      * @param outputOffset the offset in <code>output</code> where the result
1972      * is stored
1973      *
1974      * @return the number of bytes stored in <code>output</code>
1975      *
1976      * @exception IllegalStateException if this cipher is in a wrong state
1977      * (e.g., has not been initialized)
1978      * @exception IllegalBlockSizeException if this cipher is a block cipher,
1979      * no padding has been requested (only in encryption mode), and the total
1980      * input length of the data processed by this cipher is not a multiple of
1981      * block size; or if this encryption algorithm is unable to
1982      * process the input data provided.
1983      * @exception ShortBufferException if the given output buffer is too small
1984      * to hold the result
1985      * @exception BadPaddingException if this cipher is in decryption mode,
1986      * and (un)padding has been requested, but the decrypted data is not
1987      * bounded by the appropriate padding bytes
1988      * @exception AEADBadTagException if this cipher is decrypting in an
1989      * AEAD mode (such as GCM/CCM), and the received authentication tag
1990      * does not match the calculated value
1991      */
doFinal(byte[] output, int outputOffset)1992     public final int doFinal(byte[] output, int outputOffset)
1993             throws IllegalBlockSizeException, ShortBufferException,
1994                BadPaddingException {
1995         checkCipherState();
1996 
1997         // Input sanity check
1998         if ((output == null) || (outputOffset < 0)) {
1999             throw new IllegalArgumentException("Bad arguments");
2000         }
2001 
2002         updateProviderIfNeeded();
2003         return spi.engineDoFinal(null, 0, 0, output, outputOffset);
2004     }
2005 
2006     /**
2007      * Encrypts or decrypts data in a single-part operation, or finishes a
2008      * multiple-part operation. The data is encrypted or decrypted,
2009      * depending on how this cipher was initialized.
2010      *
2011      * <p>The bytes in the <code>input</code> buffer, and any input bytes that
2012      * may have been buffered during a previous <code>update</code> operation,
2013      * are processed, with padding (if requested) being applied.
2014      * If an AEAD mode such as GCM/CCM is being used, the authentication
2015      * tag is appended in the case of encryption, or verified in the
2016      * case of decryption.
2017      * The result is stored in a new buffer.
2018      *
2019      * <p>Upon finishing, this method resets this cipher object to the state
2020      * it was in when previously initialized via a call to <code>init</code>.
2021      * That is, the object is reset and available to encrypt or decrypt
2022      * (depending on the operation mode that was specified in the call to
2023      * <code>init</code>) more data.
2024      *
2025      * <p>Note: if any exception is thrown, this cipher object may need to
2026      * be reset before it can be used again.
2027      *
2028      * @param input the input buffer
2029      *
2030      * @return the new buffer with the result
2031      *
2032      * @exception IllegalStateException if this cipher is in a wrong state
2033      * (e.g., has not been initialized)
2034      * @exception IllegalBlockSizeException if this cipher is a block cipher,
2035      * no padding has been requested (only in encryption mode), and the total
2036      * input length of the data processed by this cipher is not a multiple of
2037      * block size; or if this encryption algorithm is unable to
2038      * process the input data provided.
2039      * @exception BadPaddingException if this cipher is in decryption mode,
2040      * and (un)padding has been requested, but the decrypted data is not
2041      * bounded by the appropriate padding bytes
2042      * @exception AEADBadTagException if this cipher is decrypting in an
2043      * AEAD mode (such as GCM/CCM), and the received authentication tag
2044      * does not match the calculated value
2045      */
doFinal(byte[] input)2046     public final byte[] doFinal(byte[] input)
2047             throws IllegalBlockSizeException, BadPaddingException {
2048         checkCipherState();
2049 
2050         // Input sanity check
2051         if (input == null) {
2052             throw new IllegalArgumentException("Null input buffer");
2053         }
2054 
2055         updateProviderIfNeeded();
2056         return spi.engineDoFinal(input, 0, input.length);
2057     }
2058 
2059     /**
2060      * Encrypts or decrypts data in a single-part operation, or finishes a
2061      * multiple-part operation. The data is encrypted or decrypted,
2062      * depending on how this cipher was initialized.
2063      *
2064      * <p>The first <code>inputLen</code> bytes in the <code>input</code>
2065      * buffer, starting at <code>inputOffset</code> inclusive, and any input
2066      * bytes that may have been buffered during a previous <code>update</code>
2067      * operation, are processed, with padding (if requested) being applied.
2068      * If an AEAD mode such as GCM/CCM is being used, the authentication
2069      * tag is appended in the case of encryption, or verified in the
2070      * case of decryption.
2071      * The result is stored in a new buffer.
2072      *
2073      * <p>Upon finishing, this method resets this cipher object to the state
2074      * it was in when previously initialized via a call to <code>init</code>.
2075      * That is, the object is reset and available to encrypt or decrypt
2076      * (depending on the operation mode that was specified in the call to
2077      * <code>init</code>) more data.
2078      *
2079      * <p>Note: if any exception is thrown, this cipher object may need to
2080      * be reset before it can be used again.
2081      *
2082      * @param input the input buffer
2083      * @param inputOffset the offset in <code>input</code> where the input
2084      * starts
2085      * @param inputLen the input length
2086      *
2087      * @return the new buffer with the result
2088      *
2089      * @exception IllegalStateException if this cipher is in a wrong state
2090      * (e.g., has not been initialized)
2091      * @exception IllegalBlockSizeException if this cipher is a block cipher,
2092      * no padding has been requested (only in encryption mode), and the total
2093      * input length of the data processed by this cipher is not a multiple of
2094      * block size; or if this encryption algorithm is unable to
2095      * process the input data provided.
2096      * @exception BadPaddingException if this cipher is in decryption mode,
2097      * and (un)padding has been requested, but the decrypted data is not
2098      * bounded by the appropriate padding bytes
2099      * @exception AEADBadTagException if this cipher is decrypting in an
2100      * AEAD mode (such as GCM/CCM), and the received authentication tag
2101      * does not match the calculated value
2102      */
doFinal(byte[] input, int inputOffset, int inputLen)2103     public final byte[] doFinal(byte[] input, int inputOffset, int inputLen)
2104             throws IllegalBlockSizeException, BadPaddingException {
2105         checkCipherState();
2106 
2107         // Input sanity check
2108         if (input == null || inputOffset < 0
2109             || inputLen > (input.length - inputOffset) || inputLen < 0) {
2110             throw new IllegalArgumentException("Bad arguments");
2111         }
2112 
2113         updateProviderIfNeeded();
2114         return spi.engineDoFinal(input, inputOffset, inputLen);
2115     }
2116 
2117     /**
2118      * Encrypts or decrypts data in a single-part operation, or finishes a
2119      * multiple-part operation. The data is encrypted or decrypted,
2120      * depending on how this cipher was initialized.
2121      *
2122      * <p>The first <code>inputLen</code> bytes in the <code>input</code>
2123      * buffer, starting at <code>inputOffset</code> inclusive, and any input
2124      * bytes that may have been buffered during a previous <code>update</code>
2125      * operation, are processed, with padding (if requested) being applied.
2126      * If an AEAD mode such as GCM/CCM is being used, the authentication
2127      * tag is appended in the case of encryption, or verified in the
2128      * case of decryption.
2129      * The result is stored in the <code>output</code> buffer.
2130      *
2131      * <p>If the <code>output</code> buffer is too small to hold the result,
2132      * a <code>ShortBufferException</code> is thrown. In this case, repeat this
2133      * call with a larger output buffer. Use
2134      * {@link #getOutputSize(int) getOutputSize} to determine how big
2135      * the output buffer should be.
2136      *
2137      * <p>Upon finishing, this method resets this cipher object to the state
2138      * it was in when previously initialized via a call to <code>init</code>.
2139      * That is, the object is reset and available to encrypt or decrypt
2140      * (depending on the operation mode that was specified in the call to
2141      * <code>init</code>) more data.
2142      *
2143      * <p>Note: if any exception is thrown, this cipher object may need to
2144      * be reset before it can be used again.
2145      *
2146      * <p>Note: this method should be copy-safe, which means the
2147      * <code>input</code> and <code>output</code> buffers can reference
2148      * the same byte array and no unprocessed input data is overwritten
2149      * when the result is copied into the output buffer.
2150      *
2151      * @param input the input buffer
2152      * @param inputOffset the offset in <code>input</code> where the input
2153      * starts
2154      * @param inputLen the input length
2155      * @param output the buffer for the result
2156      *
2157      * @return the number of bytes stored in <code>output</code>
2158      *
2159      * @exception IllegalStateException if this cipher is in a wrong state
2160      * (e.g., has not been initialized)
2161      * @exception IllegalBlockSizeException if this cipher is a block cipher,
2162      * no padding has been requested (only in encryption mode), and the total
2163      * input length of the data processed by this cipher is not a multiple of
2164      * block size; or if this encryption algorithm is unable to
2165      * process the input data provided.
2166      * @exception ShortBufferException if the given output buffer is too small
2167      * to hold the result
2168      * @exception BadPaddingException if this cipher is in decryption mode,
2169      * and (un)padding has been requested, but the decrypted data is not
2170      * bounded by the appropriate padding bytes
2171      * @exception AEADBadTagException if this cipher is decrypting in an
2172      * AEAD mode (such as GCM/CCM), and the received authentication tag
2173      * does not match the calculated value
2174      */
doFinal(byte[] input, int inputOffset, int inputLen, byte[] output)2175     public final int doFinal(byte[] input, int inputOffset, int inputLen,
2176                              byte[] output)
2177             throws ShortBufferException, IllegalBlockSizeException,
2178             BadPaddingException {
2179         checkCipherState();
2180 
2181         // Input sanity check
2182         if (input == null || inputOffset < 0
2183             || inputLen > (input.length - inputOffset) || inputLen < 0) {
2184             throw new IllegalArgumentException("Bad arguments");
2185         }
2186 
2187         updateProviderIfNeeded();
2188         return spi.engineDoFinal(input, inputOffset, inputLen,
2189                                        output, 0);
2190     }
2191 
2192     /**
2193      * Encrypts or decrypts data in a single-part operation, or finishes a
2194      * multiple-part operation. The data is encrypted or decrypted,
2195      * depending on how this cipher was initialized.
2196      *
2197      * <p>The first <code>inputLen</code> bytes in the <code>input</code>
2198      * buffer, starting at <code>inputOffset</code> inclusive, and any input
2199      * bytes that may have been buffered during a previous
2200      * <code>update</code> operation, are processed, with padding
2201      * (if requested) being applied.
2202      * If an AEAD mode such as GCM/CCM is being used, the authentication
2203      * tag is appended in the case of encryption, or verified in the
2204      * case of decryption.
2205      * The result is stored in the <code>output</code> buffer, starting at
2206      * <code>outputOffset</code> inclusive.
2207      *
2208      * <p>If the <code>output</code> buffer is too small to hold the result,
2209      * a <code>ShortBufferException</code> is thrown. In this case, repeat this
2210      * call with a larger output buffer. Use
2211      * {@link #getOutputSize(int) getOutputSize} to determine how big
2212      * the output buffer should be.
2213      *
2214      * <p>Upon finishing, this method resets this cipher object to the state
2215      * it was in when previously initialized via a call to <code>init</code>.
2216      * That is, the object is reset and available to encrypt or decrypt
2217      * (depending on the operation mode that was specified in the call to
2218      * <code>init</code>) more data.
2219      *
2220      * <p>Note: if any exception is thrown, this cipher object may need to
2221      * be reset before it can be used again.
2222      *
2223      * <p>Note: this method should be copy-safe, which means the
2224      * <code>input</code> and <code>output</code> buffers can reference
2225      * the same byte array and no unprocessed input data is overwritten
2226      * when the result is copied into the output buffer.
2227      *
2228      * @param input the input buffer
2229      * @param inputOffset the offset in <code>input</code> where the input
2230      * starts
2231      * @param inputLen the input length
2232      * @param output the buffer for the result
2233      * @param outputOffset the offset in <code>output</code> where the result
2234      * is stored
2235      *
2236      * @return the number of bytes stored in <code>output</code>
2237      *
2238      * @exception IllegalStateException if this cipher is in a wrong state
2239      * (e.g., has not been initialized)
2240      * @exception IllegalBlockSizeException if this cipher is a block cipher,
2241      * no padding has been requested (only in encryption mode), and the total
2242      * input length of the data processed by this cipher is not a multiple of
2243      * block size; or if this encryption algorithm is unable to
2244      * process the input data provided.
2245      * @exception ShortBufferException if the given output buffer is too small
2246      * to hold the result
2247      * @exception BadPaddingException if this cipher is in decryption mode,
2248      * and (un)padding has been requested, but the decrypted data is not
2249      * bounded by the appropriate padding bytes
2250      * @exception AEADBadTagException if this cipher is decrypting in an
2251      * AEAD mode (such as GCM/CCM), and the received authentication tag
2252      * does not match the calculated value
2253      */
doFinal(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset)2254     public final int doFinal(byte[] input, int inputOffset, int inputLen,
2255                              byte[] output, int outputOffset)
2256             throws ShortBufferException, IllegalBlockSizeException,
2257             BadPaddingException {
2258         checkCipherState();
2259 
2260         // Input sanity check
2261         if (input == null || inputOffset < 0
2262             || inputLen > (input.length - inputOffset) || inputLen < 0
2263             || outputOffset < 0) {
2264             throw new IllegalArgumentException("Bad arguments");
2265         }
2266 
2267         updateProviderIfNeeded();
2268         return spi.engineDoFinal(input, inputOffset, inputLen,
2269                                        output, outputOffset);
2270     }
2271 
2272     /**
2273      * Encrypts or decrypts data in a single-part operation, or finishes a
2274      * multiple-part operation. The data is encrypted or decrypted,
2275      * depending on how this cipher was initialized.
2276      *
2277      * <p>All <code>input.remaining()</code> bytes starting at
2278      * <code>input.position()</code> are processed.
2279      * If an AEAD mode such as GCM/CCM is being used, the authentication
2280      * tag is appended in the case of encryption, or verified in the
2281      * case of decryption.
2282      * The result is stored in the output buffer.
2283      * Upon return, the input buffer's position will be equal
2284      * to its limit; its limit will not have changed. The output buffer's
2285      * position will have advanced by n, where n is the value returned
2286      * by this method; the output buffer's limit will not have changed.
2287      *
2288      * <p>If <code>output.remaining()</code> bytes are insufficient to
2289      * hold the result, a <code>ShortBufferException</code> is thrown.
2290      * In this case, repeat this call with a larger output buffer. Use
2291      * {@link #getOutputSize(int) getOutputSize} to determine how big
2292      * the output buffer should be.
2293      *
2294      * <p>Upon finishing, this method resets this cipher object to the state
2295      * it was in when previously initialized via a call to <code>init</code>.
2296      * That is, the object is reset and available to encrypt or decrypt
2297      * (depending on the operation mode that was specified in the call to
2298      * <code>init</code>) more data.
2299      *
2300      * <p>Note: if any exception is thrown, this cipher object may need to
2301      * be reset before it can be used again.
2302      *
2303      * <p>Note: this method should be copy-safe, which means the
2304      * <code>input</code> and <code>output</code> buffers can reference
2305      * the same byte array and no unprocessed input data is overwritten
2306      * when the result is copied into the output buffer.
2307      *
2308      * @param input the input ByteBuffer
2309      * @param output the output ByteBuffer
2310      *
2311      * @return the number of bytes stored in <code>output</code>
2312      *
2313      * @exception IllegalStateException if this cipher is in a wrong state
2314      * (e.g., has not been initialized)
2315      * @exception IllegalArgumentException if input and output are the
2316      *   same object
2317      * @exception ReadOnlyBufferException if the output buffer is read-only
2318      * @exception IllegalBlockSizeException if this cipher is a block cipher,
2319      * no padding has been requested (only in encryption mode), and the total
2320      * input length of the data processed by this cipher is not a multiple of
2321      * block size; or if this encryption algorithm is unable to
2322      * process the input data provided.
2323      * @exception ShortBufferException if there is insufficient space in the
2324      * output buffer
2325      * @exception BadPaddingException if this cipher is in decryption mode,
2326      * and (un)padding has been requested, but the decrypted data is not
2327      * bounded by the appropriate padding bytes
2328      * @exception AEADBadTagException if this cipher is decrypting in an
2329      * AEAD mode (such as GCM/CCM), and the received authentication tag
2330      * does not match the calculated value
2331      *
2332      * @since 1.5
2333      */
doFinal(ByteBuffer input, ByteBuffer output)2334     public final int doFinal(ByteBuffer input, ByteBuffer output)
2335             throws ShortBufferException, IllegalBlockSizeException,
2336             BadPaddingException {
2337         checkCipherState();
2338 
2339         if ((input == null) || (output == null)) {
2340             throw new IllegalArgumentException("Buffers must not be null");
2341         }
2342         if (input == output) {
2343             throw new IllegalArgumentException("Input and output buffers must "
2344                 + "not be the same object, consider using buffer.duplicate()");
2345         }
2346         if (output.isReadOnly()) {
2347             throw new ReadOnlyBufferException();
2348         }
2349 
2350         updateProviderIfNeeded();
2351         return spi.engineDoFinal(input, output);
2352     }
2353 
2354     /**
2355      * Wrap a key.
2356      *
2357      * @param key the key to be wrapped.
2358      *
2359      * @return the wrapped key.
2360      *
2361      * @exception IllegalStateException if this cipher is in a wrong
2362      * state (e.g., has not been initialized).
2363      *
2364      * @exception IllegalBlockSizeException if this cipher is a block
2365      * cipher, no padding has been requested, and the length of the
2366      * encoding of the key to be wrapped is not a
2367      * multiple of the block size.
2368      *
2369      * @exception InvalidKeyException if it is impossible or unsafe to
2370      * wrap the key with this cipher (e.g., a hardware protected key is
2371      * being passed to a software-only cipher).
2372      */
wrap(Key key)2373     public final byte[] wrap(Key key)
2374             throws IllegalBlockSizeException, InvalidKeyException {
2375         if (!(this instanceof NullCipher)) {
2376             if (!initialized) {
2377                 throw new IllegalStateException("Cipher not initialized");
2378             }
2379             if (opmode != Cipher.WRAP_MODE) {
2380                 throw new IllegalStateException("Cipher not initialized " +
2381                                                 "for wrapping keys");
2382             }
2383         }
2384 
2385         updateProviderIfNeeded();
2386         return spi.engineWrap(key);
2387     }
2388 
2389     /**
2390      * Unwrap a previously wrapped key.
2391      *
2392      * @param wrappedKey the key to be unwrapped.
2393      *
2394      * @param wrappedKeyAlgorithm the algorithm associated with the wrapped
2395      * key.
2396      *
2397      * @param wrappedKeyType the type of the wrapped key. This must be one of
2398      * <code>SECRET_KEY</code>, <code>PRIVATE_KEY</code>, or
2399      * <code>PUBLIC_KEY</code>.
2400      *
2401      * @return the unwrapped key.
2402      *
2403      * @exception IllegalStateException if this cipher is in a wrong state
2404      * (e.g., has not been initialized).
2405      *
2406      * @exception NoSuchAlgorithmException if no installed providers
2407      * can create keys of type <code>wrappedKeyType</code> for the
2408      * <code>wrappedKeyAlgorithm</code>.
2409      *
2410      * @exception InvalidKeyException if <code>wrappedKey</code> does not
2411      * represent a wrapped key of type <code>wrappedKeyType</code> for
2412      * the <code>wrappedKeyAlgorithm</code>.
2413      */
unwrap(byte[] wrappedKey, String wrappedKeyAlgorithm, int wrappedKeyType)2414     public final Key unwrap(byte[] wrappedKey,
2415                             String wrappedKeyAlgorithm,
2416                             int wrappedKeyType)
2417             throws InvalidKeyException, NoSuchAlgorithmException {
2418 
2419         if (!(this instanceof NullCipher)) {
2420             if (!initialized) {
2421                 throw new IllegalStateException("Cipher not initialized");
2422             }
2423             if (opmode != Cipher.UNWRAP_MODE) {
2424                 throw new IllegalStateException("Cipher not initialized " +
2425                                                 "for unwrapping keys");
2426             }
2427         }
2428         if ((wrappedKeyType != SECRET_KEY) &&
2429             (wrappedKeyType != PRIVATE_KEY) &&
2430             (wrappedKeyType != PUBLIC_KEY)) {
2431             throw new InvalidParameterException("Invalid key type");
2432         }
2433 
2434         updateProviderIfNeeded();
2435         return spi.engineUnwrap(wrappedKey,
2436                                       wrappedKeyAlgorithm,
2437                                       wrappedKeyType);
2438     }
2439 
getAlgorithmParameterSpec( AlgorithmParameters params)2440     private AlgorithmParameterSpec getAlgorithmParameterSpec(
2441                                       AlgorithmParameters params)
2442             throws InvalidParameterSpecException {
2443         if (params == null) {
2444             return null;
2445         }
2446 
2447         String alg = params.getAlgorithm().toUpperCase(Locale.ENGLISH);
2448 
2449         if (alg.equalsIgnoreCase("RC2")) {
2450             return params.getParameterSpec(RC2ParameterSpec.class);
2451         }
2452 
2453         if (alg.equalsIgnoreCase("RC5")) {
2454             return params.getParameterSpec(RC5ParameterSpec.class);
2455         }
2456 
2457         if (alg.startsWith("PBE")) {
2458             return params.getParameterSpec(PBEParameterSpec.class);
2459         }
2460 
2461         if (alg.startsWith("DES")) {
2462             return params.getParameterSpec(IvParameterSpec.class);
2463         }
2464         return null;
2465     }
2466 
2467     /**
2468      * Returns the maximum key length for the specified transformation
2469      * according to the installed JCE jurisdiction policy files. If
2470      * JCE unlimited strength jurisdiction policy files are installed,
2471      * Integer.MAX_VALUE will be returned.
2472      * For more information on default key size in JCE jurisdiction
2473      * policy files, please see Appendix E in the
2474      * <a href=
2475      *   "{@docRoot}openjdk-redirect.html?v=8&path=/technotes/guides/security/crypto/CryptoSpec.html#AppC">
2476      * Java Cryptography Architecture Reference Guide</a>.
2477      *
2478      * @param transformation the cipher transformation.
2479      * @return the maximum key length in bits or Integer.MAX_VALUE.
2480      * @exception NullPointerException if <code>transformation</code> is null.
2481      * @exception NoSuchAlgorithmException if <code>transformation</code>
2482      * is not a valid transformation, i.e. in the form of "algorithm" or
2483      * "algorithm/mode/padding".
2484      * @since 1.5
2485      */
getMaxAllowedKeyLength(String transformation)2486     public static final int getMaxAllowedKeyLength(String transformation)
2487             throws NoSuchAlgorithmException {
2488         // Android-changed: Remove references to CryptoPermission and throw early
2489         // if transformation == null or isn't valid.
2490         //
2491         // CryptoPermission cp = getConfiguredPermission(transformation);
2492         // return cp.getMaxAllowedKeyLength();
2493         if (transformation == null) {
2494             throw new NullPointerException("transformation == null");
2495         }
2496         // Throws NoSuchAlgorithmException if necessary.
2497         tokenizeTransformation(transformation);
2498         return Integer.MAX_VALUE;
2499     }
2500 
2501     /**
2502      * Returns an AlgorithmParameterSpec object which contains
2503      * the maximum cipher parameter value according to the
2504      * jurisdiction policy file. If JCE unlimited strength jurisdiction
2505      * policy files are installed or there is no maximum limit on the
2506      * parameters for the specified transformation in the policy file,
2507      * null will be returned.
2508      *
2509      * @param transformation the cipher transformation.
2510      * @return an AlgorithmParameterSpec which holds the maximum
2511      * value or null.
2512      * @exception NullPointerException if <code>transformation</code>
2513      * is null.
2514      * @exception NoSuchAlgorithmException if <code>transformation</code>
2515      * is not a valid transformation, i.e. in the form of "algorithm" or
2516      * "algorithm/mode/padding".
2517      * @since 1.5
2518      */
getMaxAllowedParameterSpec( String transformation)2519     public static final AlgorithmParameterSpec getMaxAllowedParameterSpec(
2520             String transformation) throws NoSuchAlgorithmException {
2521         // Android-changed: Remove references to CryptoPermission and throw early
2522         // if transformation == null or isn't valid.
2523         //
2524         // CryptoPermission cp = getConfiguredPermission(transformation);
2525         // return cp.getAlgorithmParameterSpec();
2526         if (transformation == null) {
2527             throw new NullPointerException("transformation == null");
2528         }
2529         // Throws NoSuchAlgorithmException if necessary.
2530         tokenizeTransformation(transformation);
2531         return null;
2532     }
2533 
2534     /**
2535      * Continues a multi-part update of the Additional Authentication
2536      * Data (AAD).
2537      * <p>
2538      * Calls to this method provide AAD to the cipher when operating in
2539      * modes such as AEAD (GCM/CCM).  If this cipher is operating in
2540      * either GCM or CCM mode, all AAD must be supplied before beginning
2541      * operations on the ciphertext (via the {@code update} and {@code
2542      * doFinal} methods).
2543      *
2544      * @param src the buffer containing the Additional Authentication Data
2545      *
2546      * @throws IllegalArgumentException if the {@code src}
2547      * byte array is null
2548      * @throws IllegalStateException if this cipher is in a wrong state
2549      * (e.g., has not been initialized), does not accept AAD, or if
2550      * operating in either GCM or CCM mode and one of the {@code update}
2551      * methods has already been called for the active
2552      * encryption/decryption operation
2553      * @throws UnsupportedOperationException if the corresponding method
2554      * in the {@code CipherSpi} has not been overridden by an
2555      * implementation
2556      *
2557      * @since 1.7
2558      */
updateAAD(byte[] src)2559     public final void updateAAD(byte[] src) {
2560         if (src == null) {
2561             throw new IllegalArgumentException("src buffer is null");
2562         }
2563 
2564         updateAAD(src, 0, src.length);
2565     }
2566 
2567     /**
2568      * Continues a multi-part update of the Additional Authentication
2569      * Data (AAD), using a subset of the provided buffer.
2570      * <p>
2571      * Calls to this method provide AAD to the cipher when operating in
2572      * modes such as AEAD (GCM/CCM).  If this cipher is operating in
2573      * either GCM or CCM mode, all AAD must be supplied before beginning
2574      * operations on the ciphertext (via the {@code update} and {@code
2575      * doFinal} methods).
2576      *
2577      * @param src the buffer containing the AAD
2578      * @param offset the offset in {@code src} where the AAD input starts
2579      * @param len the number of AAD bytes
2580      *
2581      * @throws IllegalArgumentException if the {@code src}
2582      * byte array is null, or the {@code offset} or {@code length}
2583      * is less than 0, or the sum of the {@code offset} and
2584      * {@code len} is greater than the length of the
2585      * {@code src} byte array
2586      * @throws IllegalStateException if this cipher is in a wrong state
2587      * (e.g., has not been initialized), does not accept AAD, or if
2588      * operating in either GCM or CCM mode and one of the {@code update}
2589      * methods has already been called for the active
2590      * encryption/decryption operation
2591      * @throws UnsupportedOperationException if the corresponding method
2592      * in the {@code CipherSpi} has not been overridden by an
2593      * implementation
2594      *
2595      * @since 1.7
2596      */
updateAAD(byte[] src, int offset, int len)2597     public final void updateAAD(byte[] src, int offset, int len) {
2598         checkCipherState();
2599 
2600         // Input sanity check
2601         if ((src == null) || (offset < 0) || (len < 0)
2602                 || ((len + offset) > src.length)) {
2603             throw new IllegalArgumentException("Bad arguments");
2604         }
2605 
2606         updateProviderIfNeeded();
2607         if (len == 0) {
2608             return;
2609         }
2610         spi.engineUpdateAAD(src, offset, len);
2611     }
2612 
2613     /**
2614      * Continues a multi-part update of the Additional Authentication
2615      * Data (AAD).
2616      * <p>
2617      * Calls to this method provide AAD to the cipher when operating in
2618      * modes such as AEAD (GCM/CCM).  If this cipher is operating in
2619      * either GCM or CCM mode, all AAD must be supplied before beginning
2620      * operations on the ciphertext (via the {@code update} and {@code
2621      * doFinal} methods).
2622      * <p>
2623      * All {@code src.remaining()} bytes starting at
2624      * {@code src.position()} are processed.
2625      * Upon return, the input buffer's position will be equal
2626      * to its limit; its limit will not have changed.
2627      *
2628      * @param src the buffer containing the AAD
2629      *
2630      * @throws IllegalArgumentException if the {@code src ByteBuffer}
2631      * is null
2632      * @throws IllegalStateException if this cipher is in a wrong state
2633      * (e.g., has not been initialized), does not accept AAD, or if
2634      * operating in either GCM or CCM mode and one of the {@code update}
2635      * methods has already been called for the active
2636      * encryption/decryption operation
2637      * @throws UnsupportedOperationException if the corresponding method
2638      * in the {@code CipherSpi} has not been overridden by an
2639      * implementation
2640      *
2641      * @since 1.7
2642      */
updateAAD(ByteBuffer src)2643     public final void updateAAD(ByteBuffer src) {
2644         checkCipherState();
2645 
2646         // Input sanity check
2647         if (src == null) {
2648             throw new IllegalArgumentException("src ByteBuffer is null");
2649         }
2650 
2651         updateProviderIfNeeded();
2652         if (src.remaining() == 0) {
2653             return;
2654         }
2655         spi.engineUpdateAAD(src);
2656     }
2657 
2658     /**
2659      * Returns the {@code CipherSpi} backing this {@code Cipher} or {@code null} if no
2660      * {@code CipherSpi} is backing this {@code Cipher}.
2661      *
2662      * @hide
2663      */
getCurrentSpi()2664     public CipherSpi getCurrentSpi() {
2665         return spi;
2666     }
2667 
2668     /** The attribute used for supported paddings. */
2669     private static final String ATTRIBUTE_PADDINGS = "SupportedPaddings";
2670 
2671     /** The attribute used for supported modes. */
2672     private static final String ATTRIBUTE_MODES = "SupportedModes";
2673 
2674     /**
2675      * If the attribute listed exists, check that it matches the regular
2676      * expression.
2677      */
matchAttribute(Provider.Service service, String attr, String value)2678     static boolean matchAttribute(Provider.Service service, String attr, String value) {
2679         if (value == null) {
2680             return true;
2681         }
2682         final String pattern = service.getAttribute(attr);
2683         if (pattern == null) {
2684             return true;
2685         }
2686         final String valueUc = value.toUpperCase(Locale.US);
2687         return valueUc.matches(pattern.toUpperCase(Locale.US));
2688     }
2689 
2690     /** Items that need to be set on the Cipher instance. */
2691     enum NeedToSet {
2692         NONE, MODE, PADDING, BOTH,
2693     }
2694 
2695     /**
2696      * Expresses the various types of transforms that may be used during
2697      * initialization.
2698      */
2699     static class Transform {
2700         private final String name;
2701         private final NeedToSet needToSet;
2702 
Transform(String name, NeedToSet needToSet)2703         public Transform(String name, NeedToSet needToSet) {
2704             this.name = name;
2705             this.needToSet = needToSet;
2706         }
2707     }
2708 
2709     /**
2710      * Keeps track of the possible arguments to {@code Cipher#init(...)}.
2711      */
2712     static class InitParams {
2713         final InitType initType;
2714         final int opmode;
2715         final Key key;
2716         final SecureRandom random;
2717         final AlgorithmParameterSpec spec;
2718         final AlgorithmParameters params;
2719 
InitParams(InitType initType, int opmode, Key key, SecureRandom random, AlgorithmParameterSpec spec, AlgorithmParameters params)2720         InitParams(InitType initType, int opmode, Key key, SecureRandom random,
2721                 AlgorithmParameterSpec spec, AlgorithmParameters params) {
2722             this.initType = initType;
2723             this.opmode = opmode;
2724             this.key = key;
2725             this.random = random;
2726             this.spec = spec;
2727             this.params = params;
2728         }
2729     }
2730 
2731     /**
2732      * Used to keep track of which underlying {@code CipherSpi#engineInit(...)}
2733      * variant to call when testing suitability.
2734      */
2735     static enum InitType {
2736         KEY, ALGORITHM_PARAMS, ALGORITHM_PARAM_SPEC,
2737     }
2738 
2739     class SpiAndProviderUpdater {
2740         /**
2741          * Lock held while the SPI is initializing.
2742          */
2743         private final Object initSpiLock = new Object();
2744 
2745         /**
2746          * The provider specified when instance created.
2747          */
2748         private final Provider specifiedProvider;
2749 
2750         /**
2751          * The SPI implementation.
2752          */
2753         private final CipherSpi specifiedSpi;
2754 
SpiAndProviderUpdater(Provider specifiedProvider, CipherSpi specifiedSpi)2755         SpiAndProviderUpdater(Provider specifiedProvider, CipherSpi specifiedSpi) {
2756             this.specifiedProvider = specifiedProvider;
2757             this.specifiedSpi = specifiedSpi;
2758         }
2759 
setCipherSpiImplAndProvider(CipherSpi cipherSpi, Provider provider)2760         void setCipherSpiImplAndProvider(CipherSpi cipherSpi, Provider provider) {
2761             Cipher.this.spi = cipherSpi;
2762             Cipher.this.provider = provider;
2763         }
2764 
2765         /**
2766          * Makes sure a CipherSpi that matches this type is selected. If
2767          * {@code key != null} then it assumes that a suitable provider exists for
2768          * this instance (used by {@link Cipher#init}. If the {@code initParams} is passed
2769          * in, then the {@code CipherSpi} returned will be initialized.
2770          *
2771          * @throws InvalidKeyException if the specified key cannot be used to
2772          *                             initialize this cipher.
2773          */
updateAndGetSpiAndProvider( InitParams initParams, CipherSpi spiImpl, Provider provider)2774         CipherSpiAndProvider updateAndGetSpiAndProvider(
2775                 InitParams initParams,
2776                 CipherSpi spiImpl,
2777                 Provider provider)
2778                 throws InvalidKeyException, InvalidAlgorithmParameterException {
2779             if (specifiedSpi != null) {
2780                 return new CipherSpiAndProvider(specifiedSpi, provider);
2781             }
2782             synchronized (initSpiLock) {
2783                 // This is not only a matter of performance. Many methods like update, doFinal, etc.
2784                 // call {@code #getSpi()} (ie, {@code #getSpi(null /* params */)}) and without this
2785                 // shortcut they would override an spi that was chosen using the key.
2786                 if (spiImpl != null && initParams == null) {
2787                     return new CipherSpiAndProvider(spiImpl, provider);
2788                 }
2789                 final CipherSpiAndProvider sap = tryCombinations(
2790                         initParams, specifiedProvider, tokenizedTransformation);
2791                 if (sap == null) {
2792                     throw new ProviderException("No provider found for "
2793                             + Arrays.toString(tokenizedTransformation));
2794                 }
2795                 setCipherSpiImplAndProvider(sap.cipherSpi, sap.provider);
2796                 return new CipherSpiAndProvider(sap.cipherSpi, sap.provider);
2797             }
2798         }
2799 
2800         /**
2801          * Convenience call when the Key is not available.
2802          */
updateAndGetSpiAndProvider(CipherSpi spiImpl, Provider provider)2803         CipherSpiAndProvider updateAndGetSpiAndProvider(CipherSpi spiImpl, Provider provider) {
2804             try {
2805                 return updateAndGetSpiAndProvider(null, spiImpl, provider);
2806             } catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
2807                 throw new ProviderException("Exception thrown when params == null", e);
2808            }
2809         }
2810 
getCurrentSpi(CipherSpi spiImpl)2811         CipherSpi getCurrentSpi(CipherSpi spiImpl) {
2812             if (specifiedSpi != null) {
2813                 return specifiedSpi;
2814             }
2815 
2816             synchronized (initSpiLock) {
2817                 return spiImpl;
2818             }
2819         }
2820     }
2821 
2822     /**
2823      * Tries to find the correct {@code Cipher} transform to use. Returns a
2824      * {@link org.apache.harmony.security.fortress.Engine.SpiAndProvider}, throws the first exception that was
2825      * encountered during attempted initialization, or {@code null} if there are
2826      * no providers that support the {@code initParams}.
2827      * <p>
2828      * {@code tokenizedTransformation} must be in the format returned by
2829      * {@link Cipher#checkTransformation(String)}. The combinations of mode strings
2830      * tried are as follows:
2831      * <ul>
2832      * <li><code>[cipher]/[mode]/[padding]</code>
2833      * <li><code>[cipher]/[mode]</code>
2834      * <li><code>[cipher]//[padding]</code>
2835      * <li><code>[cipher]</code>
2836      * </ul>
2837      * {@code services} is a list of cipher services. Needs to be non-null only if
2838      * {@code provider != null}
2839      */
tryCombinations(InitParams initParams, Provider provider, String[] tokenizedTransformation)2840     static CipherSpiAndProvider tryCombinations(InitParams initParams, Provider provider,
2841             String[] tokenizedTransformation)
2842             throws InvalidKeyException,
2843             InvalidAlgorithmParameterException {
2844         // Enumerate all the transforms we need to try
2845         ArrayList<Transform> transforms = new ArrayList<Transform>();
2846         if (tokenizedTransformation[1] != null && tokenizedTransformation[2] != null) {
2847             transforms.add(new Transform(tokenizedTransformation[0] + "/" + tokenizedTransformation[1] + "/"
2848                     + tokenizedTransformation[2], NeedToSet.NONE));
2849         }
2850         if (tokenizedTransformation[1] != null) {
2851             transforms.add(new Transform(tokenizedTransformation[0] + "/" + tokenizedTransformation[1],
2852                     NeedToSet.PADDING));
2853         }
2854         if (tokenizedTransformation[2] != null) {
2855             transforms.add(new Transform(tokenizedTransformation[0] + "//" + tokenizedTransformation[2],
2856                     NeedToSet.MODE));
2857         }
2858         transforms.add(new Transform(tokenizedTransformation[0], NeedToSet.BOTH));
2859 
2860         // Try each of the transforms and keep track of the first exception
2861         // encountered.
2862         Exception cause = null;
2863 
2864         if (provider != null) {
2865             for (Transform transform : transforms) {
2866                 Provider.Service service = provider.getService("Cipher", transform.name);
2867                 if (service == null) {
2868                     continue;
2869                 }
2870                 return tryTransformWithProvider(initParams, tokenizedTransformation, transform.needToSet,
2871                                 service);
2872             }
2873         } else {
2874             for (Provider prov : Security.getProviders()) {
2875                 for (Transform transform : transforms) {
2876                     Provider.Service service = prov.getService("Cipher", transform.name);
2877                     if (service == null) {
2878                         continue;
2879                     }
2880 
2881                     if (initParams == null || initParams.key == null
2882                             || service.supportsParameter(initParams.key)) {
2883                         try {
2884                             CipherSpiAndProvider sap = tryTransformWithProvider(initParams,
2885                                     tokenizedTransformation, transform.needToSet, service);
2886                             if (sap != null) {
2887                                 return sap;
2888                             }
2889                         } catch (Exception e) {
2890                             if (cause == null) {
2891                                 cause = e;
2892                             }
2893                         }
2894                     }
2895                 }
2896             }
2897         }
2898         if (cause instanceof InvalidKeyException) {
2899             throw (InvalidKeyException) cause;
2900         } else if (cause instanceof InvalidAlgorithmParameterException) {
2901             throw (InvalidAlgorithmParameterException) cause;
2902         } else if (cause instanceof RuntimeException) {
2903             throw (RuntimeException) cause;
2904         } else if (cause != null) {
2905             throw new InvalidKeyException("No provider can be initialized with given key", cause);
2906         } else if (initParams == null || initParams.key == null) {
2907             return null;
2908         } else {
2909             // Since the key is not null, a suitable provider exists,
2910             // and it is an InvalidKeyException.
2911             throw new InvalidKeyException(
2912                     "No provider offers " + Arrays.toString(tokenizedTransformation) + " for "
2913                     + initParams.key.getAlgorithm() + " key of class "
2914                     + initParams.key.getClass().getName() + " and export format "
2915                     + initParams.key.getFormat());
2916         }
2917     }
2918 
2919     static class CipherSpiAndProvider {
2920         CipherSpi cipherSpi;
2921         Provider provider;
2922 
CipherSpiAndProvider(CipherSpi cipherSpi, Provider provider)2923         CipherSpiAndProvider(CipherSpi cipherSpi, Provider provider) {
2924             this.cipherSpi = cipherSpi;
2925             this.provider = provider;
2926         }
2927     }
2928 
2929     /**
2930      * Tries to initialize the {@code Cipher} from a given {@code service}. If
2931      * initialization is successful, the initialized {@code spi} is returned. If
2932      * the {@code service} cannot be initialized with the specified
2933      * {@code initParams}, then it's expected to throw
2934      * {@code InvalidKeyException} or {@code InvalidAlgorithmParameterException}
2935      * as a hint to the caller that it should continue searching for a
2936      * {@code Service} that will work.
2937      */
tryTransformWithProvider(InitParams initParams, String[] tokenizedTransformation, NeedToSet type, Provider.Service service)2938     static CipherSpiAndProvider tryTransformWithProvider(InitParams initParams,
2939             String[] tokenizedTransformation, NeedToSet type, Provider.Service service)
2940                 throws InvalidKeyException, InvalidAlgorithmParameterException  {
2941         try {
2942             /*
2943              * Check to see if the Cipher even supports the attributes before
2944              * trying to instantiate it.
2945              */
2946             if (!matchAttribute(service, ATTRIBUTE_MODES, tokenizedTransformation[1])
2947                     || !matchAttribute(service, ATTRIBUTE_PADDINGS, tokenizedTransformation[2])) {
2948                 return null;
2949             }
2950 
2951             CipherSpiAndProvider sap = new CipherSpiAndProvider(
2952                 (CipherSpi) service.newInstance(null), service.getProvider());
2953             if (sap.cipherSpi == null || sap.provider == null) {
2954                 return null;
2955             }
2956             CipherSpi spi = sap.cipherSpi;
2957             if (((type == NeedToSet.MODE) || (type == NeedToSet.BOTH))
2958                     && (tokenizedTransformation[1] != null)) {
2959                 spi.engineSetMode(tokenizedTransformation[1]);
2960             }
2961             if (((type == NeedToSet.PADDING) || (type == NeedToSet.BOTH))
2962                     && (tokenizedTransformation[2] != null)) {
2963                 spi.engineSetPadding(tokenizedTransformation[2]);
2964             }
2965 
2966             if (initParams != null) {
2967                 switch (initParams.initType) {
2968                     case ALGORITHM_PARAMS:
2969                         spi.engineInit(initParams.opmode, initParams.key, initParams.params,
2970                                 initParams.random);
2971                         break;
2972                     case ALGORITHM_PARAM_SPEC:
2973                         spi.engineInit(initParams.opmode, initParams.key, initParams.spec,
2974                                 initParams.random);
2975                         break;
2976                     case KEY:
2977                         spi.engineInit(initParams.opmode, initParams.key, initParams.random);
2978                         break;
2979                     default:
2980                         throw new AssertionError("This should never be reached");
2981                 }
2982             }
2983             return new CipherSpiAndProvider(spi, sap.provider);
2984         } catch (NoSuchAlgorithmException ignored) {
2985         } catch (NoSuchPaddingException ignored) {
2986         }
2987         return null;
2988     }
2989 }
2990