1. 程式人生 > >java程式碼實現SSL單向認證(cer crt公鑰)

java程式碼實現SSL單向認證(cer crt公鑰)

這裡的程式碼主要是和mqtt一起連用,使用的證書是mqttserver.crt

public static final String caPath = "mqttserver.crt";

public SSLSocketFactory getSSLSocktet() throws Exception {		
		// CA certificate is used to authenticate server
		CertificateFactory cAf = CertificateFactory.getInstance("X.509");
		FileInputStream caIn = new FileInputStream(caPath);
		X509Certificate ca = (X509Certificate) cAf.generateCertificate(caIn);
		KeyStore caKs = KeyStore.getInstance("JKS");
		caKs.load(null, null);
		caKs.setCertificateEntry("ca-certificate", ca);
		TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
		tmf.init(caKs);    		
		
		// finally, create SSL socket factory
		SSLContext context = SSLContext.getInstance("TLSv1");
		context.init(null, tmf.getTrustManagers(), new SecureRandom());

		return context.getSocketFactory();
	}

mqtt使用SSL認證程式碼:

public void mqttTest(){
        MqttConnectOptions conOpt = new MqttConnectOptions();
        //網址:https://www.ibm.com/support/knowledgecenter/SSFKSJ_7.5.0/com.ibm.mq.javadoc.doc/WMQMQxrClasses/org/eclipse/paho/client/mqttv3/MqttConnectOptions.html
        //是否自動重新連線
        conOpt.setAutomaticReconnect(false);
        //設定伺服器是否應該在重新連線時記住客戶端的狀態。
        conOpt.setCleanSession(this.cleanSession);
        if (password != null) {
            //設定用於連線的賬戶
            conOpt.setPassword(this.password.toCharArray());
        }
        if (userName != null) {
            //設定用於連線的密碼
            conOpt.setUserName(this.userName);
        }
        //設定保持活躍間隔(心跳時間,單位秒)
        conOpt.setKeepAliveInterval(60);
        //設定超時時間
        conOpt.setConnectionTimeout(30);
        //設定要使用的socketFactory;這允許應用程式圍繞建立網路套接字應用自己的策略,如果使用SSL連線,則可以使用SSLSocketFactory提供特定於應用程式的安全策略。
        conOpt.setSocketFactory(getSSLSocket());
        
    }