Copyright update
[openflowjava.git] / openflow-protocol-impl / src / main / java / org / opendaylight / openflowjava / protocol / impl / core / SslContextFactory.java
1 /*
2  * Copyright (c) 2013 Pantheon Technologies s.r.o. and others. All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.openflowjava.protocol.impl.core;
10
11 import java.security.KeyStore;
12 import java.security.Security;
13
14 import javax.net.ssl.KeyManagerFactory;
15 import javax.net.ssl.SSLContext;
16
17 /**
18  * Class for setting up TLS connection.
19  *
20  * @author michal.polkorab
21  */
22 public final class SslContextFactory {
23
24     
25     // "TLS" - supports some version of TLS
26     // Use "TLSv1", "TLSv1.1", "TLSv1.2" for specific TLS version
27     private static final String PROTOCOL = "TLS";
28     private static final SSLContext SERVER_CONTEXT;
29     private static final SSLContext CLIENT_CONTEXT;
30
31     static {
32         String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
33         if (algorithm == null) {
34             algorithm = "SunX509";
35         }
36
37         SSLContext serverContext;
38         SSLContext clientContext;
39         try {
40             KeyStore ks = KeyStore.getInstance("JKS");
41             ks.load(SslKeyStore.asInputStream(),
42                     SslKeyStore.getKeyStorePassword());
43
44             KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
45             kmf.init(ks, SslKeyStore.getCertificatePassword());
46
47             serverContext = SSLContext.getInstance(PROTOCOL);
48             serverContext.init(kmf.getKeyManagers(), null, null);
49         } catch (RuntimeException e) {
50             throw new Error(
51                     "Failed to initialize the server-side SSLContext", e);
52         } catch (Exception e) {
53             throw new Error(
54                     "Failed to initialize the server-side SSLContext", e);
55         }
56         try {
57             clientContext = SSLContext.getInstance(PROTOCOL);
58             clientContext.init(null, SslTrustManagerFactory.getTrustManagers(), null);
59         } catch (Exception e) {
60             throw new Error(
61                     "Failed to initialize the client-side SSLContext", e);
62         }
63
64         SERVER_CONTEXT = serverContext;
65         CLIENT_CONTEXT = clientContext;
66     }
67
68     /**
69      * @return servercontext
70      */
71     public static SSLContext getServerContext() {
72         return SERVER_CONTEXT;
73     }
74
75     /**
76      * @return cliencontext
77      */
78     public static SSLContext getClientContext() {
79         return CLIENT_CONTEXT;
80     }
81 }