当服务器端因安全需要,网站升级了 https SSL TLSv1.2版本时,可能会出问题,之前客户端好好的Java代码,为什么突然会报错呢?

前段时间,米扑代理的支付,升级了PayPal 所强制需要的 https SSL TLSv1.2 后,有客户反馈之前的Java无法提取,详见:PayPal:SSL connect error 解决方案

这是因为服务器端升级了,但是客户端的代码 jdk1.6不支持TLSv1.2协议,jdk1.8默认支持TLSv1.2

比较好的解决方案是客户端升级JDK为 1.8 以上版本,但是升级jdk风险极大。

不能升级jdk的情况下,可以使用第三方jar库来解决。

 

场景 

Java程序使用https方式调用nessus接口时,使用 jdk1.7 返回如下内容:

Java代码:

SSLContext sc = SSLContext.getInstance("SSL");

SSLContext sc = SSLContext.getInstance("SSL","SunJSSE"); 

报错提示:

javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?

 

使用 jdk1.8 返回正常

{"token":"f360654233f65d964ed220914ec10916fe206a3d1b1c1b41"}  

 

使用浏览器访问正常,debug发现发现:

协议版本:TLSv1.2  
密码组合:TLS_RSA_WITH_AES_128_CBC_SHA 

 

原因是 jdk1.7 默认不支持 TLSv1.2jdk1.8 默认支持 TLSv1.2浏览器一般都支持 TLSv1.2

如上图,已经给出了jdk各个版本的默认值,jdk1.7默认支持TLSv1 ,jdk1.8默认支持TLSv1.2

 

1、升级JDK 1.8,满足默认的 SSL TLSv1.2

 

2、JDK 1.7 简单解决方案

解决jdk1.7 不支持TLS1.2的问题,这个问题是在服务器端的生产环境调整之后出现的,因为之前客户端访问 https(ssl)是好使的,后来又一天突然不好使了,查看日志发现代码抛异常,感觉是没有连接上服务器,但是其他环境是好使的,有点疑惑,分析后发现可能是ssl的协议问题,所以观察了下Nginx的配置,发现米扑科技的运维基于公司安全机制的升级,将ssl_protocols 从 TLSv1.1 TLSv1.0 升级到了 TLSv1.2; 然后查了下资料,发现jdk的各个版本对ssl协议的默认支持是不一样的,如上图所示。

问题的原因,说白了用的是当前JDK版本的默认协议,当前用的是JDK1.7,默认使用的是TLSv1.0,虽然JDK1.7也支持TLSv1.2 TLSv1.1但是默认使用的并不是这两个,因此我这边调整了下代码,用三种协议挨个去连接,谁链接成功就用谁,代码如下:

if (buildHttpsConn(map, "TLSv1") || buildHttpsConn(map, "TLSv1.1")|| buildHttpsConn(map, "TLSv1.2")) {
	            		
	// 获取封装在map中的链接对象
	httpsConn = (HttpsURLConnection) map.get("httpsConn");
	
	// 取得该连接的输入流,以读取响应内容
    insr = new InputStreamReader(httpsConn.getInputStream());
    
    // 读取服务器的响应内容并显示
    int respInt;
    respInt = insr.read();
    while (respInt != -1){
        sb.append((char) respInt);
        respInt = insr.read();
    }
    data = sb.toString();
}

/**
 * 获取httpsConn链接
 * @param map (url,httpsConn)
 * @param protocol 协议
 * @return
 */
