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