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