2 * Copyright (c) 2013 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.controller.netconf.it;
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;
19 import javax.net.ssl.KeyManagerFactory;
20 import javax.net.ssl.SSLContext;
21 import javax.net.ssl.TrustManagerFactory;
23 import com.google.common.base.Preconditions;
25 public final class SSLUtil {
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 {
34 Preconditions.checkNotNull(ksTrustFile, "ksTrustFile cannot be null");
35 Preconditions.checkNotNull(ksKeysFile, "ksKeysFile cannot be null");
37 final char[] passphrase = pass.toCharArray();
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);
45 // KeyManager's decide which key material to use.
46 final KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
47 kmf.init(ksKeys, passphrase);
49 // TrustManager's decide whether to allow connections.
50 final TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
53 final SSLContext sslContext = SSLContext.getInstance("TLS");
55 // Create/initialize the SSLContext with key material
56 sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);