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