-
Notifications
You must be signed in to change notification settings - Fork 364
/
SslContextUtil.java
1824 lines (1719 loc) · 62.6 KB
/
SslContextUtil.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) 2016 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v20.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.html.
*
* Contributors:
* Bosch Software Innovations GmbH - initial implementation.
* Achim Kraus (Bosch Software Innovations GmbH) - introduce configurable
* key store type and
* InputStreamFactory.
* Achim Kraus (Bosch Software Innovations GmbH) - use file system, if
* no scheme is provided in URI
* Achim Kraus (Bosch Software Innovations GmbH) - add SSLContext protocol to
* selective disable TLSv1.3 for
* TLSv1.2 dependent unit tests.
******************************************************************************/
package org.eclipse.californium.elements.util;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.Principal;
import java.security.KeyStore.Entry;
import java.security.KeyStore.PrivateKeyEntry;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.cert.CertPath;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateFactory;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509ExtendedKeyManager;
import javax.net.ssl.X509ExtendedTrustManager;
import javax.net.ssl.X509KeyManager;
import javax.net.ssl.X509TrustManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Utility functions for {@link javax.net.ssl.SSLContext}.
*
* This utility converts between the informations used by the javax SSL
* implementation and the plain credentials used by scandium. It offers reading
* KeyStores, extracting credentials, and creating KeyManager and TrustManager
* from the KeyStores or extracted credentials. Java SSLContext is able to
* maintain different key-certificate pairs for different key and signing
* algorithms. The californium-scandium concentrates on embedded client and
* therefore supports only one key-signing algorithm. This utility therefore
* helps, to select the right credentials or create a javax security classes for
* javax SSL implementation from that selected credentials.
*
* The utility provides a configurable mapping of URI endings with key store
* type, enable to use different KeyStore implementations and formats. The URI
* ending is defined as the part starting with the last "." after all "/"
* separator. e.g.: "cert/keyStore.p12" has ending ".p12", and
* "cert/keyStore.p12/test" has no ending. The currently pre-configured mapping
* contains:
*
* <pre>
* ".jks" to "JKS"
* ".bks" to "BKS"
* ".p12" to "PKCS12"
* ".pem" to "CRT/PEM" (custom reader)
* ".crt" to "CRT/PEM" (custom reader)
* "*" to system default
* </pre>
*
* CRT/PEM Custom Reader: Read private keys (PKCS8 and PKCS12 (EC only)), public
* key (x509), and certificates (x509). These credentials are stored in the PEM
* format, which is base64 encoded. The sections of the file contains a
* description of the encoded credential. If a general load function is used,
* {@link Credentials} are returned with the loaded data filled in.
*
* Example:
*
* <pre>
* -----BEGIN EC PRIVATE KEY-----
* MHcCAQEEIBw7lyMR21FDpCecT0bNr4oKBuYw1VdNnCB5xSS4dQrcoAoGCCqGSM49
* AwEHoUQDQgAETY8Y02TZuaRUQvXnguxg6EPN7wR5vzxthmDk+6vvf6oJgBylWIU2
* E3khCBkZM9Um7JCA9/kcbNezwJDzyQAnIw==
* -----END EC PRIVATE KEY-----
* </pre>
*
* You may use
* <a href="https://lapo.it/asn1js" target="_blank">lapo.it/asn1js</a> to decode
* the content. Please ensure, that you only provide test- or demo-credentials.
*
* If that example file is loaded with {@link #loadCredentials(String)} the
* returned {@link Credentials} contains a private key, and here, also the
* corresponding public key.
*
* The utility provides also a configurable input stream factory of URI schemes.
* Currently only {@link #CLASSPATH_SCHEME} is pre-configured to load key stores
* from the classpath. If the scheme of the URI has no configured input stream
* factory, the URI is loaded with {@link URL#URL(String)}.
*
* Note: It is not intended, that the configuration is changed during usage,
* this may cause race conditions! Currently this class provides a class level
* access based API. Therefore only one configuration at all is possible.
* Depending on the usage, this may change to instance level access based API to
* support more parallel configurations to be used.
*
* @see #configure(String, KeyStoreType)
* @see #configure(String, InputStreamFactory)
*/
public class SslContextUtil {
/**
* The logger.
*
* @deprecated scope will change to private.
*/
@Deprecated
public static final Logger LOGGER = LoggerFactory.getLogger(SslContextUtil.class);
/**
* Scheme for key store URI. Used to load the key stores from classpath.
*/
public static final String CLASSPATH_SCHEME = "classpath://";
/**
* Separator for parameters.
*
* @see #loadTrustedCertificates(String)
* @see #loadCredentials(String)
*/
public static final String PARAMETER_SEPARATOR = "#";
/**
* Ending for key stores with type {@link #JKS_TYPE}.
*/
public static final String JKS_ENDING = ".jks";
/**
* Ending for key stores with type {@link #BKS_TYPE}.
*/
public static final String BKS_ENDING = ".bks";
/**
* Ending for key stores with type {@link #PKCS12_TYPE}.
*/
public static final String PKCS12_ENDING = ".p12";
/**
* Ending for CRT/PEM key stores.
*
* @see SimpleKeyStore
* @see #CRT_ENDING
*/
public static final String PEM_ENDING = ".pem";
/**
* Ending for CRT/PEM key stores.
*
* @see SimpleKeyStore
* @see #PEM_ENDING
*/
public static final String CRT_ENDING = ".crt";
/**
* Label to provide default key store type.
*/
public static final String DEFAULT_ENDING = "*";
/**
* Key store type JKS.
*/
public static final String JKS_TYPE = "JKS";
/**
* Key store type BKS.
*/
public static final String BKS_TYPE = "BKS";
/**
* Key store type PKCS12.
*/
public static final String PKCS12_TYPE = "PKCS12";
/**
* Default protocol used for
* {@link #createSSLContext(String, PrivateKey, X509Certificate[], Certificate[])}.
*/
public static final String DEFAULT_SSL_PROTOCOL = "TLSv1.2";
/**
* Schema delimiter.
*/
private static final String SCHEME_DELIMITER = "://";
/**
* Default alias.
*/
private static final String DEFAULT_ALIAS = "californium";
/**
* Map URI endings to key store types.
*
* @see #configure(String, KeyStoreType)
* @see #getKeyStoreTypeFromUri(String)
*/
private static final Map<String, KeyStoreType> KEY_STORE_TYPES = new ConcurrentHashMap<>();
/**
* Map URI scheme to input stream factories.
*
* @see #configure(String, InputStreamFactory)
* @see #getInputStreamFromUri(String)
*/
private static final Map<String, InputStreamFactory> INPUT_STREAM_FACTORIES = new ConcurrentHashMap<>();
/**
* Anonymous key manager.
*
* @since 2.4
*/
private static final KeyManager ANONYMOUS = new AnonymousX509ExtendedKeyManager();
/**
* TrustManager to trust all.
*
* @since 2.4
*/
private static final TrustManager TRUST_ALL;
static {
JceProviderUtil.init();
configureDefaults();
TrustManager trustAll;
try {
trustAll = new X509ExtendedTrustAllManager();
} catch (NoClassDefFoundError ex) {
trustAll = new X509TrustAllManager();
}
TRUST_ALL = trustAll;
}
/**
* Load trusted certificates from key store.
*
* @param trust trust definition keystore#hexstorepwd#aliaspattern or
* keystore.pem. If no aliaspattern should be used, just leave it
* blank keystore#hexstorepwd#
* @return array with trusted certificates.
* @throws IOException if key store could not be loaded.
* @throws GeneralSecurityException if security setup failed.
* @throws IllegalArgumentException if trust doesn't match
* keystore#hexstorepwd#aliaspattern or no matching trusts are
* found
* @throws NullPointerException if trust is {@code null}.
* @see #PARAMETER_SEPARATOR
*/
public static Certificate[] loadTrustedCertificates(String trust) throws IOException, GeneralSecurityException {
if (null == trust) {
throw new NullPointerException("trust must be provided!");
}
String[] parameters = trust.split(PARAMETER_SEPARATOR, 3);
if (1 == parameters.length) {
KeyStoreType configuration = getKeyStoreTypeFromUri(parameters[0]);
if (configuration.simpleStore != null) {
return loadTrustedCertificates(parameters[0], null, null);
}
}
if (3 != parameters.length) {
throw new IllegalArgumentException("trust must comply the pattern <keystore" + PARAMETER_SEPARATOR
+ "hexstorepwd" + PARAMETER_SEPARATOR + "aliaspattern>");
}
return loadTrustedCertificates(parameters[0], parameters[2], StringUtil.hex2CharArray(parameters[1]));
}
/**
* Load credentials from key store.
*
* @param credentials credentials definition
* keystore#hexstorepwd#hexkeypwd#alias or keystore.pem
* @return credentials
* @throws IOException if key store could not be loaded.
* @throws GeneralSecurityException if security setup failed.
* @throws IllegalArgumentException if keys doesn't match
* keystore#hexstorepwd#hexkeypwd#alias or no matching trusts
* are found
* @throws IncompleteCredentialsException if either private key or
* certificate chain and public key is missing.
* @throws NullPointerException if credentials is {@code null}.
* @see #PARAMETER_SEPARATOR
* @since 3.0 IncompleteCredentialsException added
*/
public static Credentials loadCredentials(String credentials) throws IOException, GeneralSecurityException {
if (null == credentials) {
throw new NullPointerException("credentials must be provided!");
}
String[] parameters = credentials.split(PARAMETER_SEPARATOR, 4);
if (1 == parameters.length) {
KeyStoreType configuration = getKeyStoreTypeFromUri(parameters[0]);
if (configuration.simpleStore != null) {
return loadCredentials(parameters[0], null, null, null);
}
}
if (4 != parameters.length) {
throw new IllegalArgumentException("credentials must comply the pattern <keystore" + PARAMETER_SEPARATOR
+ "hexstorepwd" + PARAMETER_SEPARATOR + "hexkeypwd" + PARAMETER_SEPARATOR + "alias>");
}
return loadCredentials(parameters[0], parameters[3], StringUtil.hex2CharArray(parameters[1]),
StringUtil.hex2CharArray(parameters[2]));
}
/**
* Load TrustManager from key store.
*
* @param keyStoreUri key store URI. Supports configurable URI scheme based
* input streams and URI ending based key store type.
* @param aliasPattern regular expression for aliases to load only specific
* certificates for the TrustManager. null to load all
* certificates.
* @param storePassword password for key store.
* @return array with TrustManager
* @throws IOException if key store could not be loaded.
* @throws GeneralSecurityException if security setup failed.
* @throws IllegalArgumentException if no matching trusts are found
* @throws NullPointerException if keyStoreUri or storePassword is
* {@code null}.
*/
public static TrustManager[] loadTrustManager(String keyStoreUri, String aliasPattern, char[] storePassword)
throws IOException, GeneralSecurityException {
Certificate[] trustedCertificates = loadTrustedCertificates(keyStoreUri, aliasPattern, storePassword);
return createTrustManager("trusts", trustedCertificates);
}
/**
* Load KeyManager from key store.
*
* @param keyStoreUri key store URI. Supports configurable URI scheme based
* input streams and URI ending based key store type.
* @param aliasPattern alias pattern to load only specific credentials into
* the KeyManager. null to load all credentials into the
* KeyManager.
* @param storePassword password for key store.
* @param keyPassword password for private key.
* @return array with KeyManager
* @throws IOException if key store could not be loaded.
* @throws GeneralSecurityException if security setup failed.
* @throws IllegalArgumentException if no matching credentials are found
* @throws NullPointerException if keyStoreUri, storePassword, or
* keyPassword is {@code null}.
* @since 3.0 (add support for alias pattern)
*/
public static KeyManager[] loadKeyManager(String keyStoreUri, String aliasPattern, char[] storePassword,
char[] keyPassword) throws IOException, GeneralSecurityException {
KeyStoreType configuration = getKeyStoreTypeFromUri(keyStoreUri);
KeyStore ks;
if (configuration.simpleStore != null) {
Credentials credentials = loadSimpleKeyStore(keyStoreUri, configuration);
if (credentials.privateKey == null) {
throw new IllegalArgumentException("credentials missing! No private key found!");
}
if (credentials.chain == null) {
throw new IllegalArgumentException("credentials missing! No certificate chain found!");
}
return createKeyManager(DEFAULT_ALIAS, credentials.privateKey, credentials.chain);
} else {
if (null == keyPassword) {
throw new NullPointerException("keyPassword must be provided!");
}
ks = loadKeyStore(keyStoreUri, storePassword, configuration);
if (aliasPattern != null && !aliasPattern.isEmpty()) {
boolean found = false;
;
Pattern pattern = Pattern.compile(aliasPattern);
KeyStore ksAlias = KeyStore.getInstance(ks.getType());
ksAlias.load(null);
for (Enumeration<String> e = ks.aliases(); e.hasMoreElements();) {
String alias = e.nextElement();
Matcher matcher = pattern.matcher(alias);
if (!matcher.matches()) {
continue;
}
Entry entry = ks.getEntry(alias, new KeyStore.PasswordProtection(keyPassword));
if (null != entry) {
ksAlias.setEntry(alias, entry, new KeyStore.PasswordProtection(keyPassword));
found = true;
} else {
throw new GeneralSecurityException(
"key stores '" + keyStoreUri + "' doesn't contain credentials for '" + alias + "'");
}
}
if (!found) {
throw new GeneralSecurityException(
"no credentials found in '" + keyStoreUri + "' for '" + aliasPattern + "'!");
}
ks = ksAlias;
}
return createKeyManager(ks, keyPassword);
}
}
/**
* Load trusted certificates from key store.
*
* @param keyStoreUri key store URI. Supports configurable URI scheme based
* input streams and URI ending based key store type.
* @param aliasPattern regular expression for aliases to load only specific
* certificates for trusting. null to load all certificates.
* @param storePassword password for key store.
* @return array with trusted certificates.
* @throws IOException if key store could not be loaded.
* @throws GeneralSecurityException if security setup failed.
* @throws IllegalArgumentException if no matching certificates are found
* @throws NullPointerException if keyStoreUri or storePassword is
* {@code null}.
*/
public static Certificate[] loadTrustedCertificates(String keyStoreUri, String aliasPattern, char[] storePassword)
throws IOException, GeneralSecurityException {
KeyStoreType configuration = getKeyStoreTypeFromUri(keyStoreUri);
if (configuration.simpleStore != null) {
Credentials credentials = loadSimpleKeyStore(keyStoreUri, configuration);
if (credentials.trusts != null) {
return credentials.trusts;
} else if (credentials.chain != null) {
return credentials.chain;
}
throw new IllegalArgumentException("no trusted x509 certificates found in '" + keyStoreUri + "'!");
}
KeyStore ks = loadKeyStore(keyStoreUri, storePassword, configuration);
Pattern pattern = null;
if (null != aliasPattern && !aliasPattern.isEmpty()) {
pattern = Pattern.compile(aliasPattern);
}
List<Certificate> trustedCertificates = new ArrayList<Certificate>();
for (Enumeration<String> e = ks.aliases(); e.hasMoreElements();) {
String alias = e.nextElement();
if (null != pattern) {
Matcher matcher = pattern.matcher(alias);
if (!matcher.matches()) {
continue;
}
}
Certificate certificate = ks.getCertificate(alias);
if (!trustedCertificates.contains(certificate)) {
trustedCertificates.add(certificate);
}
}
if (trustedCertificates.isEmpty()) {
throw new IllegalArgumentException(
"no trusted x509 certificates found in '" + keyStoreUri + "' for '" + aliasPattern + "'!");
}
return trustedCertificates.toArray(new Certificate[trustedCertificates.size()]);
}
/**
* Load credentials from key store.
*
* @param keyStoreUri key store URI. Supports configurable URI scheme based
* input streams and URI ending based key store type.
* @param alias alias to load specific credentials.
* @param storePassword password for key store.
* @param keyPassword password for private key.
* @return credentials for the alias.
* @throws IOException if key store could not be loaded.
* @throws GeneralSecurityException if security setup failed.
* @throws IllegalArgumentException if alias is empty, or no matching
* credentials are found.
* @throws IncompleteCredentialsException if either private key or
* certificate chain and public key is missing.
* @throws NullPointerException if keyStoreUri, storePassword, keyPassword,
* or alias is {@code null}.
* @since 3.0 IncompleteCredentialsException added
*/
public static Credentials loadCredentials(String keyStoreUri, String alias, char[] storePassword,
char[] keyPassword) throws IOException, GeneralSecurityException {
KeyStoreType configuration = getKeyStoreTypeFromUri(keyStoreUri);
if (configuration.simpleStore != null) {
Credentials credentials = loadSimpleKeyStore(keyStoreUri, configuration);
if (credentials.publicKey == null && credentials.privateKey == null) {
throw new IllegalArgumentException("credentials missing! No keys found!");
} else if (credentials.privateKey == null) {
throw new IncompleteCredentialsException(credentials, "credentials missing! No private key found!");
} else if (credentials.publicKey == null) {
throw new IncompleteCredentialsException(credentials,
"credentials missing! Neither certificate chain nor public key found!");
}
return credentials;
}
if (null == alias) {
throw new NullPointerException("alias must be provided!");
}
if (alias.isEmpty()) {
throw new IllegalArgumentException("alias must not be empty!");
}
if (null == keyPassword) {
throw new NullPointerException("keyPassword must be provided!");
}
KeyStore ks = loadKeyStore(keyStoreUri, storePassword, configuration);
if (ks.entryInstanceOf(alias, PrivateKeyEntry.class)) {
Entry entry = ks.getEntry(alias, new KeyStore.PasswordProtection(keyPassword));
if (entry instanceof PrivateKeyEntry) {
PrivateKeyEntry pkEntry = (PrivateKeyEntry) entry;
Certificate[] chain = pkEntry.getCertificateChain();
X509Certificate[] x509Chain = asX509Certificates(chain);
return new Credentials(pkEntry.getPrivateKey(), null, x509Chain);
}
}
throw new IllegalArgumentException("no credentials found for '" + alias + "' in '" + keyStoreUri + "'!");
}
/**
* Load private key from key store.
*
* @param keyStoreUri key store URI. Supports configurable URI scheme based
* input streams and URI ending based key store type.
* @param alias alias to load specific credentials.
* @param storePassword password for key store.
* @param keyPassword password for private key.
* @return private key for the alias.
* @throws IOException if key store could not be loaded.
* @throws GeneralSecurityException if security setup failed.
* @throws IllegalArgumentException if alias is empty, or no matching
* credentials are found.
* @throws NullPointerException if keyStoreUri, storePassword, keyPassword,
* or alias is {@code null}.
*/
public static PrivateKey loadPrivateKey(String keyStoreUri, String alias, char[] storePassword, char[] keyPassword)
throws IOException, GeneralSecurityException {
KeyStoreType configuration = getKeyStoreTypeFromUri(keyStoreUri);
if (configuration.simpleStore != null) {
Credentials credentials = loadSimpleKeyStore(keyStoreUri, configuration);
if (credentials.privateKey != null) {
return credentials.privateKey;
}
} else {
if (null == alias) {
throw new NullPointerException("alias must be provided!");
}
if (alias.isEmpty()) {
throw new IllegalArgumentException("alias must not be empty!");
}
if (null == keyPassword) {
throw new NullPointerException("keyPassword must be provided!");
}
KeyStore ks = loadKeyStore(keyStoreUri, storePassword, configuration);
if (ks.entryInstanceOf(alias, PrivateKeyEntry.class)) {
Entry entry = ks.getEntry(alias, new KeyStore.PasswordProtection(keyPassword));
if (entry instanceof PrivateKeyEntry) {
PrivateKeyEntry pkEntry = (PrivateKeyEntry) entry;
return pkEntry.getPrivateKey();
}
}
}
throw new IllegalArgumentException("no private key found for '" + alias + "' in '" + keyStoreUri + "'!");
}
/**
* Load public key from key store.
*
* @param keyStoreUri key store URI. Supports configurable URI scheme based
* input streams and URI ending based key store type.
* @param alias alias to load specific credentials.
* @param storePassword password for key store.
* @return public key for the alias.
* @throws IOException if key store could not be loaded.
* @throws GeneralSecurityException if security setup failed.
* @throws IllegalArgumentException if alias is empty, or no matching
* credentials are found.
* @throws NullPointerException if keyStoreUri, storePassword, keyPassword,
* or alias is {@code null}.
*/
public static PublicKey loadPublicKey(String keyStoreUri, String alias, char[] storePassword)
throws IOException, GeneralSecurityException {
KeyStoreType configuration = getKeyStoreTypeFromUri(keyStoreUri);
if (configuration.simpleStore != null) {
Credentials credentials = loadSimpleKeyStore(keyStoreUri, configuration);
if (credentials.publicKey != null) {
return credentials.publicKey;
}
} else {
if (null == alias) {
throw new NullPointerException("alias must be provided!");
}
if (alias.isEmpty()) {
throw new IllegalArgumentException("alias must not be empty!");
}
KeyStore ks = loadKeyStore(keyStoreUri, storePassword, configuration);
Certificate[] chain = ks.getCertificateChain(alias);
return chain[0].getPublicKey();
}
throw new IllegalArgumentException("no public key found for '" + alias + "' in '" + keyStoreUri + "'!");
}
/**
* Load certificate chain from key store.
*
* @param keyStoreUri key store URI. Supports configurable URI scheme based
* input streams and URI ending based key store type.
* @param alias alias to load the certificate chain.
* @param storePassword password for key store.
* @return certificate chain for the alias.
* @throws IOException if key store could not be loaded.
* @throws GeneralSecurityException if security setup failed.
* @throws IllegalArgumentException if alias is empty, or no matching
* certificate chain is found.
* @throws NullPointerException if keyStoreUri, storePassword, or alias is
* {@code null}.
*/
public static X509Certificate[] loadCertificateChain(String keyStoreUri, String alias, char[] storePassword)
throws IOException, GeneralSecurityException {
KeyStoreType configuration = getKeyStoreTypeFromUri(keyStoreUri);
if (configuration.simpleStore != null) {
Credentials credentials = loadSimpleKeyStore(keyStoreUri, configuration);
if (credentials.chain == null) {
throw new IllegalArgumentException("No certificate chain found!");
}
return credentials.chain;
}
if (null == alias) {
throw new NullPointerException("alias must be provided!");
}
if (alias.isEmpty()) {
throw new IllegalArgumentException("alias must not be empty!");
}
KeyStore ks = loadKeyStore(keyStoreUri, storePassword, configuration);
Certificate[] chain = ks.getCertificateChain(alias);
return asX509Certificates(chain);
}
/**
* Configure defaults.
*
* Key store type:
*
* <pre>
* ".jks" to "JKS"
* ".bks" to "BKS"
* ".p12" to "PKCS12"
* ".pem" to "CRT/PEM" (custom reader)
* ".crt" to "CRT/PEM" (custom reader)
* "*" to system default
* </pre>
*
* Input stream factory: {@link #CLASSPATH_SCHEME} to classpath loader.
*
* Clear previous configuration. Custom entry must be added again using
* {@link #configure(String, InputStreamFactory)},
* {@link #configure(String, KeyStoreType)}, and
* {@link #configureAlias(String, String)}.
*/
public static void configureDefaults() {
KEY_STORE_TYPES.clear();
KEY_STORE_TYPES.put(JKS_ENDING, new KeyStoreType(JKS_TYPE));
KEY_STORE_TYPES.put(BKS_ENDING, new KeyStoreType(BKS_TYPE));
KEY_STORE_TYPES.put(PKCS12_ENDING, new KeyStoreType(PKCS12_TYPE));
KeyStoreType simple = new KeyStoreType(new SimpleKeyStore() {
@Override
public Credentials load(InputStream inputStream) throws GeneralSecurityException, IOException {
return loadPemCredentials(inputStream);
}
});
KEY_STORE_TYPES.put(PEM_ENDING, simple);
KEY_STORE_TYPES.put(CRT_ENDING, simple);
KEY_STORE_TYPES.put(DEFAULT_ENDING, new KeyStoreType(KeyStore.getDefaultType()));
INPUT_STREAM_FACTORIES.clear();
INPUT_STREAM_FACTORIES.put(CLASSPATH_SCHEME, new ClassLoaderInputStreamFactory());
}
/**
* Configure a {@link KeyStoreType} for a URI ending.
*
* @param ending URI ending. If {@link #DEFAULT_ENDING} is used, the key
* store default type is configured. Ending is converted to lower
* case before added to the {@link #KEY_STORE_TYPES}.
* @param type the key store type.
* @return previous key store type, or {@code null}, if no key store type
* was configured before
* @throws NullPointerException if ending or type is {@code null}.
* @throws IllegalArgumentException if ending doesn't start with "." and
* isn't {@link #DEFAULT_ENDING}.
* @since 3.0 (changed parameter type to KeyStoreType)
*/
public static KeyStoreType configure(String ending, KeyStoreType type) {
if (ending == null) {
throw new NullPointerException("ending must not be null!");
}
if (!ending.equals(DEFAULT_ENDING) && !ending.startsWith(".")) {
throw new IllegalArgumentException("ending must start with \".\"!");
}
if (type == null) {
throw new NullPointerException("key store type must not be null!");
}
return KEY_STORE_TYPES.put(ending.toLowerCase(), type);
}
/**
* Add alias for ending.
*
* Use the same {@link KeyStoreType} for the alias as for the ending.
*
* @param alias new alias
* @param ending already configured ending
* @return previous key store type, or {@code null}, if no key store type
* was configured before
* @throws NullPointerException if alias of ending is {@code null}.
* @throws IllegalArgumentException if alias and ending are equal, or alias
* or ending doesn't start with "." and isn't
* {@link #DEFAULT_ENDING}.
* @since 3.6
*/
public static KeyStoreType configureAlias(String alias, String ending) {
if (alias == null) {
throw new NullPointerException("alias must not be null!");
}
if (ending == null) {
throw new NullPointerException("ending must not be null!");
}
if (ending.equals(alias)) {
throw new IllegalArgumentException("alias must differ from ending!");
}
if (!ending.equals(DEFAULT_ENDING) && !ending.startsWith(".")) {
throw new IllegalArgumentException("ending must start with \".\"!");
}
if (!alias.equals(DEFAULT_ENDING) && !ending.startsWith(".")) {
throw new IllegalArgumentException("alias must start with \".\"!");
}
KeyStoreType type = KEY_STORE_TYPES.get(ending);
if (type == null) {
throw new IllegalArgumentException("ending must already be configured!");
}
return KEY_STORE_TYPES.put(alias, type);
}
/**
* Configure input stream factory for URI scheme.
*
* @param scheme URI scheme. Scheme is converted to lower case before added
* to the {@link #INPUT_STREAM_FACTORIES}.
* @param streamFactory input stream factory to read key stores access with
* this URI scheme.
* @return previous stream factory, if already configure, or {@code null},
* if not stream factory was previously configured.
* @throws NullPointerException if scheme or stream factory is {@code null}.
* @throws IllegalArgumentException if scheme doesn't end with "://".
*/
public static InputStreamFactory configure(String scheme, InputStreamFactory streamFactory) {
if (scheme == null) {
throw new NullPointerException("scheme must not be null!");
}
if (!scheme.endsWith(SCHEME_DELIMITER)) {
throw new IllegalArgumentException("scheme must end with \"" + SCHEME_DELIMITER + "\"!");
}
if (streamFactory == null) {
throw new NullPointerException("stream factory must not be null!");
}
return INPUT_STREAM_FACTORIES.put(scheme.toLowerCase(), streamFactory);
}
/**
* Check, if input stream from URI is available.
*
* @param keyStoreUri URI of input stream
* @return {@code true}, if available, {@code false}, if not.
* @throws NullPointerException if the keyStoreUri is {@code null}
* @since 3.0
*/
public static boolean isAvailableFromUri(String keyStoreUri) {
try {
InputStream in = getInputStreamFromUri(keyStoreUri);
if (in != null) {
in.close();
return true;
}
} catch (IOException ex) {
}
return false;
}
/**
* Get key store type from URI.
*
* Get the configured key store type for URI ending from
* {@link #KEY_STORE_TYPES}. If no key store type for URI ending is
* available, get the key store type for {@link #DEFAULT_ENDING}.
*
* @param uri URI provide ending for lookup. Converted to lower case before
* used.
* @return configured key store type for ending or default, if ending is not
* configured.
* @throws GeneralSecurityException if configuration is not available
* @see #configure(String, KeyStoreType)
* @since 3.0 (renamed, was getKeyStoreConfigurationFromUri)
*/
private static KeyStoreType getKeyStoreTypeFromUri(String uri) throws GeneralSecurityException {
String ending = null;
KeyStoreType type = null;
if (!uri.equals(DEFAULT_ENDING)) {
int lastPartIndex = uri.lastIndexOf('/');
int endingIndex = uri.lastIndexOf('.');
if (lastPartIndex < endingIndex) {
ending = uri.substring(endingIndex).toLowerCase();
type = KEY_STORE_TYPES.get(ending);
}
}
if (type == null) {
type = KEY_STORE_TYPES.get(DEFAULT_ENDING);
}
if (type == null) {
throw new GeneralSecurityException("no key store type for " + uri);
}
return type;
}
/**
* Get scheme from URI.
*
* Use {@link #SCHEME_DELIMITER} to split scheme from URI.
*
* @param uri URI starting with scheme.
* @return scheme, or {@code null}, if no scheme is provided.
*/
private static String getSchemeFromUri(String uri) {
int schemeIndex = uri.indexOf(SCHEME_DELIMITER);
if (0 < schemeIndex) {
return uri.substring(0, schemeIndex + SCHEME_DELIMITER.length()).toLowerCase();
}
return null;
}
/**
* Get input stream from URI.
*
* Create input stream from URI. If no scheme is provided
* ({@link #SCHEME_DELIMITER} not found), open a file using the URI.
* Otherwise, if a scheme is provided, use that scheme to lookup a
* configured {@link InputStreamFactory}. If no factory for that scheme was
* configured with {@link #configure(String, InputStreamFactory)}, then use
* {@link URL}.
*
* @param keyStoreUri URI of input stream
* @return input stream
* @throws IOException if input stream is not available
* @throws NullPointerException if the keyStoreUri is {@code null}
*/
private static InputStream getInputStreamFromUri(String keyStoreUri) throws IOException {
if (null == keyStoreUri) {
throw new NullPointerException("keyStoreUri must be provided!");
}
InputStream inStream = null;
String scheme = getSchemeFromUri(keyStoreUri);
if (scheme == null) {
// no scheme, fall-back to local file
String errorMessage = null;
File file = new File(keyStoreUri);
if (!file.exists()) {
errorMessage = " doesn't exists!";
} else if (!file.isFile()) {
errorMessage = " is not a file!";
} else if (!file.canRead()) {
errorMessage = " could not be read!";
}
if (errorMessage == null) {
inStream = new FileInputStream(file);
} else {
throw new IOException("URI: " + keyStoreUri + ", file: " + file.getAbsolutePath() + errorMessage);
}
} else {
InputStreamFactory streamFactory = INPUT_STREAM_FACTORIES.get(scheme);
if (streamFactory != null) {
inStream = streamFactory.create(keyStoreUri);
}
}
if (inStream == null) {
URL url = new URL(keyStoreUri);
inStream = url.openStream();
}
return inStream;
}
/**
* Load key store.
*
* @param keyStoreUri key store URI. Use
* {@link #getInputStreamFromUri(String)} to read the key store,
* and {@link #getKeyStoreTypeFromUri(String)} to determine the
* type of the key store.
* @param storePassword password for key store.
* @param configuration password for key store.
* @return key store
* @throws IOException if key store could not be loaded.
* @throws GeneralSecurityException if security setup failed.
* @throws NullPointerException if keyStoreUri or storePassword is null.
* @since 3.0 (changed parameter type to KeyStoreType)
*/
private static KeyStore loadKeyStore(String keyStoreUri, char[] storePassword, KeyStoreType configuration)
throws GeneralSecurityException, IOException {
if (null == storePassword) {
throw new NullPointerException("storePassword must be provided!");
}
InputStream inStream = getInputStreamFromUri(keyStoreUri);
KeyStore keyStore = KeyStore.getInstance(configuration.type);
try {
keyStore.load(inStream, storePassword);
return keyStore;
} catch (IOException ex) {
throw new IOException(ex + ", URI: " + keyStoreUri + ", type: " + configuration.type + ", "
+ keyStore.getProvider().getName());
} finally {
inStream.close();
}
}
/**
* Load simple key store
*
* @param keyStoreUri key store URI. Use
* {@link #getInputStreamFromUri(String)} to read the simple key
* store
* @param configuration the key store configuration to read the simnple key
* store
* @return credentials
* @throws GeneralSecurityException if credentials could not be read
* @throws IOException if key store could not be read
* @since 3.0 (changed parameter type to KeyStoreType)
*/
private static Credentials loadSimpleKeyStore(String keyStoreUri, KeyStoreType configuration)
throws GeneralSecurityException, IOException {
InputStream inputStream = getInputStreamFromUri(keyStoreUri);
try {
return configuration.simpleStore.load(inputStream);
} finally {
inputStream.close();
}
}
/**
* Load credentials in PEM format
*
* @param inputStream input stream
* @return credentials
* @throws GeneralSecurityException if credentials could not be read
* @throws IOException if key store could not be read
* @since 3.0 (changed scope to public)
*/
public static Credentials loadPemCredentials(InputStream inputStream) throws GeneralSecurityException, IOException {
return loadPemCredentials(new PemReader(inputStream));
}
/**
* Load credentials in PEM format
*
* @param pemReader PEM reader
* @return credentials
* @throws GeneralSecurityException if credentials could not be read
* @throws IOException if key store could not be read
* @since 3.12
*/
public static Credentials loadPemCredentials(PemReader pemReader) throws GeneralSecurityException, IOException {
try {
String tag;
Asn1DerDecoder.Keys keys = new Asn1DerDecoder.Keys();
List<Certificate> certificatesList = new ArrayList<>();
CertificateFactory factory = CertificateFactory.getInstance("X.509");
while ((tag = pemReader.readNextBegin()) != null) {
byte[] decode = pemReader.readToEnd();
if (decode != null) {
if (tag.contains("CERTIFICATE")) {
certificatesList.add(factory.generateCertificate(new ByteArrayInputStream(decode)));
} else if (tag.contains("PRIVATE KEY")) {
Asn1DerDecoder.Keys read = Asn1DerDecoder.readPrivateKey(decode);
if (read == null) {
throw new GeneralSecurityException("private key type not supported!");
}
keys.add(read);
} else if (tag.contains("PUBLIC KEY")) {
PublicKey read = Asn1DerDecoder.readSubjectPublicKey(decode);
if (read == null) {
throw new GeneralSecurityException("public key type not supported!");
}