BundledTrustManager.java

 1package eu.siacs.conversations.crypto;
 2
 3import java.io.IOException;
 4import java.io.InputStream;
 5import java.security.KeyStore;
 6import java.security.KeyStoreException;
 7import java.security.NoSuchAlgorithmException;
 8import java.security.cert.CertificateException;
 9import java.security.cert.X509Certificate;
10
11import javax.net.ssl.X509TrustManager;
12
13public class BundledTrustManager implements X509TrustManager {
14
15    private final X509TrustManager delegate;
16
17    private BundledTrustManager(final KeyStore keyStore)
18            throws NoSuchAlgorithmException, KeyStoreException {
19        this.delegate = TrustManagers.createTrustManager(keyStore);
20    }
21
22    public static Builder builder() throws KeyStoreException {
23        return new Builder();
24    }
25
26    @Override
27    public void checkClientTrusted(final X509Certificate[] chain, final String authType)
28            throws CertificateException {
29        this.delegate.checkClientTrusted(chain, authType);
30    }
31
32    @Override
33    public void checkServerTrusted(final X509Certificate[] chain, final String authType)
34            throws CertificateException {
35        this.delegate.checkServerTrusted(chain, authType);
36    }
37
38    @Override
39    public X509Certificate[] getAcceptedIssuers() {
40        return this.delegate.getAcceptedIssuers();
41    }
42
43    public static class Builder {
44
45        private KeyStore keyStore;
46
47        private Builder() {}
48
49        public Builder loadKeyStore(final InputStream inputStream, final String password)
50                throws CertificateException, IOException, NoSuchAlgorithmException,
51                        KeyStoreException {
52            if (this.keyStore != null) {
53                throw new IllegalStateException("KeyStore has already been loaded");
54            }
55            final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
56            keyStore.load(inputStream, password.toCharArray());
57            this.keyStore = keyStore;
58            return this;
59        }
60
61        public BundledTrustManager build() throws NoSuchAlgorithmException, KeyStoreException {
62            return new BundledTrustManager(keyStore);
63        }
64    }
65}