001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 * 017 */ 018 019package org.apache.commons.net.util; 020 021import java.io.IOException; 022import java.security.GeneralSecurityException; 023 024import javax.net.ssl.KeyManager; 025import javax.net.ssl.SSLContext; 026import javax.net.ssl.TrustManager; 027 028/** 029 * General utilities for SSLContext. 030 * @since 3.0 031 */ 032public class SSLContextUtils { 033 034 private SSLContextUtils() { 035 // Not instantiable 036 } 037 038 /** 039 * Create and initialize an SSLContext. 040 * @param protocol the protocol used to instatiate the context 041 * @param keyManager the key manager, may be {@code null} 042 * @param trustManager the trust manager, may be {@code null} 043 * @return the initialized context. 044 * @throws IOException this is used to wrap any {@link GeneralSecurityException} that occurs 045 */ 046 public static SSLContext createSSLContext(final String protocol, final KeyManager keyManager, final TrustManager trustManager) 047 throws IOException { 048 return createSSLContext(protocol, 049 keyManager == null ? null : new KeyManager[] { keyManager }, 050 trustManager == null ? null : new TrustManager[] { trustManager }); 051 } 052 053 /** 054 * Create and initialize an SSLContext. 055 * @param protocol the protocol used to instatiate the context 056 * @param keyManagers the array of key managers, may be {@code null} but array entries must not be {@code null} 057 * @param trustManagers the array of trust managers, may be {@code null} but array entries must not be {@code null} 058 * @return the initialized context. 059 * @throws IOException this is used to wrap any {@link GeneralSecurityException} that occurs 060 */ 061 public static SSLContext createSSLContext(final String protocol, final KeyManager[] keyManagers, 062 final TrustManager[] trustManagers) throws IOException { 063 final SSLContext ctx; 064 try { 065 ctx = SSLContext.getInstance(protocol); 066 ctx.init(keyManagers, trustManagers, /* SecureRandom */ null); 067 } catch (final GeneralSecurityException e) { 068 final IOException ioe = new IOException("Could not initialize SSL context"); 069 ioe.initCause(e); 070 throw ioe; 071 } 072 return ctx; 073 } 074}