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