private boolean buildHttpsConn(Map<String, Object> map, String protocol){
	try {
		URL url = (URL) map.get("url");
		
		// 创建SSLContext对象,并使用我们指定的信任管理器初始化
        TrustManager[] tm = {new MyX509TrustManager ()}; 
        SSLContext sslContext = SSLContext.getInstance(protocol); 			// 判断协议类型
        sslContext.init(null, tm, new java.security.SecureRandom()); 

        // 从上述SSLContext对象中得到SSLSocketFactory对象
        SSLSocketFactory ssf = sslContext.getSocketFactory();

        // 创建HttpsURLConnection对象,并设置其SSLSocketFactory对象
        HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection();
        
        // 创建HttpsURLConnection对象,并设置其SSLSocketFactory对象
        httpsConn.setSSLSocketFactory(ssf);
        
        LOGGER.info("开始建立https链接使用{}协议", protocol);
        httpsConn.getResponseCode();
        map.put("httpsConn", httpsConn);
	} catch (Exception e) {
		LOGGER.error("建立https链接使用{}协议无效!", protocol);
		return false;
	}
	return true;
}

 

 

3、JDK1.7、JDK1.6 第三方jar包的通用解决方案

解决方案使用第三方的Bouncy Castle  代码如下:

1、建立一个TLSSocketConnectionFactory

import java.io.ByteArrayInputStream;  
import java.io.ByteArrayOutputStream;  
import java.io.DataOutputStream;  
import java.io.FileInputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.OutputStream;  
import java.net.InetAddress;  
import java.net.InetSocketAddress;  
import java.net.Socket;  
import java.net.UnknownHostException;  
import java.security.KeyStore;  
import java.security.Principal;  
import java.security.SecureRandom;  
import java.security.Security;  
import java.security.cert.CertificateExpiredException;  
import java.security.cert.CertificateFactory;  
import java.util.Hashtable;  
import java.util.LinkedList;  
import java.util.List;  
  
import javax.net.ssl.HandshakeCompletedListener;  
import javax.net.ssl.SSLPeerUnverifiedException;  
import javax.net.ssl.SSLSession;  
import javax.net.ssl.SSLSessionContext;  
import javax.net.ssl.SSLSocket;  
import javax.net.ssl.SSLSocketFactory;  
import javax.security.cert.X509Certificate;  
  
import org.bouncycastle.crypto.tls.*;  
import org.bouncycastle.crypto.tls.Certificate;  
import org.bouncycastle.jce.provider.BouncyCastleProvider;  
  
/** 
 * Created by in 2016-09-09
 * https://blog.mimvp.com 
 */  
public class TLSSocketConnectionFactory extends SSLSocketFactory {  
  
    static {  
        if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {  
            Security.addProvider(new BouncyCastleProvider());  
        }  
    }  
  
    @Override  
    public Socket createSocket(Socket socket, final String host, int port, boolean arg3) throws IOException {  
        if (socket == null) {  
            socket = new Socket();  
        }  
        if (!socket.isConnected()) {  
            socket.connect(new InetSocketAddress(host, port));  
        }  
  
        final TlsClientProtocol tlsClientProtocol = new TlsClientProtocol(socket.getInputStream(), socket.getOutputStream(), new SecureRandom());  
  
        return _createSSLSocket(host, tlsClientProtocol);  
    }  
  
    @Override  
    public String[] getDefaultCipherSuites() {  
        return null;  
    }  
  
    @Override  
    public String[] getSupportedCipherSuites() {  
        return null;  
    }  
  
    @Override  
    public Socket createSocket(String host, int port) throws IOException, UnknownHostException {  
        throw new UnsupportedOperationException();  
    }  
  
    @Override  
    public Socket createSocket(InetAddress host, int port) throws IOException {  
        throw new UnsupportedOperationException();  
    }  
  
    @Override  
    public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {  
        return null;  
    }  
  
    @Override  
    public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {  
        throw new UnsupportedOperationException();  
    }  
  
