tls1.2的支持

nx7onnlm  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(551)

我们有一个运行在嵌入式平台上的遗留应用程序,我们使用Java6作为jvm。我们可以从需要tls1.2支持的应用程序访问https。我们使用的jvm没有提供这一点。如何实现对应用程序的tls1.2支持?

f0ofjuux

f0ofjuux1#

我们可以使用bouncy castle库来实现对tls1.2的支持。
下面是详细的解决方案
将适当的bc库添加到项目中
maven依赖

<dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15to18</artifactId>
            <version>1.64</version>
    </dependency>
    <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bctls-jdk15to18</artifactId>
            <version>1.64</version>
    </dependency>

将安全提供程序添加为bc

if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
      Security.insertProviderAt(new BouncyCastleProvider(), 1);
  }
  // add provider only if it's not in the JVM
  if (Security.getProvider(BouncyCastleJsseProvider.PROVIDER_NAME) == null) {
      Security.insertProviderAt(new BouncyCastleJsseProvider(), 2);
  }

或者可以更新jre/lib/security/java.security

security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider
security.provider.2=org.bouncycastle.jsse.provider.BouncyCastleJsseProvider
security.provider.3=sun.security.provider.Sun
security.provider.4=sun.security.rsa.SunRsaSign
security.provider.5=com.sun.net.ssl.internal.ssl.Provider
security.provider.6=com.sun.crypto.provider.SunJCE
security.provider.7=sun.security.jgss.SunProvider
security.provider.8=com.sun.security.sasl.Provider

bc库需要在顶部(1和2)
使用tls1.2初始化ssl上下文

SSLContext tls = SSLContext.getInstance("TLSv1.2");
tls.init(null, null, null);
SSLContext.setDefault(tls);

测试

HttpsURLConnection urlConnection = null;

    try {

        URL url = new URL("https://www.nist.gov/");
        urlConnection = (HttpsURLConnection) url.openConnection();

        String data = IOUtils.toString(urlConnection.getInputStream(), "UTF-8");
        System.out.println(data);

    } catch (IOException ex) {
        ex.printStackTrace();
        try {
            if (urlConnection != null) {
                code = ((HttpURLConnection) urlConnection).getResponseCode();
                message = ((HttpURLConnection) urlConnection).getResponseMessage();
            } else {
                message = ex.toString();
            }
        } catch (IOException ex2) {
            message = ex2.toString();
        }

        System.out.println("Response : " + message);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }

相关问题