1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 package org.apache.commons.net.util;
19
20 import java.io.IOException;
21 import java.security.GeneralSecurityException;
22
23 import javax.net.ssl.KeyManager;
24 import javax.net.ssl.SSLContext;
25 import javax.net.ssl.TrustManager;
26
27 /**
28 * General utilities for SSLContext.
29 *
30 * @since 3.0
31 */
32 public class SSLContextUtils {
33
34 /**
35 * Create and initialize an SSLContext.
36 *
37 * @param protocol the protocol used to instantiate the context
38 * @param keyManager the key manager, may be {@code null}
39 * @param trustManager the trust manager, may be {@code null}
40 * @return the initialized context.
41 * @throws IOException this is used to wrap any {@link GeneralSecurityException} that occurs
42 */
43 public static SSLContext createSSLContext(final String protocol, final KeyManager keyManager, final TrustManager trustManager) throws IOException {
44 return createSSLContext(protocol, keyManager == null ? null : new KeyManager[] { keyManager },
45 trustManager == null ? null : new TrustManager[] { trustManager });
46 }
47
48 /**
49 * Create and initialize an SSLContext.
50 *
51 * @param protocol the protocol used to instantiate the context
52 * @param keyManagers the array of key managers, may be {@code null} but array entries must not be {@code null}
53 * @param trustManagers the array of trust managers, may be {@code null} but array entries must not be {@code null}
54 * @return the initialized context.
55 * @throws IOException this is used to wrap any {@link GeneralSecurityException} that occurs
56 */
57 public static SSLContext createSSLContext(final String protocol, final KeyManager[] keyManagers, final TrustManager[] trustManagers) throws IOException {
58 final SSLContext ctx;
59 try {
60 ctx = SSLContext.getInstance(protocol);
61 ctx.init(keyManagers, trustManagers, /* SecureRandom */ null);
62 } catch (final GeneralSecurityException e) {
63 final IOException ioe = new IOException("Could not initialize SSL context");
64 ioe.initCause(e);
65 throw ioe;
66 }
67 return ctx;
68 }
69
70 private SSLContextUtils() {
71 // Not instantiable
72 }
73 }