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