summaryrefslogtreecommitdiffstats
path: root/security-utils/src/main/java/com/yahoo/security/tls/TrustManagerUtils.java
blob: f114b672ed89d3ad8d5bbe66612744fdebefa90f (plain) (blame)
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
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security.tls;

import com.yahoo.security.KeyStoreBuilder;
import com.yahoo.security.KeyStoreType;

import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509ExtendedTrustManager;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.List;

/**
 * Utility methods for constructing {@link X509ExtendedTrustManager}.
 *
 * @author bjorncs
 */
public class TrustManagerUtils {

    public static X509ExtendedTrustManager createDefaultX509TrustManager(KeyStore truststore) {
        try {
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(truststore);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
            return Arrays.stream(trustManagers)
                    .filter(manager -> manager instanceof X509ExtendedTrustManager)
                    .map(X509ExtendedTrustManager.class::cast)
                    .findFirst()
                    .orElseThrow(() -> new RuntimeException("No X509ExtendedTrustManager in " + List.of(trustManagers)));
        } catch (GeneralSecurityException e) {
            throw new RuntimeException(e);
        }
    }

    public static X509ExtendedTrustManager createDefaultX509TrustManager(List<X509Certificate> certificates) {
        KeyStoreBuilder truststoreBuilder = KeyStoreBuilder.withType(KeyStoreType.PKCS12);
        for (int i = 0; i < certificates.size(); i++) {
            truststoreBuilder.withCertificateEntry("cert-" + i, certificates.get(i));
        }
        KeyStore truststore = truststoreBuilder.build();
        return createDefaultX509TrustManager(truststore);
    }

    public static X509ExtendedTrustManager createDefaultX509TrustManager() {
        return createDefaultX509TrustManager((KeyStore) null);
    }
}