1/*
2 *  Licensed to the Apache Software Foundation (ASF) under one or more
3 *  contributor license agreements.  See the NOTICE file distributed with
4 *  this work for additional information regarding copyright ownership.
5 *  The ASF licenses this file to You under the Apache License, Version 2.0
6 *  (the "License"); you may not use this file except in compliance with
7 *  the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *  Unless required by applicable law or agreed to in writing, software
12 *  distributed under the License is distributed on an "AS IS" BASIS,
13 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *  See the License for the specific language governing permissions and
15 *  limitations under the License.
16 */
17
18package org.conscrypt;
19
20import java.io.IOException;
21import java.security.InvalidAlgorithmParameterException;
22import java.security.KeyStore;
23import java.security.KeyStoreException;
24import java.security.NoSuchAlgorithmException;
25import java.security.cert.CertificateException;
26import javax.net.ssl.ManagerFactoryParameters;
27import javax.net.ssl.TrustManager;
28import javax.net.ssl.TrustManagerFactorySpi;
29
30/**
31 *
32 * TrustManagerFactory service provider interface implementation.
33 *
34 * @see javax.net.ssl.TrustManagerFactorySpi
35 */
36public class TrustManagerFactoryImpl extends TrustManagerFactorySpi {
37
38    private KeyStore keyStore;
39
40    /**
41     * @see javax.net.ssl.TrustManagerFactorySpi#engineInit(KeyStore)
42     */
43    @Override
44    public void engineInit(KeyStore ks) throws KeyStoreException {
45        if (ks != null) {
46            keyStore = ks;
47        } else {
48            keyStore = KeyStore.getInstance("AndroidCAStore");
49            try {
50                keyStore.load(null, null);
51            } catch (IOException e) {
52                throw new KeyStoreException(e);
53            } catch (CertificateException e) {
54                throw new KeyStoreException(e);
55            } catch (NoSuchAlgorithmException e) {
56                throw new KeyStoreException(e);
57            }
58        }
59    }
60
61    /**
62     * @see javax.net.ssl#engineInit(ManagerFactoryParameters)
63     */
64    @Override
65    public void engineInit(ManagerFactoryParameters spec)
66            throws InvalidAlgorithmParameterException {
67        throw new InvalidAlgorithmParameterException(
68                "ManagerFactoryParameters not supported");
69    }
70
71    /**
72     * @see javax.net.ssl#engineGetTrustManagers()
73     */
74    @Override
75    public TrustManager[] engineGetTrustManagers() {
76        if (keyStore == null) {
77            throw new IllegalStateException(
78                    "TrustManagerFactory is not initialized");
79        }
80        return new TrustManager[] { new TrustManagerImpl(keyStore) };
81    }
82}
83