1 /*
   2  * Copyright (c) 1997, 2019, 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 
  26 package javax.crypto;
  27 
  28 import java.util.*;
  29 import java.util.concurrent.ConcurrentHashMap;
  30 import java.util.concurrent.ConcurrentMap;
  31 import java.util.regex.*;
  32 
  33 
  34 import java.security.*;
  35 import java.security.Provider.Service;
  36 import java.security.spec.AlgorithmParameterSpec;
  37 import java.security.spec.InvalidParameterSpecException;
  38 import java.security.cert.Certificate;
  39 import java.security.cert.X509Certificate;
  40 
  41 import javax.crypto.spec.*;
  42 
  43 import java.nio.ByteBuffer;
  44 import java.nio.ReadOnlyBufferException;
  45 
  46 import sun.security.util.Debug;
  47 import 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>AES</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>AES/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 AES/CFB8/NoPadding}" and
  86  * "{@code AES/OFB32/PKCS5Padding}" transformations. If no such
  87  * number is specified, a provider-specific default is used.
  88  * (See the
  89  * {@extLink security_guide_jdk_providers JDK Providers Documentation}
  90  * for the JDK Providers default values.)
  91  * Thus, block ciphers can be turned into byte-oriented stream ciphers by
  92  * using an 8 bit mode such as CFB8 or OFB8.
  93  * <p>
  94  * Modes such as Authenticated Encryption with Associated Data (AEAD)
  95  * provide authenticity assurances for both confidential data and
  96  * Additional Associated Data (AAD) that is not encrypted.  (Please see
  97  * <a href="http://www.ietf.org/rfc/rfc5116.txt"> RFC 5116 </a> for more
  98  * information on AEAD and AAD algorithms such as GCM/CCM.) Both
  99  * confidential and AAD data can be used when calculating the
 100  * authentication tag (similar to a {@link Mac}).  This tag is appended
 101  * to the ciphertext during encryption, and is verified on decryption.
 102  * <p>
 103  * AEAD modes such as GCM/CCM perform all AAD authenticity calculations
 104  * before starting the ciphertext authenticity calculations.  To avoid
 105  * implementations having to internally buffer ciphertext, all AAD data
 106  * must be supplied to GCM/CCM implementations (via the {@code updateAAD}
 107  * methods) <b>before</b> the ciphertext is processed (via
 108  * the {@code update} and {@code doFinal} methods).
 109  * <p>
 110  * Note that GCM mode has a uniqueness requirement on IVs used in
 111  * encryption with a given key. When IVs are repeated for GCM
 112  * encryption, such usages are subject to forgery attacks. Thus, after
 113  * each encryption operation using GCM mode, callers should re-initialize
 114  * the cipher objects with GCM parameters which have a different IV value.
 115  * <pre>
 116  *     GCMParameterSpec s = ...;
 117  *     cipher.init(..., s);
 118  *
 119  *     // If the GCM parameters were generated by the provider, it can
 120  *     // be retrieved by:
 121  *     // cipher.getParameters().getParameterSpec(GCMParameterSpec.class);
 122  *
 123  *     cipher.updateAAD(...);  // AAD
 124  *     cipher.update(...);     // Multi-part update
 125  *     cipher.doFinal(...);    // conclusion of operation
 126  *
 127  *     // Use a different IV value for every encryption
 128  *     byte[] newIv = ...;
 129  *     s = new GCMParameterSpec(s.getTLen(), newIv);
 130  *     cipher.init(..., s);
 131  *     ...
 132  *
 133  * </pre>
 134  * The ChaCha20 and ChaCha20-Poly1305 algorithms have a similar requirement
 135  * for unique nonces with a given key.  After each encryption or decryption
 136  * operation, callers should re-initialize their ChaCha20 or ChaCha20-Poly1305
 137  * ciphers with parameters that specify a different nonce value.  Please
 138  * see <a href="https://tools.ietf.org/html/rfc7539">RFC 7539</a> for more
 139  * information on the ChaCha20 and ChaCha20-Poly1305 algorithms.
 140  * <p>
 141  * Every implementation of the Java platform is required to support
 142  * the following standard {@code Cipher} transformations with the keysizes
 143  * in parentheses:
 144  * <ul>
 145  * <li>{@code AES/CBC/NoPadding} (128)</li>
 146  * <li>{@code AES/CBC/PKCS5Padding} (128)</li>
 147  * <li>{@code AES/ECB/NoPadding} (128)</li>
 148  * <li>{@code AES/ECB/PKCS5Padding} (128)</li>
 149  * <li>{@code AES/GCM/NoPadding} (128)</li>




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