    private SSLSocket _createSSLSocket(final String host, final TlsClientProtocol tlsClientProtocol) {  
        return new SSLSocket() {  
            private java.security.cert.Certificate[] peertCerts;  
  
            @Override  
            public InputStream getInputStream() throws IOException {  
                return tlsClientProtocol.getInputStream();  
            }  
  
            @Override  
            public OutputStream getOutputStream() throws IOException {  
                return tlsClientProtocol.getOutputStream();  
            }  
  
            @Override  
            public synchronized void close() throws IOException {  
                tlsClientProtocol.close();  
            }  
  
            @Override  
            public void addHandshakeCompletedListener(HandshakeCompletedListener arg0) {  
            }  
  
            @Override  
            public boolean getEnableSessionCreation() {  
                return false;  
            }  
  
            @Override  
            public String[] getEnabledCipherSuites() {  
                return null;  
            }  
  
            @Override  
            public String[] getEnabledProtocols() {  
                return null;  
            }  
  
            @Override  
            public boolean getNeedClientAuth() {  
                return false;  
            }  
  
            @Override  
            public SSLSession getSession() {  
                return new SSLSession() {  
  
                    @Override  
                    public int getApplicationBufferSize() {  
                        return 0;  
                    }  
  
                    @Override  
                    public String getCipherSuite() {  
                        throw new UnsupportedOperationException();  
                    }  
  
                    @Override  
                    public long getCreationTime() {  
                        throw new UnsupportedOperationException();  
                    }  
  
                    @Override  
                    public byte[] getId() {  
                        throw new UnsupportedOperationException();  
                    }  
  
                    @Override  
                    public long getLastAccessedTime() {  
                        throw new UnsupportedOperationException();  
                    }  
  
                    @Override  
                    public java.security.cert.Certificate[] getLocalCertificates() {  
                        throw new UnsupportedOperationException();  
                    }  
  
                    @Override  
                    public Principal getLocalPrincipal() {  
                        throw new UnsupportedOperationException();  
                    }  
  
                    @Override  
                    public int getPacketBufferSize() {  
                        throw new UnsupportedOperationException();  
                    }  
  
                    @Override  
                    public X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException {  
                        return null;  
                    }  
  
                    @Override  
                    public java.security.cert.Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException {  
                        return peertCerts;  
                    }  
  
                    @Override  
                    public String getPeerHost() {  
                        throw new UnsupportedOperationException();  
                    }  
  
                    @Override  
                    public int getPeerPort() {  
                        return 0;  
                    }  
  
                    @Override  
                    public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {  
                        return null;  
                    }  
  
                    @Override  
                    public String getProtocol() {  
                        throw new UnsupportedOperationException();  
                    }  
  
                    @Override  
                    public SSLSessionContext getSessionContext() {  
                        throw new UnsupportedOperationException();  
                    }  
  
                    @Override  
                    public Object getValue(String arg0) {  
                        throw new UnsupportedOperationException();  
                    }  
  
                    @Override  
                    public String[] getValueNames() {  
                        throw new UnsupportedOperationException();  
                    }  
  
                    @Override  
                    public void invalidate() {  
                        throw new UnsupportedOperationException();  
                    }  
  
                    @Override  
                    public boolean isValid() {  
                        throw new UnsupportedOperationException();  
                    }  
  
                    @Override  
                    public void putValue(String arg0, Object arg1) {  
                        throw new UnsupportedOperationException();  
                    }  
  
                    @Override  
                    public void removeValue(String arg0) {  
                        throw new UnsupportedOperationException();  
                    }  
                };  
            }  
  
            @Override  
            public String[] getSupportedProtocols() {  
                return null;  
            }  
  
            @Override  
            public boolean getUseClientMode() {  
                return false;  
            }  
  
            @Override  
            public boolean getWantClientAuth() {  
                return false;  
            }  
  
            @Override  
            public void removeHandshakeCompletedListener(HandshakeCompletedListener arg0) {  
            }  
  
            @Override  
            public void setEnableSessionCreation(boolean arg0) {  
            }  
  
            @Override  
            public void setEnabledCipherSuites(String[] arg0) {  
            }  
  
            @Override  
            public void setEnabledProtocols(String[] arg0) {  
            }  
  
            @Override  
            public void setNeedClientAuth(boolean arg0) {  
            }  
  
            @Override  
            public void setUseClientMode(boolean arg0) {  
            }  
  
            @Override  
            public void setWantClientAuth(boolean arg0) {  
            }  
  
            @Override  
            public String[] getSupportedCipherSuites() {  
                return null;  
            }  
  
            @Override  
            public void startHandshake() throws IOException 
            {  
                tlsClientProtocol.connect(new DefaultTlsClient() {  
  
                    @SuppressWarnings("unchecked")  
                    @Override  
                    public Hashtable<Integer, byte[]> getClientExtensions() throws IOException {  
                        Hashtable<Integer, byte[]> clientExtensions = super.getClientExtensions();  
                        if (clientExtensions == null) {  
                            clientExtensions = new Hashtable<Integer, byte[]>();  
                        }  
  
                        //Add host_name  
                        byte[] host_name = host.getBytes();  
  
                        final ByteArrayOutputStream baos = new ByteArrayOutputStream();  
                        final DataOutputStream dos = new DataOutputStream(baos);  
                        dos.writeShort(host_name.length + 3);  
                        dos.writeByte(0);  
                        dos.writeShort(host_name.length);  
                        dos.write(host_name);  
                        dos.close();  
                        clientExtensions.put(ExtensionType.server_name, baos.toByteArray());  
                        return clientExtensions;  
                    }  
  
                    @Override  
                    public TlsAuthentication getAuthentication() throws IOException {  
                        return new TlsAuthentication() {  
                            @Override  
                            public void notifyServerCertificate(Certificate serverCertificate) throws IOException {  
                                try {  
                                    KeyStore ks = _loadKeyStore();  
  
                                    CertificateFactory cf = CertificateFactory.getInstance("X.509");  
                                    List<java.security.cert.Certificate> certs = new LinkedList<java.security.cert.Certificate>();  
                                    boolean trustedCertificate = false;  
                                    for (org.bouncycastle.asn1.x509.Certificate c : ((org.bouncycastle.crypto.tls.Certificate) serverCertificate).getCertificateList()) {  
                                        java.security.cert.Certificate cert = cf.generateCertificate(new ByteArrayInputStream(c.getEncoded()));  
                                        certs.add(cert);  
  
                                        String alias = ks.getCertificateAlias(cert);  
                                        if (alias != null) {  
                                            if (cert instanceof java.security.cert.X509Certificate) {  
                                                try {  
                                                    ((java.security.cert.X509Certificate) cert).checkValidity();  
                                                    trustedCertificate = true;  
                                                } catch (CertificateExpiredException cee) {  
                                                    // Accept all the certs!  
                                                }  
                                            }  
                                        } else {  
                                            // Accept all the certs!  
                                        }  
  
                                    }  
                                    if (!trustedCertificate) {  
                                        // Accept all the certs!  
                                    }  
                                    peertCerts = certs.toArray(new java.security.cert.Certificate[0]);  
                                } catch (Exception ex) {  
                                    ex.printStackTrace();  
                                    throw new IOException(ex);  
                                }  
                            }  
  
                            @Override  
                            public TlsCredentials getClientCredentials(CertificateRequest certificateRequest) throws IOException {  
                                return null;  
                            }  
  
                            private KeyStore _loadKeyStore() throws Exception {  
                                FileInputStream trustStoreFis = null;  
                                try {  
                                    KeyStore localKeyStore = null;  
  
                                    String trustStoreType = System.getProperty("javax.net.ssl.trustStoreType") != null ? System.getProperty("javax.net.ssl.trustStoreType") : KeyStore.getDefaultType();  
                                    String trustStoreProvider = System.getProperty("javax.net.ssl.trustStoreProvider") != null ? System.getProperty("javax.net.ssl.trustStoreProvider") : "";  
  
                                    if (trustStoreType.length() != 0) {  
                                        if (trustStoreProvider.length() == 0) {  
                                            localKeyStore = KeyStore.getInstance(trustStoreType);  
                                        } else {  
                                            localKeyStore = KeyStore.getInstance(trustStoreType, trustStoreProvider);  
                                        }  
  
                                        char[] keyStorePass = null;  
                                        String str5 = System.getProperty("javax.net.ssl.trustStorePassword") != null ? System.getProperty("javax.net.ssl.trustStorePassword") : "";  
  
                                        if (str5.length() != 0) {  
                                            keyStorePass = str5.toCharArray();  
                                        }  
  
                                        localKeyStore.load(trustStoreFis, keyStorePass);  
  
                                        if (keyStorePass != null) {  
                                            for (int i = 0; i < keyStorePass.length; i++) {  
                                                keyStorePass[i] = 0;  
                                            }  
                                        }  
                                    }  
                                    return localKeyStore;  
                                } finally {  
                                    if (trustStoreFis != null) {  
                                        trustStoreFis.close();  
                                    }  
                                }  
                            }  
  
                        };  
                    }  
  
                });  
            } // startHandshake  
        };  
    }  
}  

 

