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());
        
    }

 

你可能感兴趣的:(java)