View Javadoc
1   /*
2    * Copyright 2017 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.handler.ssl;
17  
18  import io.netty.util.internal.PlatformDependent;
19  
20  import javax.net.ssl.SSLEngine;
21  import java.lang.reflect.InvocationTargetException;
22  import java.lang.reflect.Method;
23  
24  /**
25   * Contains methods that can be used to detect if conscrypt is usable.
26   */
27  final class Conscrypt {
28      // This class exists to avoid loading other conscrypt related classes using features only available in JDK8+,
29      // because we need to maintain JDK6+ runtime compatibility.
30      private static final Method IS_CONSCRYPT_SSLENGINE = loadIsConscryptEngine();
31  
32      private static Method loadIsConscryptEngine() {
33          try {
34              Class<?> conscryptClass = Class.forName("org.conscrypt.Conscrypt", true,
35                      ConscryptAlpnSslEngine.class.getClassLoader());
36              return conscryptClass.getMethod("isConscrypt", SSLEngine.class);
37          } catch (Throwable ignore) {
38              // Conscrypt was not loaded.
39              return null;
40          }
41      }
42  
43      /**
44       * Indicates whether or not conscrypt is available on the current system.
45       */
46      static boolean isAvailable() {
47          return IS_CONSCRYPT_SSLENGINE != null && PlatformDependent.javaVersion() >= 8;
48      }
49  
50      static boolean isEngineSupported(SSLEngine engine) {
51          return isAvailable() && isConscryptEngine(engine);
52      }
53  
54      private static boolean isConscryptEngine(SSLEngine engine) {
55          try {
56              return (Boolean) IS_CONSCRYPT_SSLENGINE.invoke(null, engine);
57          } catch (IllegalAccessException ignore) {
58              return false;
59          } catch (InvocationTargetException ex) {
60              throw new RuntimeException(ex);
61          }
62      }
63  
64      private Conscrypt() { }
65  }