|
23 | 23 | import java.io.InputStream; |
24 | 24 | import java.io.InputStreamReader; |
25 | 25 | import java.io.UnsupportedEncodingException; |
| 26 | +import java.security.GeneralSecurityException; |
26 | 27 | import java.security.KeyFactory; |
| 28 | +import java.security.KeyStore; |
27 | 29 | import java.security.NoSuchAlgorithmException; |
28 | 30 | import java.security.PrivateKey; |
29 | 31 | import java.security.cert.Certificate; |
|
32 | 34 | import java.security.cert.X509Certificate; |
33 | 35 | import java.security.spec.InvalidKeySpecException; |
34 | 36 | import java.security.spec.PKCS8EncodedKeySpec; |
| 37 | +import java.util.Arrays; |
35 | 38 | import java.util.Collection; |
| 39 | +import java.util.Optional; |
| 40 | +import javax.net.ssl.TrustManager; |
| 41 | +import javax.net.ssl.TrustManagerFactory; |
| 42 | +import javax.net.ssl.X509ExtendedTrustManager; |
| 43 | +import javax.security.auth.x500.X500Principal; |
36 | 44 |
|
37 | 45 | /** |
38 | 46 | * Contains certificate/key PEM file utility method(s). |
@@ -91,5 +99,31 @@ public static PrivateKey getPrivateKey(InputStream inputStream) |
91 | 99 | } |
92 | 100 | } |
93 | 101 | } |
| 102 | + |
| 103 | + /** |
| 104 | + * Creates a X509ExtendedTrustManager using the provided CA certs if applicable for the |
| 105 | + * certificate type. |
| 106 | + */ |
| 107 | + public static Optional<TrustManager> getX509ExtendedTrustManager(InputStream rootCerts) |
| 108 | + throws GeneralSecurityException { |
| 109 | + KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); |
| 110 | + try { |
| 111 | + ks.load(null, null); |
| 112 | + } catch (IOException ex) { |
| 113 | + // Shouldn't really happen, as we're not loading any data. |
| 114 | + throw new GeneralSecurityException(ex); |
| 115 | + } |
| 116 | + X509Certificate[] certs = CertificateUtils.getX509Certificates(rootCerts); |
| 117 | + for (X509Certificate cert : certs) { |
| 118 | + X500Principal principal = cert.getSubjectX500Principal(); |
| 119 | + ks.setCertificateEntry(principal.getName("RFC2253"), cert); |
| 120 | + } |
| 121 | + |
| 122 | + TrustManagerFactory trustManagerFactory = |
| 123 | + TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); |
| 124 | + trustManagerFactory.init(ks); |
| 125 | + return Arrays.stream(trustManagerFactory.getTrustManagers()) |
| 126 | + .filter(trustManager -> trustManager instanceof X509ExtendedTrustManager).findFirst(); |
| 127 | + } |
94 | 128 | } |
95 | 129 |
|
0 commit comments