c1199c1e66527bca2a92d61d7f40d048edaaad25
[openflowjava.git] / simple-client / src / main / java / org / opendaylight / openflowjava / protocol / impl / clients / ClientSslContextFactory.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.clients;
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 import javax.net.ssl.TrustManagerFactory;
17
18 /**
19  * Class for setting up TLS connection.
20  *
21  * @author michal.polkorab
22  */
23 public final class ClientSslContextFactory {
24
25     
26     // "TLS" - supports some version of TLS
27     // Use "TLSv1", "TLSv1.1", "TLSv1.2" for specific TLS version
28     private static final String PROTOCOL = "TLS";
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 clientContext;
38         try {
39             KeyStore ks = KeyStore.getInstance("JKS");
40             ks.load(ClientSslKeyStore.asInputStream(),
41                     ClientSslKeyStore.getKeyStorePassword());
42
43             KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
44             kmf.init(ks, ClientSslKeyStore.getCertificatePassword());
45             
46             KeyStore ts = KeyStore.getInstance("JKS");
47             ts.load(ClientSslTrustStore.asInputStream(),
48                     ClientSslTrustStore.getKeyStorePassword());
49             
50             TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
51             tmf.init(ts);
52             
53             clientContext = SSLContext.getInstance(PROTOCOL);
54             clientContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
55         } catch (Exception e) {
56             throw new Error(
57                     "Failed to initialize the client-side SSLContext", e);
58         }
59
60         CLIENT_CONTEXT = clientContext;
61     }
62
63     /**
64      * @return cliencontext
65      */
66     public static SSLContext getClientContext() {
67         return CLIENT_CONTEXT;
68     }
69 }