评论

收藏

[Java] 使用RestTemplate访问https实现SSL请求操作

编程语言 编程语言 发布于:2022-03-07 14:54 | 阅读数:486 | 评论:0

这篇文章主要介绍了使用RestTemplate访问https实现SSL请求操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
目录

  • 1、添加HttpsClientRequestFactory工具类
  • 2、修改RestTemplate
  • 3、访问https,抛出的异常

    • 方案一:替换jce包
    • 方案二:升级 JDK到1.8版本(推荐方式)

方法1: 用java生成证书,不建议,移植性差。
方法2: 将RestTemplate改为https请求。

1、添加HttpsClientRequestFactory工具类
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import javax.net.ssl.*;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.Socket;
import java.security.cert.X509Certificate;
 
/**
 * TLS的三个作用:
 *  (1)身份认证
 *    通过证书认证来确认对方的身份,防止中间人攻击
 *  (2)数据私密性
 *    使用对称性密钥加密传输的数据,由于密钥只有客户端/服务端有,其他人无法窥探。
 *  (3)数据完整性
 *    使用摘要算法对报文进行计算,收到消息后校验该值防止数据被篡改或丢失。
 *   
 *   使用RestTemplate进行HTTPS请求访问:
 *  private static RestTemplate restTemplate = new RestTemplate(new HttpsClientRequestFactory());
 * 
 */
public class HttpsClientRequestFactory extends SimpleClientHttpRequestFactory {
  @Override
  protected void prepareConnection(HttpURLConnection connection, String httpMethod) {
    try {
      if (!(connection instanceof HttpsURLConnection)) {
        throw new RuntimeException("An instance of HttpsURLConnection is expected");
      }
 
      HttpsURLConnection httpsConnection = (HttpsURLConnection) connection; 
      TrustManager[] trustAllCerts = new TrustManager[]{
          new X509TrustManager() {
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
              return null;
            }
            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }
            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            } 
          }
      };
      SSLContext sslContext = SSLContext.getInstance("TLS");
      sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
      httpsConnection.setSSLSocketFactory(new MyCustomSSLSocketFactory(sslContext.getSocketFactory()));
 
      httpsConnection.setHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String s, SSLSession sslSession) {
          return true;
        }
      });
 
      super.prepareConnection(httpsConnection, httpMethod);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  private static class MyCustomSSLSocketFactory extends SSLSocketFactory { 
    private final SSLSocketFactory delegate; 
    public MyCustomSSLSocketFactory(SSLSocketFactory delegate) {
      this.delegate = delegate;
    }
 
    // 返回默认启用的密码套件。除非一个列表启用,对SSL连接的握手会使用这些密码套件。
    // 这些默认的服务的最低质量要求保密保护和服务器身份验证
    @Override
    public String[] getDefaultCipherSuites() {
      return delegate.getDefaultCipherSuites();
    }
 
    // 返回的密码套件可用于SSL连接启用的名字
    @Override
    public String[] getSupportedCipherSuites() {
      return delegate.getSupportedCipherSuites();
    } 
 
    @Override
    public Socket createSocket(final Socket socket, final String host, final int port,
                   final boolean autoClose) throws IOException {
      final Socket underlyingSocket = delegate.createSocket(socket, host, port, autoClose);
      return overrideProtocol(underlyingSocket);
    } 
 
    @Override
    public Socket createSocket(final String host, final int port) throws IOException {
      final Socket underlyingSocket = delegate.createSocket(host, port);
      return overrideProtocol(underlyingSocket);
    }
 
    @Override
    public Socket createSocket(final String host, final int port, final InetAddress localAddress,
                   final int localPort) throws
        IOException {
      final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
      return overrideProtocol(underlyingSocket);
    }
 
    @Override
    public Socket createSocket(final InetAddress host, final int port) throws IOException {
      final Socket underlyingSocket = delegate.createSocket(host, port);
      return overrideProtocol(underlyingSocket);
    }
 
    @Override
    public Socket createSocket(final InetAddress host, final int port, final InetAddress localAddress,
                   final int localPort) throws
        IOException {
      final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
      return overrideProtocol(underlyingSocket);
    }
 
    private Socket overrideProtocol(final Socket socket) {
      if (!(socket instanceof SSLSocket)) {
        throw new RuntimeException("An instance of SSLSocket is expected");
      }
      //((SSLSocket) socket).setEnabledProtocols(new String[]{"TLSv1.2"});
      ((SSLSocket) socket).setEnabledProtocols(new String[]{"TLSv1", "TLSv1.1", "TLSv1.2"});
      return socket;
    }
  }
}
注意:服务端TLS版本要和客户端工具类中定义的一致。(TLSv1.2)

2、修改RestTemplate
在使用的时候,将
private static RestTemplate restTemplate = new RestTemplate();
改为:
private static RestTemplate restTemplate = new RestTemplate(new HttpsClientRequestFactory());
其他代码不变。
也可使用注入的方式:
@Configuration
public class ConfigBean {
 @Bean
 public RestTemplate getRestTemplate() {
  return new RestTemplate(new HttpsClientRequestFactory());
 }
}
3、访问https,抛出的异常
javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure解决方案
因为jdk中jce的安全机制导致报的错,需要去oracle官网下载对应的jce包替换jdk中的jce包。

方案一:替换jce包
目录 %JAVA_HOME%\jre\lib\security里的local_policy.jar,US_export_policy.jar
JDK7 http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
JDK8 http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html
 
// pub1:/home/myron/jdk1.7.0_80 % cd $JAVA_HOME/jre/lib/security/  //jce所在jdk的路径
US_export_policy.jar
local_policy.jar
方案二:升级 JDK到1.8版本(推荐方式)
// pub1:/home/myron % vi .cshrc
setenv JAVA_HOME /home/myron/jdk1.8.0_211
// pub1:/home/myron % source .cshrc
// pub1:/home/myron % java -version
java version "1.8.0_211"
以上为个人经验,希望能给大家一个参考,也希望大家多多支持CodeAE代码之家
原文链接:https://blog.csdn.net/MyronCham/article/details/103481046

关注下面的标签,发现更多相似文章