1. 程式人生 > >解決JDK1.7,1.6不支援TLS1.2的問題

解決JDK1.7,1.6不支援TLS1.2的問題

開發過程中用JDK遇到ssl peer shut down incorrectly這個錯誤,是因為JDK1.8預設是TLS1.2

解決辦法:

建立一個TLSSocketConnectionFactory,利用這個工具類,再寫相關POST,GET方法就OK了

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 hzlizhou on 2016/9/9.
 */
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
        };
    }
}
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;
    }
}


相關推薦

解決JDK1.7,1.6支援TLS1.2的問題

開發過程中用JDK遇到ssl peer shut down incorrectly這個錯誤,是因為JDK1.8預設是TLS1.2解決辦法:建立一個TLSSocketConnectionFactory,利用這個工具類,再寫相關POST,GET方法就OK了import java.

github支援tls1.1導致egit cannot open git-upload-pack

【前言】 本文可以當小說看,懸疑小說。 【起因】 過年後開始上班,大概是2.22開始上班,到昨天2.25發現問題, myeclipse的egit不能clone和pull github上的專案了。 報錯資訊cannot open git-upload-pack, 2.25的時候

centos 6.5下編譯安裝php-7.1.6和 php memcached擴展

php 編譯安裝 memcached 0,安裝 php-7.1.6 依賴包# yum groupinstall "Development tools" "Desktop Platform Development" # yum -y install openssl-devel libcurl-dev

(hdu step 7.1.6)最大三角形(凸包的應用——在n個點中找到3個點,它們所形成的三角形面積最大)

三角形 struct names com 都在 acm sni 都是 tran 題目:最大三角形Time Limit: 5000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total S

7.1.6 DOM對象屬性操作

move ons console tel doc get att ole elements prop() removeProp() $(function(){   //js對input單選按鈕checked的默認設置   //console.log($(‘input[

ArrayList實現原理以及原始碼解析(補充JDK1.7,1.8)

ArrayList實現原理以及原始碼解析(補充JDK1.7,1.8) ArrayList的基本知識在上一節已經討論過,這節主要看ArrayList在JDK1.6到1.8的一些實現變化。 JDK版本不一樣,ArrayList類的原始碼也不一樣。 1、ArrayList類結構:

解決CentOS 7.1版本以上安裝好zabbix 3.4 無法重啟zabbix-server的問題

1. 問題所在 報錯資訊:zabbix_server[46512]: segfault at 18 ip 00007f78842b4bd0 sp 00007fff1995a818 error 4 in libpthread-2.17.so[7f78842ab000+16000] 2. 產生原

android 7.1到 ll (ls -l)命令

平臺 rk3288 + android 7.12 描述 在使用android 5.1 時, 在adb shell 下, 可以使用ls 和 ll 命令, 但在7.1中, 發現 ll 命令無法使用: /system/bin/sh: ll: not found 分析 在lin

Apache Flink 1.7.0 釋出,支援 Scala 2.12

Apache Flink 1.7.0 已釋出,Apache Flink 是一個開源的流處理框架,應用於分散式、高效能、始終可用的、準確的資料流應用程式。 新特性和改進: 支援 Scala 2.12 State Evolution:現在能夠更靈活地調整長時間執行的應用的使用者狀態模式,同時保持與先

hdu step 7 1 6 最大三角形 凸包的應用——在n個點中找到3個點 它們所形成的三角形面積最大

                題目:最大三角形Time Limit: 5000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 121 Accepted Submission(s): 61

解決瀏覽器或移動端支援小於12px的字型

字型大小 <style> //方法一 .setSize{ font-size: 10px; transform: scale(0.7); display: inline-block;

.finally is not a function —— 解決低版本瀏覽器axios支援finally

框架專案用axios呼叫介面時,我們常用:介面名().then(result=>{ do sth... }).catch(()=>{ do sth... }).finally

ClusterControl 1.7.1 釋出,支援 PostgreSQL 11 和 MongoDB 4.0

   ClusterControl 1.7.1 釋出了,ClusterControl 是一個數據庫的叢集控制程式,支援 MySQL、PostgreSQL 和 MongoDB。 更新內容如下: 效能方面 增強的MySQL、Galera Cluster、Postgre

openssh升級到7.9p1導致securecrt 7.1上的問題

今天我登入一臺伺服器,看著openssh版本有點兒低,手賤給升級到openssh7.9p1版,然後有人反饋連不上了,問我是不是把他key刪了,這不可能啊,我沒動那些。網上基本都是說,securecrt什麼加密方法過時啥的,客戶端是7.1啊!低什麼低。自己拿虛機試驗終於發現問題了。securecrt客戶端生成的

JDK1.7&1.8HashMap不同

摘要 HashMap是Java程式設計師使用頻率最高的用於對映(鍵值對)處理的資料型別。隨著JDK(Java Developmet Kit)版本的更新,JDK1.8對HashMap底層的實現進行了優化,例如引入紅黑樹的資料結構和擴容的優化等。本文結合JDK1.7和JDK

CentOS-解決CentOS 7 history命令顯示操作記錄的時間和使用者身份問題

[[email protected] data]# history 10   1273  2017-01-05 19:40:18  root history  1274  2017-01-05 19:40:27  root clear  1275  2017-01-05 19:40:29  root

關於Android4.x系統支援TLS1.2解決方案

為Http請求的網路客戶端設定一個特殊的SSLSocketFactory。 這個代理SSLSocketFactory在建立一個Socket連線的時候,會設定Socket的可用的TLS版本。 private static final String[] TLS_

《React-Native系列》21、 解決RN在Android下支援gif問題

由於RN在Android平臺上不支援gif格式的圖片,今天介紹下我們是怎麼處理這個問題的。 先來看看我們需要實現的效果,這是一張gif圖片,當我們列表上拉載入下一頁的時候需要使用這個效果,如下圖: 我們的解決方案是:將gif切成15張png的圖片,暫且命名為loadin

解決document.formname.submit()物件支援此屬性或方法的辦法

今天在工作中,遇到了一個小問題,提示document.formname.submit()物件不支援此屬性或方法的檔案 原因:在formname中有個name=submit的設定,指令碼執行時吧submit()當成了屬性,所以報錯了 方法:將name=submit 重新命名

jdk1.7 1.8新特性

轉自:http://www.2cto.com/kf/201307/225968.html 本文是我學習瞭解了jdk7和jdk8的一些新特性的一些資料,有興趣的大家可以瀏覽下下面的內容。 官方文件:http://www.oracle.com/technetwork/java