2、发送一个map格式的post请求

import javax.net.ssl.HttpsURLConnection;  
import com.alibaba.fastjson.JSON;  
import java.io.BufferedReader;  
import java.io.DataOutputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.InputStreamReader;  
import java.io.OutputStreamWriter;  
import java.net.HttpURLConnection;  
import java.net.URI;  
import java.net.URISyntaxException;  
import java.net.URL;  
import java.net.URLConnection;  
  
  
public class HttpsUrlConnectionForTLS {  
    public HttpURLConnection createConnection(URI uri) throws IOException {  
        URL url = uri.toURL();  
        URLConnection connection = url.openConnection();  
        HttpsURLConnection httpsURLConnection = (HttpsURLConnection) connection;  
        httpsURLConnection.setSSLSocketFactory(new TLSSocketConnectionFactory());  
        return httpsURLConnection;  
    }  
      
    public static void main(String[] args) {  
        HttpsUrlConnectionForTLS httpsUrlConnectionMessageSender = new HttpsUrlConnectionForTLS();  
        String loginUrl = "https://192.168.186.73/session";  
        String data = "username=xiaomi&password=Ultrasafe_123";  
        HttpURLConnection connection;  
        try {  
            connection = httpsUrlConnectionMessageSender.createConnection(new URI(loginUrl ));  
            connection.setDoOutput(true);  
            connection.setDoInput(true);  
            connection.setRequestMethod("POST");  
            connection.setUseCaches(false);  
            connection.setInstanceFollowRedirects(true);  
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");  
  
            connection.connect();  
            //POST请求  
            OutputStreamWriter os = null;  
            String json="";  
            os = new OutputStreamWriter(connection.getOutputStream());  
            os.write(data);  
            os.flush();  
            json=getResponse(connection);  
            System.out.println(json);  
  
   
            if (connection != null) {  
          		connection.disconnect();  
            }  
        } catch (IOException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (URISyntaxException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
    }  
      
    public static String getResponse(HttpURLConnection Conn) throws IOException {  
        InputStream is;  
        if (Conn.getResponseCode() >= 400) {  
            is = Conn.getErrorStream();  
        } else {  
            is = Conn.getInputStream();  
        }  
  
        String response = "";  
        byte buff[] = new byte[512];  
        int b = 0;  
        while ((b = is.read(buff, 0, buff.length)) != -1) {  
            response += new String(buff, 0, b);  
  
        }  
        is.close();  
  
        System.out.println(response);  
        return response;  
    }  
}  

 

以上代码,需要用到的 jar 包,请到米扑博客的百度网盘下载

百度网盘:bcprov-ext-jdk15on-154.jar (密码:pc38)

解决 javax.net.ssl.SSLException: java.lang.RuntimeException: Could not generate DH keypair 异常所需jar包

 

 

4、jar包执行时,添加执行参数  -Dhttps.protocols=TLSv1.1,TLSv1.2

示例: java -jar yourapplication.jar -Dhttps.protocols=TLSv1.2

或者 somewhere in the application (server) configuration files. You can verify if it works by adding additional param: -Djavax.net.debug=all

详见 Enable TLS 1.1 and 1.2 for Clients on Java 7

 

 

参考推荐

Enable TLS 1.1 and 1.2 for Clients on Java 7

PayPal:SSL connect error 解决方案