2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.protocol.pcep.impl.tls;
10 import com.google.common.base.Preconditions;
11 import java.io.IOException;
12 import java.security.KeyStore;
13 import java.security.NoSuchAlgorithmException;
14 import java.security.cert.CertificateException;
15 import javax.net.ssl.KeyManagerFactory;
16 import javax.net.ssl.SSLContext;
17 import javax.net.ssl.TrustManagerFactory;
18 import org.opendaylight.controller.config.yang.pcep.impl.Tls;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
23 * Class for setting up TLS connection.
25 public class SslContextFactory {
27 private static final String PROTOCOL = "TLS";
28 private final Tls tlsConfig;
30 private static final Logger LOG = LoggerFactory
31 .getLogger(SslContextFactory.class);
35 * TLS configuration object, contains keystore locations and
38 public SslContextFactory(final Tls tlsConfig) {
39 this.tlsConfig = Preconditions.checkNotNull(tlsConfig);
42 public SSLContext getServerContext() {
44 final KeyStore ks = KeyStore.getInstance(this.tlsConfig.getKeystoreType().name());
45 ks.load(SslKeyStore.asInputStream(this.tlsConfig.getKeystore(), this.tlsConfig.getKeystorePathType()),
46 this.tlsConfig.getKeystorePassword().toCharArray());
47 final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
48 kmf.init(ks, this.tlsConfig.getCertificatePassword().toCharArray());
50 final KeyStore ts = KeyStore.getInstance(this.tlsConfig.getTruststoreType().name());
51 ts.load(SslKeyStore.asInputStream(this.tlsConfig.getTruststore(), this.tlsConfig.getTruststorePathType()),
52 this.tlsConfig.getTruststorePassword().toCharArray());
53 final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
56 final SSLContext serverContext = SSLContext.getInstance(PROTOCOL);
57 serverContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
59 } catch (final IOException e) {
60 LOG.warn("IOException - Failed to load keystore / truststore."
61 + " Failed to initialize the server-side SSLContext", e);
62 } catch (final NoSuchAlgorithmException e) {
63 LOG.warn("NoSuchAlgorithmException - Unsupported algorithm."
64 + " Failed to initialize the server-side SSLContext", e);
65 } catch (final CertificateException e) {
66 LOG.warn("CertificateException - Unable to access certificate (check password)."
67 + " Failed to initialize the server-side SSLContext", e);
68 } catch (final Exception e) {
69 LOG.warn("Exception - Failed to initialize the server-side SSLContext", e);
71 //TODO try to use default SSLContext instance?