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