-
Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy pathCipher.java
2907 lines (2752 loc) · 120 KB
/
Cipher.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.crypto;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.regex.*;
import java.security.*;
import java.security.Provider.Service;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidParameterSpecException;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import javax.crypto.spec.*;
import java.nio.ByteBuffer;
import java.nio.ReadOnlyBufferException;
import sun.security.util.Debug;
import sun.security.jca.*;
import sun.security.util.KnownOIDs;
/**
* This class provides the functionality of a cryptographic cipher for
* encryption and decryption. It forms the core of the Java Cryptographic
* Extension (JCE) framework.
*
* <p>In order to create a {@code Cipher} object, the application calls the
* cipher's {@code getInstance} method, and passes the name of the
* requested <i>transformation</i> to it. Optionally, the name of a provider
* may be specified.
*
* <p>A <i>transformation</i> is a string that describes the operation (or
* set of operations) to be performed on the given input, to produce some
* output. A transformation always includes the name of a cryptographic
* algorithm (e.g., <i>AES</i>), and may be followed by a feedback mode and
* padding scheme.
*
* <p> A transformation is of the form:
*
* <ul>
* <li>"<i>algorithm/mode/padding</i>" or
*
* <li>"<i>algorithm</i>"
* </ul>
*
* <P> (in the latter case,
* provider-specific default values for the mode and padding scheme are used).
* For example, the following is a valid transformation:
*
* <pre>
* Cipher c = Cipher.getInstance("<i>AES/CBC/PKCS5Padding</i>");
* </pre>
*
* Using modes such as {@code CFB} and {@code OFB}, block
* ciphers can encrypt data in units smaller than the cipher's actual
* block size. When requesting such a mode, you may optionally specify
* the number of bits to be processed at a time by appending this number
* to the mode name as shown in the "{@code AES/CFB8/NoPadding}" and
* "{@code AES/OFB32/PKCS5Padding}" transformations. If no such
* number is specified, a provider-specific default is used.
* (See the
* {@extLink security_guide_jdk_providers JDK Providers Documentation}
* for the JDK Providers default values.)
* Thus, block ciphers can be turned into byte-oriented stream ciphers by
* using an 8 bit mode such as CFB8 or OFB8.
* <p>
* Modes such as Authenticated Encryption with Associated Data (AEAD)
* provide authenticity assurances for both confidential data and
* Additional Associated Data (AAD) that is not encrypted. (Please see
* <a href="http://www.ietf.org/rfc/rfc5116.txt"> RFC 5116 </a> for more
* information on AEAD and AAD algorithms such as GCM/CCM.) Both
* confidential and AAD data can be used when calculating the
* authentication tag (similar to a {@link Mac}). This tag is appended
* to the ciphertext during encryption, and is verified on decryption.
* <p>
* AEAD modes such as GCM/CCM perform all AAD authenticity calculations
* before starting the ciphertext authenticity calculations. To avoid
* implementations having to internally buffer ciphertext, all AAD data
* must be supplied to GCM/CCM implementations (via the {@code updateAAD}
* methods) <b>before</b> the ciphertext is processed (via
* the {@code update} and {@code doFinal} methods).
* <p>
* Note that GCM mode has a uniqueness requirement on IVs used in
* encryption with a given key. When IVs are repeated for GCM
* encryption, such usages are subject to forgery attacks. Thus, after
* each encryption operation using GCM mode, callers should re-initialize
* the {@code Cipher} objects with GCM parameters which have a different IV
* value.
* <pre>
* GCMParameterSpec s = ...;
* cipher.init(..., s);
*
* // If the GCM parameters were generated by the provider, it can
* // be retrieved by:
* // cipher.getParameters().getParameterSpec(GCMParameterSpec.class);
*
* cipher.updateAAD(...); // AAD
* cipher.update(...); // Multi-part update
* cipher.doFinal(...); // conclusion of operation
*
* // Use a different IV value for every encryption
* byte[] newIv = ...;
* s = new GCMParameterSpec(s.getTLen(), newIv);
* cipher.init(..., s);
* ...
*
* </pre>
* The ChaCha20 and ChaCha20-Poly1305 algorithms have a similar requirement
* for unique nonces with a given key. After each encryption or decryption
* operation, callers should re-initialize their ChaCha20 or ChaCha20-Poly1305
* ciphers with parameters that specify a different nonce value. Please
* see <a href="https://tools.ietf.org/html/rfc7539">RFC 7539</a> for more
* information on the ChaCha20 and ChaCha20-Poly1305 algorithms.
* <p>
* Every implementation of the Java platform is required to support
* the following standard {@code Cipher} object transformations with
* the keysizes in parentheses:
* <ul>
* <li>{@code AES/CBC/NoPadding} (128)</li>
* <li>{@code AES/CBC/PKCS5Padding} (128)</li>
* <li>{@code AES/ECB/NoPadding} (128)</li>
* <li>{@code AES/ECB/PKCS5Padding} (128)</li>
* <li>{@code AES/GCM/NoPadding} (128, 256)</li>
* <li>{@code ChaCha20-Poly1305}</li>
* <li>{@code DESede/CBC/NoPadding} (168)</li>
* <li>{@code DESede/CBC/PKCS5Padding} (168)</li>
* <li>{@code DESede/ECB/NoPadding} (168)</li>
* <li>{@code DESede/ECB/PKCS5Padding} (168)</li>
* <li>{@code RSA/ECB/PKCS1Padding} (1024, 2048)</li>
* <li>{@code RSA/ECB/OAEPWithSHA-1AndMGF1Padding} (1024, 2048)</li>
* <li>{@code RSA/ECB/OAEPWithSHA-256AndMGF1Padding} (1024, 2048)</li>
* </ul>
* These transformations are described in the
* <a href="{@docRoot}/../specs/security/standard-names.html#cipher-algorithms">
* Cipher section</a> of the
* Java Security Standard Algorithm Names Specification.
* Consult the release documentation for your implementation to see if any
* other transformations are supported.
*
* @spec https://www.rfc-editor.org/info/rfc5116
* RFC 5116: An Interface and Algorithms for Authenticated Encryption
* @spec https://www.rfc-editor.org/info/rfc7539
* RFC 7539: ChaCha20 and Poly1305 for IETF Protocols
* @spec security/standard-names.html Java Security Standard Algorithm Names
* @author Jan Luehe
* @see KeyGenerator
* @see SecretKey
* @since 1.4
*/
public class Cipher {
private static final Debug debug =
Debug.getInstance("jca", "Cipher");
private static final Debug pdebug =
Debug.getInstance("provider", "Provider");
private static final boolean skipDebug =
Debug.isOn("engine=") && !Debug.isOn("cipher");
/**
* Constant used to initialize cipher to encryption mode.
*/
public static final int ENCRYPT_MODE = 1;
/**
* Constant used to initialize cipher to decryption mode.
*/
public static final int DECRYPT_MODE = 2;
/**
* Constant used to initialize cipher to key-wrapping mode.
*/
public static final int WRAP_MODE = 3;
/**
* Constant used to initialize cipher to key-unwrapping mode.
*/
public static final int UNWRAP_MODE = 4;
/**
* Constant used to indicate the to-be-unwrapped key is a "public key".
*/
public static final int PUBLIC_KEY = 1;
/**
* Constant used to indicate the to-be-unwrapped key is a "private key".
*/
public static final int PRIVATE_KEY = 2;
/**
* Constant used to indicate the to-be-unwrapped key is a "secret key".
*/
public static final int SECRET_KEY = 3;
// The provider
private Provider provider;
// The provider implementation (delegate)
private CipherSpi spi;
// The transformation
private final String transformation;
// Crypto permission representing the maximum allowable cryptographic
// strength that this cipher can be used for. (The cryptographic
// strength is a function of the keysize and algorithm parameters encoded
// in the crypto permission.)
private CryptoPermission cryptoPerm;
// The exemption mechanism that needs to be enforced
private ExemptionMechanism exmech;
// Flag which indicates whether or not this cipher has been initialized
private boolean initialized = false;
// The operation mode - store the operation mode after the
// cipher has been initialized.
private int opmode = 0;
// next SPI to try in provider selection
// null once provider is selected
private CipherSpi firstSpi;
// next service to try in provider selection
// null once provider is selected
private Service firstService;
// remaining services to try in provider selection
// null once provider is selected
private Iterator<Service> serviceIterator;
// list of transform Strings to lookup in the provider
private List<Transform> transforms;
private final Object lock;
/**
* Creates a {@code Cipher} object.
*
* @param cipherSpi the delegate
* @param provider the provider
* @param transformation the transformation
* @throws NullPointerException if {@code provider} is {@code null}
* @throws IllegalArgumentException if the supplied arguments
* are deemed invalid for constructing the {@code Cipher} object
*/
protected Cipher(CipherSpi cipherSpi,
Provider provider,
String transformation) {
// See bug 4341369 & 4334690 for more info.
// If the caller is trusted, then okay.
// Otherwise throw an IllegalArgumentException.
if (!JceSecurityManager.INSTANCE.isCallerTrusted(
JceSecurityManager.WALKER.getCallerClass(), provider)) {
throw new IllegalArgumentException("Cannot construct cipher");
}
this.spi = cipherSpi;
this.provider = provider;
this.transformation = transformation;
this.cryptoPerm = CryptoAllPermission.INSTANCE;
this.lock = null;
}
/**
* Creates a {code Cipher} object. Called internally by {code NullCipher}.
*
* @param cipherSpi the delegate
* @param transformation the transformation
*/
Cipher(CipherSpi cipherSpi, String transformation) {
this.spi = cipherSpi;
this.transformation = transformation;
this.cryptoPerm = CryptoAllPermission.INSTANCE;
this.lock = null;
}
private Cipher(CipherSpi firstSpi, Service firstService,
Iterator<Service> serviceIterator, String transformation,
List<Transform> transforms) {
this.firstSpi = firstSpi;
this.firstService = firstService;
this.serviceIterator = serviceIterator;
this.transforms = transforms;
this.transformation = transformation;
this.lock = new Object();
}
private static final String SHA512TRUNCATED = "SHA512/2";
private static String[] tokenizeTransformation(String transformation)
throws NoSuchAlgorithmException {
if (transformation == null) {
throw new NoSuchAlgorithmException("No transformation given");
}
/*
* array containing the components of a cipher transformation:
*
* index 0: algorithm component (e.g., AES)
* index 1: feedback component (e.g., CFB)
* index 2: padding component (e.g., PKCS5Padding)
*/
String[] parts = { "", "", "" };
// check if the transformation contains algorithms with "/" in their
// name which can cause the parsing logic to go wrong
int sha512Idx = transformation.toUpperCase(Locale.ENGLISH)
.indexOf(SHA512TRUNCATED);
int startIdx = (sha512Idx == -1 ? 0 :
sha512Idx + SHA512TRUNCATED.length());
int endIdx = transformation.indexOf('/', startIdx);
if (endIdx == -1) {
// algorithm
parts[0] = transformation.trim();
} else {
// algorithm/mode/padding
parts[0] = transformation.substring(0, endIdx).trim();
startIdx = endIdx+1;
endIdx = transformation.indexOf('/', startIdx);
if (endIdx == -1) {
throw new NoSuchAlgorithmException("Invalid transformation"
+ " format:" + transformation);
}
parts[1] = transformation.substring(startIdx, endIdx).trim();
parts[2] = transformation.substring(endIdx+1).trim();
}
if (parts[0].isEmpty()) {
throw new NoSuchAlgorithmException("Invalid transformation: " +
"algorithm not specified-"
+ transformation);
}
return parts;
}
// Provider attribute name for supported chaining mode
private static final String ATTR_MODE = "SupportedModes";
// Provider attribute name for supported padding names
private static final String ATTR_PAD = "SupportedPaddings";
// constants indicating whether the provider supports
// a given mode or padding
private static final int S_NO = 0; // does not support
private static final int S_MAYBE = 1; // unable to determine
private static final int S_YES = 2; // does support
/**
* Nested class to deal with modes and paddings.
*/
private static class Transform {
// transform string to lookup in the provider
final String transform;
// the mode/padding suffix in upper case. for example, if the algorithm
// to lookup is "AES/CBC/PKCS5Padding" suffix is "/CBC/PKCS5PADDING"
// if lookup is "AES", suffix is the empty string
// needed because aliases prevent straight transform.equals()
final String suffix;
// value to pass to setMode() or null if no such call required
final String mode;
// value to pass to setPadding() or null if no such call required
final String pad;
Transform(String alg, String suffix, String mode, String pad) {
this.transform = alg + suffix;
this.suffix = suffix.toUpperCase(Locale.ENGLISH);
this.mode = mode;
this.pad = pad;
}
// set mode and padding for the given SPI
void setModePadding(CipherSpi spi) throws NoSuchAlgorithmException,
NoSuchPaddingException {
if (mode != null) {
spi.engineSetMode(mode);
}
if (pad != null) {
spi.engineSetPadding(pad);
}
}
// check whether the given services supports the mode and
// padding described by this Transform
int supportsModePadding(Service s) {
int smode = supportsMode(s);
if (smode == S_NO) {
return smode;
}
int spad = supportsPadding(s);
// our constants are defined so that Math.min() is a tri-valued AND
return Math.min(smode, spad);
}
// separate methods for mode and padding
// called directly by cipher only to throw the correct exception
int supportsMode(Service s) {
return supports(s, ATTR_MODE, mode);
}
int supportsPadding(Service s) {
return supports(s, ATTR_PAD, pad);
}
private static int supports(Service s, String attrName, String value) {
if (value == null) {
return S_YES;
}
String regexp = s.getAttribute(attrName);
if (regexp == null) {
return S_MAYBE;
}
return matches(regexp, value) ? S_YES : S_NO;
}
// ConcurrentMap<String,Pattern> for previously compiled patterns
private static final ConcurrentMap<String, Pattern> patternCache =
new ConcurrentHashMap<String, Pattern>();
private static boolean matches(String regexp, String str) {
Pattern pattern = patternCache.get(regexp);
if (pattern == null) {
pattern = Pattern.compile(regexp);
patternCache.putIfAbsent(regexp, pattern);
}
return pattern.matcher(str.toUpperCase(Locale.ENGLISH)).matches();
}
}
private static List<Transform> getTransforms(String transformation)
throws NoSuchAlgorithmException {
String[] parts = tokenizeTransformation(transformation);
String alg = parts[0];
String mode = parts[1];
String pad = parts[2];
if ((mode.length() == 0) && (pad.length() == 0)) {
// Algorithm only
Transform tr = new Transform(alg, "", null, null);
return Collections.singletonList(tr);
} else {
// Algorithm w/ at least mode or padding or both
List<Transform> list = new ArrayList<>(4);
list.add(new Transform(alg, "/" + mode + "/" + pad, null, null));
list.add(new Transform(alg, "/" + mode, null, pad));
list.add(new Transform(alg, "//" + pad, mode, null));
list.add(new Transform(alg, "", mode, pad));
return list;
}
}
// get the transform matching the specified service
private static Transform getTransform(Service s,
List<Transform> transforms) {
String alg = s.getAlgorithm().toUpperCase(Locale.ENGLISH);
for (Transform tr : transforms) {
if (alg.endsWith(tr.suffix)) {
return tr;
}
}
return null;
}
/**
* Returns a {@code Cipher} object that implements the specified
* transformation.
*
* <p> This method traverses the list of registered security providers,
* starting with the most preferred provider.
* A new {@code Cipher} object encapsulating the
* {@code CipherSpi} implementation from the first
* provider that supports the specified algorithm is returned.
*
* <p> Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @apiNote
* It is recommended to use a transformation that fully specifies the
* algorithm, mode, and padding. By not doing so, the provider will
* use a default for the mode and padding which may not meet the security
* requirements of your application.
*
* @implNote
* The JDK Reference Implementation additionally uses the
* {@code jdk.security.provider.preferred}
* {@link Security#getProperty(String) Security} property to determine
* the preferred provider order for the specified algorithm. This
* may be different than the order of providers returned by
* {@link Security#getProviders() Security.getProviders()}.
* See also the Cipher Transformations section of the {@extLink
* security_guide_jdk_providers JDK Providers} document for information
* on the transformation defaults used by JDK providers.
*
* @param transformation the name of the transformation, e.g.,
* <i>AES/CBC/PKCS5Padding</i>.
* See the Cipher section in the <a href=
* "{@docRoot}/../specs/security/standard-names.html#cipher-algorithms">
* Java Security Standard Algorithm Names Specification</a>
* for information about standard transformation names.
*
* @spec security/standard-names.html Java Security Standard Algorithm Names
* @return a {@code Cipher} object that implements the requested
* transformation
*
* @throws NoSuchAlgorithmException if {@code transformation}
* is {@code null}, empty, in an invalid format,
* or if no provider supports a {@code CipherSpi}
* implementation for the specified algorithm
*
* @throws NoSuchPaddingException if {@code transformation}
* contains a padding scheme that is not available
*
* @see java.security.Provider
*/
public static final Cipher getInstance(String transformation)
throws NoSuchAlgorithmException, NoSuchPaddingException
{
if ((transformation == null) || transformation.isEmpty()) {
throw new NoSuchAlgorithmException("Null or empty transformation");
}
List<Transform> transforms = getTransforms(transformation);
List<ServiceId> cipherServices = new ArrayList<>(transforms.size());
for (Transform transform : transforms) {
cipherServices.add(new ServiceId("Cipher", transform.transform));
}
// make sure there is at least one service from a signed provider
// and that it can use the specified mode and padding
Iterator<Service> t = GetInstance.getServices(cipherServices);
Exception failure = null;
while (t.hasNext()) {
Service s = t.next();
if (JceSecurity.canUseProvider(s.getProvider()) == false) {
continue;
}
Transform tr = getTransform(s, transforms);
if (tr == null) {
// should never happen
continue;
}
int canuse = tr.supportsModePadding(s);
if (canuse == S_NO) {
// does not support mode or padding we need, ignore
continue;
}
// S_YES, S_MAYBE
// even when mode and padding are both supported, they
// may not be used together, try out and see if it works
try {
CipherSpi spi = (CipherSpi)s.newInstance(null);
tr.setModePadding(spi);
// specify null instead of spi for delayed provider selection
return new Cipher(null, s, t, transformation, transforms);
} catch (Exception e) {
failure = e;
}
}
throw new NoSuchAlgorithmException
("Cannot find any provider supporting " + transformation, failure);
}
/**
* Returns a {@code Cipher} object that implements the specified
* transformation.
*
* <p> A new {@code Cipher} object encapsulating the
* {@code CipherSpi} implementation from the specified provider
* is returned. The specified provider must be registered
* in the security provider list.
*
* <p> Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @apiNote
* It is recommended to use a transformation that fully specifies the
* algorithm, mode, and padding. By not doing so, the provider will
* use a default for the mode and padding which may not meet the security
* requirements of your application.
*
* @implNote
* See the Cipher Transformations section of the {@extLink
* security_guide_jdk_providers JDK Providers} document for information
* on the transformation defaults used by JDK providers.
*
* @param transformation the name of the transformation,
* e.g., <i>AES/CBC/PKCS5Padding</i>.
* See the Cipher section in the <a href=
* "{@docRoot}/../specs/security/standard-names.html#cipher-algorithms">
* Java Security Standard Algorithm Names Specification</a>
* for information about standard transformation names.
*
* @param provider the name of the provider
*
* @spec security/standard-names.html Java Security Standard Algorithm Names
* @return a {@code Cipher} object that implements the requested
* transformation
*
* @throws IllegalArgumentException if the {@code provider}
* is {@code null} or empty
*
* @throws NoSuchAlgorithmException if {@code transformation}
* is {@code null}, empty, in an invalid format,
* or if a {@code CipherSpi} implementation for the
* specified algorithm is not available from the specified
* provider
*
* @throws NoSuchPaddingException if {@code transformation}
* contains a padding scheme that is not available
*
* @throws NoSuchProviderException if the specified provider is not
* registered in the security provider list
*
* @see java.security.Provider
*/
public static final Cipher getInstance(String transformation,
String provider)
throws NoSuchAlgorithmException, NoSuchProviderException,
NoSuchPaddingException
{
if ((transformation == null) || transformation.isEmpty()) {
throw new NoSuchAlgorithmException("Null or empty transformation");
}
if ((provider == null) || (provider.isEmpty())) {
throw new IllegalArgumentException("Missing provider");
}
Provider p = Security.getProvider(provider);
if (p == null) {
throw new NoSuchProviderException("No such provider: " +
provider);
}
return getInstance(transformation, p);
}
private String getProviderName() {
return (provider == null) ? "(no provider)" : provider.getName();
}
/**
* Returns a {@code Cipher} object that implements the specified
* transformation.
*
* <p> A new {@code Cipher} object encapsulating the
* {@code CipherSpi} implementation from the specified {@code provider}
* object is returned. Note that the specified {@code provider} object
* does not have to be registered in the provider list.
*
* @apiNote
* It is recommended to use a transformation that fully specifies the
* algorithm, mode, and padding. By not doing so, the provider will
* use a default for the mode and padding which may not meet the security
* requirements of your application.
*
* @implNote
* See the Cipher Transformations section of the {@extLink
* security_guide_jdk_providers JDK Providers} document for information
* on the transformation defaults used by JDK providers.
*
* @param transformation the name of the transformation,
* e.g., <i>AES/CBC/PKCS5Padding</i>.
* See the Cipher section in the <a href=
* "{@docRoot}/../specs/security/standard-names.html#cipher-algorithms">
* Java Security Standard Algorithm Names Specification</a>
* for information about standard transformation names.
*
* @param provider the provider
*
* @spec security/standard-names.html Java Security Standard Algorithm Names
* @return a {@code Cipher} object that implements the requested
* transformation
*
* @throws IllegalArgumentException if the {@code provider}
* is {@code null}
*
* @throws NoSuchAlgorithmException if {@code transformation}
* is {@code null}, empty, in an invalid format,
* or if a {@code CipherSpi} implementation for the
* specified algorithm is not available from the specified
* {@code provider} object
*
* @throws NoSuchPaddingException if {@code transformation}
* contains a padding scheme that is not available
*
* @see java.security.Provider
*/
public static final Cipher getInstance(String transformation,
Provider provider)
throws NoSuchAlgorithmException, NoSuchPaddingException
{
if ((transformation == null) || transformation.isEmpty()) {
throw new NoSuchAlgorithmException("Null or empty transformation");
}
if (provider == null) {
throw new IllegalArgumentException("Missing provider");
}
Exception failure = null;
List<Transform> transforms = getTransforms(transformation);
boolean providerChecked = false;
String paddingError = null;
for (Transform tr : transforms) {
Service s = provider.getService("Cipher", tr.transform);
if (s == null) {
continue;
}
if (providerChecked == false) {
// for compatibility, first do the lookup and then verify
// the provider. this makes the difference between a NSAE
// and a SecurityException if the
// provider does not support the algorithm.
Exception ve = JceSecurity.getVerificationResult(provider);
if (ve != null) {
String msg = "JCE cannot authenticate the provider "
+ provider.getName();
throw new SecurityException(msg, ve);
}
providerChecked = true;
}
if (tr.supportsMode(s) == S_NO) {
continue;
}
if (tr.supportsPadding(s) == S_NO) {
paddingError = tr.pad;
continue;
}
try {
CipherSpi spi = (CipherSpi)s.newInstance(null);
tr.setModePadding(spi);
Cipher cipher = new Cipher(spi, transformation);
cipher.provider = s.getProvider();
cipher.initCryptoPermission();
return cipher;
} catch (Exception e) {
failure = e;
}
}
// throw NoSuchPaddingException if the problem is with padding
if (failure instanceof NoSuchPaddingException) {
throw (NoSuchPaddingException)failure;
}
if (paddingError != null) {
throw new NoSuchPaddingException
("Padding not supported: " + paddingError);
}
throw new NoSuchAlgorithmException
("No such algorithm: " + transformation, failure);
}
// If the requested crypto service is export-controlled,
// determine the maximum allowable keysize.
private void initCryptoPermission() throws NoSuchAlgorithmException {
if (JceSecurity.isRestricted() == false) {
cryptoPerm = CryptoAllPermission.INSTANCE;
exmech = null;
return;
}
cryptoPerm = getConfiguredPermission(transformation);
// Instantiate the exemption mechanism (if required)
String exmechName = cryptoPerm.getExemptionMechanism();
if (exmechName != null) {
exmech = ExemptionMechanism.getInstance(exmechName);
}
}
// max number of debug warnings to print from chooseFirstProvider()
private static int warnCount = 10;
/**
* Choose the Spi from the first provider available. Used if
* delayed provider selection is not possible because init()
* is not the first method called.
*/
void chooseFirstProvider() {
if (spi != null) {
return;
}
synchronized (lock) {
if (spi != null) {
return;
}
if (debug != null) {
int w = --warnCount;
if (w >= 0) {
debug.println("Cipher.init() not first method "
+ "called, disabling delayed provider selection");
if (w == 0) {
debug.println("Further warnings of this type will "
+ "be suppressed");
}
new Exception("Call trace").printStackTrace();
}
}
Exception lastException = null;
while ((firstService != null) || serviceIterator.hasNext()) {
Service s;
CipherSpi thisSpi;
if (firstService != null) {
s = firstService;
thisSpi = firstSpi;
firstService = null;
firstSpi = null;
} else {
s = serviceIterator.next();
thisSpi = null;
}
if (JceSecurity.canUseProvider(s.getProvider()) == false) {
continue;
}
Transform tr = getTransform(s, transforms);
if (tr == null) {
// should never happen
continue;
}
if (tr.supportsModePadding(s) == S_NO) {
continue;
}
try {
if (thisSpi == null) {
Object obj = s.newInstance(null);
if (obj instanceof CipherSpi == false) {
continue;
}
thisSpi = (CipherSpi)obj;
}
tr.setModePadding(thisSpi);
initCryptoPermission();
spi = thisSpi;
provider = s.getProvider();
// not needed any more
firstService = null;
serviceIterator = null;
transforms = null;
return;
} catch (Exception e) {
lastException = e;
}
}
ProviderException e = new ProviderException
("Could not construct CipherSpi instance");
if (lastException != null) {
e.initCause(lastException);
}
throw e;
}
}
private static final int I_KEY = 1;
private static final int I_PARAMSPEC = 2;
private static final int I_PARAMS = 3;
private static final int I_CERT = 4;
private void implInit(CipherSpi thisSpi, int type, int opmode, Key key,
AlgorithmParameterSpec paramSpec, AlgorithmParameters params,
SecureRandom random) throws InvalidKeyException,
InvalidAlgorithmParameterException {
switch (type) {
case I_KEY:
checkCryptoPerm(thisSpi, key);
thisSpi.engineInit(opmode, key, random);
break;
case I_PARAMSPEC:
checkCryptoPerm(thisSpi, key, paramSpec);
thisSpi.engineInit(opmode, key, paramSpec, random);
break;
case I_PARAMS:
checkCryptoPerm(thisSpi, key, params);
thisSpi.engineInit(opmode, key, params, random);
break;
case I_CERT:
checkCryptoPerm(thisSpi, key);
thisSpi.engineInit(opmode, key, random);
break;
default:
throw new AssertionError("Internal Cipher error: " + type);
}
}
private void chooseProvider(int initType, int opmode, Key key,
AlgorithmParameterSpec paramSpec,
AlgorithmParameters params, SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException {
synchronized (lock) {
if (spi != null) {
implInit(spi, initType, opmode, key, paramSpec, params, random);
return;
}
Exception lastException = null;
while ((firstService != null) || serviceIterator.hasNext()) {
Service s;
CipherSpi thisSpi;
if (firstService != null) {
s = firstService;
thisSpi = firstSpi;
firstService = null;
firstSpi = null;
} else {
s = serviceIterator.next();
thisSpi = null;
}
// if provider says it does not support this key, ignore it
if (s.supportsParameter(key) == false) {
continue;
}
if (JceSecurity.canUseProvider(s.getProvider()) == false) {
continue;
}
Transform tr = getTransform(s, transforms);
if (tr == null) {
// should never happen
continue;
}
if (tr.supportsModePadding(s) == S_NO) {
continue;
}
try {
if (thisSpi == null) {
thisSpi = (CipherSpi)s.newInstance(null);
}
tr.setModePadding(thisSpi);
initCryptoPermission();
implInit(thisSpi, initType, opmode, key, paramSpec,
params, random);
provider = s.getProvider();
this.spi = thisSpi;
firstService = null;
serviceIterator = null;
transforms = null;
return;
} catch (Exception e) {
// NoSuchAlgorithmException from newInstance()
// InvalidKeyException from init()
// RuntimeException (ProviderException) from init()
// SecurityException from crypto permission check
if (lastException == null) {
lastException = e;
}
}
}
// no working provider found, fail
if (lastException instanceof InvalidKeyException) {
throw (InvalidKeyException)lastException;
}
if (lastException instanceof InvalidAlgorithmParameterException) {
throw (InvalidAlgorithmParameterException)lastException;
}
if (lastException instanceof RuntimeException) {
throw (RuntimeException)lastException;
}
String kName = (key != null) ? key.getClass().getName() : "(null)";
throw new InvalidKeyException
("No installed provider supports this key: "
+ kName, lastException);
}
}
/**
* Returns the provider of this {@code Cipher} object.
*
* @return the provider of this {@code Cipher} object
*/
public final Provider getProvider() {
chooseFirstProvider();
return this.provider;
}
/**
* Returns the algorithm name of this {@code Cipher} object.
*
* <p>This is the same name that was specified in one of the
* {@code getInstance} calls that created this {@code Cipher}
* object.
*
* @return the algorithm name of this {@code Cipher} object
*/
public final String getAlgorithm() {
return this.transformation;
}
/**