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; 023import javax.net.ssl.KeyManager; 024import javax.net.ssl.SSLContext; 025import javax.net.ssl.TrustManager; 026 027/** 028 * General utilities for SSLContext. 029 * @since 3.0 030 */ 031public class SSLContextUtils { 032 033 private SSLContextUtils() { 034 // Not instantiable 035 } 036 037 /** 038 * Create and initialise an SSLContext. 039 * @param protocol the protocol used to instatiate the context 040 * @param keyManager the key manager, may be {@code null} 041 * @param trustManager the trust manager, may be {@code null} 042 * @return the initialised context. 043 * @throws IOException this is used to wrap any {@link GeneralSecurityException} that occurs 044 */ 045 public static SSLContext createSSLContext(String protocol, KeyManager keyManager, TrustManager trustManager) 046 throws IOException { 047 return createSSLContext(protocol, 048 keyManager == null ? null : new KeyManager[] { keyManager }, 049 trustManager == null ? null : new TrustManager[] { trustManager }); 050 } 051 052 /** 053 * Create and initialise an SSLContext. 054 * @param protocol the protocol used to instatiate the context 055 * @param keyManagers the array of key managers, may be {@code null} but array entries must not be {@code null} 056 * @param trustManagers the array of trust managers, may be {@code null} but array entries must not be {@code null} 057 * @return the initialised context. 058 * @throws IOException this is used to wrap any {@link GeneralSecurityException} that occurs 059 */ 060 public static SSLContext createSSLContext(String protocol, KeyManager[] keyManagers, TrustManager[] trustManagers) 061 throws IOException { 062 SSLContext ctx; 063 try { 064 ctx = SSLContext.getInstance(protocol); 065 ctx.init(keyManagers, trustManagers, /*SecureRandom*/ null); 066 } catch (GeneralSecurityException e) { 067 IOException ioe = new IOException("Could not initialize SSL context"); 068 ioe.initCause(e); 069 throw ioe; 070 } 071 return ctx; 072 } 073}