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.lang.reflect.InvocationTargetException; 022import java.lang.reflect.Method; 023 024import javax.net.ssl.SSLSocket; 025 026/** 027 * General utilities for SSLSocket. 028 * @since 3.4 029 */ 030public class SSLSocketUtils { 031 private SSLSocketUtils() { 032 // Not instantiable 033 } 034 035 /** 036 * Enable the HTTPS endpoint identification algorithm on an SSLSocket. 037 * @param socket the SSL socket 038 * @return {@code true} on success (this is only supported on Java 1.7+) 039 */ 040 public static boolean enableEndpointNameVerification(SSLSocket socket) { 041 try { 042 Class<?> cls = Class.forName("javax.net.ssl.SSLParameters"); 043 Method setEndpointIdentificationAlgorithm = cls.getDeclaredMethod("setEndpointIdentificationAlgorithm", String.class); 044 Method getSSLParameters = SSLSocket.class.getDeclaredMethod("getSSLParameters"); 045 Method setSSLParameters = SSLSocket.class.getDeclaredMethod("setSSLParameters", cls); 046 if (setEndpointIdentificationAlgorithm != null && getSSLParameters != null && setSSLParameters != null) { 047 Object sslParams = getSSLParameters.invoke(socket); 048 if (sslParams != null) { 049 setEndpointIdentificationAlgorithm.invoke(sslParams, "HTTPS"); 050 setSSLParameters.invoke(socket, sslParams); 051 return true; 052 } 053 } 054 } catch (SecurityException e) { // Ignored 055 } catch (ClassNotFoundException e) { // Ignored 056 } catch (NoSuchMethodException e) { // Ignored 057 } catch (IllegalArgumentException e) { // Ignored 058 } catch (IllegalAccessException e) { // Ignored 059 } catch (InvocationTargetException e) { // Ignored 060 } 061 return false; 062 } 063}