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