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