Merge "BUG 1330 - list key counts|values diff in payload and URI"
[controller.git] / opendaylight / netconf / netconf-it / src / test / java / org / opendaylight / controller / netconf / it / SSLUtil.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. 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 package org.opendaylight.controller.netconf.it;
9
10 import java.io.IOException;
11 import java.io.InputStream;
12 import java.security.KeyManagementException;
13 import java.security.KeyStore;
14 import java.security.KeyStoreException;
15 import java.security.NoSuchAlgorithmException;
16 import java.security.UnrecoverableKeyException;
17 import java.security.cert.CertificateException;
18
19 import javax.net.ssl.KeyManagerFactory;
20 import javax.net.ssl.SSLContext;
21 import javax.net.ssl.TrustManagerFactory;
22
23 import com.google.common.base.Preconditions;
24
25 public final class SSLUtil {
26
27     private SSLUtil() {
28     }
29
30     public static SSLContext initializeSecureContext(final String pass, final InputStream ksKeysFile, final InputStream ksTrustFile,
31                                                      final String algorithm) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
32             UnrecoverableKeyException, KeyManagementException {
33
34         Preconditions.checkNotNull(ksTrustFile, "ksTrustFile cannot be null");
35         Preconditions.checkNotNull(ksKeysFile, "ksKeysFile cannot be null");
36
37         final char[] passphrase = pass.toCharArray();
38
39         // First initialize the key and trust material.
40         final KeyStore ksKeys = KeyStore.getInstance("JKS");
41         ksKeys.load(ksKeysFile, passphrase);
42         final KeyStore ksTrust = KeyStore.getInstance("JKS");
43         ksTrust.load(ksTrustFile, passphrase);
44
45         // KeyManager's decide which key material to use.
46         final KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
47         kmf.init(ksKeys, passphrase);
48
49         // TrustManager's decide whether to allow connections.
50         final TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
51         tmf.init(ksTrust);
52
53         final SSLContext sslContext = SSLContext.getInstance("TLS");
54
55         // Create/initialize the SSLContext with key material
56         sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
57         return sslContext;
58     }
59
60 }