如何做ssl socket编程 [英] how to do ssl socket programming

查看:105
本文介绍了如何做ssl socket编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过以下IP地址进行套接字通信但是我不想在ssl模式下进行通信但是如何更改 InetAddress serverAddr = InetAddress.getByName(192.168.1.2); 来SSL

I am doing socket communication through follwing IP address it working but no i want to do communication in ssl mode but how can I change InetAddress serverAddr = InetAddress.getByName("192.168.1.2"); to SSL.

public class TCPClient implements Runnable {

    public void run() {

     try {

         InetAddress serverAddr = InetAddress.getByName("192.168.1.2");

             Log.d("TCP", "C: Connecting...");

             Socket socket = new Socket(serverAddr,12345);

             String message = "Hello from Client android emulator";
              try {

                     Log.d("TCP", "C: Sending: '" + message + "'");

                     PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);

                     out.println(message);

                     Log.d("TCP", "C: Sent.");

                 Log.d("TCP", "C: Done.");



         } catch(Exception e) {

             Log.e("TCP", "S: Error", e);
                 } finally {

                    socket.close();

                  }
     } catch (Exception e) {

          Log.e("TCP", "C: Error", e);

     }

}

}


推荐答案

创建 SSLSocket 而不是Socket。休息是一样的。

Create SSLSocket instead of Socket. Rest is the same.

SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket("192.168.1.2", 12345);

您可能想要添加aditional SSL属性。您必须执行此操作:

You may want to add aditional SSL properties. You have to do it ealier:

要对服务器进行身份验证,客户端的信任存储区必须包含服务器的证书。具有服务器身份验证的客户端SSL由URL属性ssl或设置为peerAuthentication的属性ssl启用。此外,需要设置系统属性javax.net.ssl.trustStore和javax.net.ssl.trustStorePassword。:

To authenticate the server, the client's trust store must contain the server's certificate. Client SSL with server authentication is enabled by the URL attribute ssl or the property ssl set to peerAuthentication. In addition, the system properties javax.net.ssl.trustStore and javax.net.ssl.trustStorePassword need to be set.:

System.setProperty("javax.net.ssl.trustStore","clientTrustStore.key");
System.setProperty("javax.net.ssl.trustStorePassword","qwerty");

如果服务器进行客户端身份验证,客户端将需要密钥对和客户端证书:

If the server does client authentication, the client will need a key pair and a client certificate:

System.setProperty("javax.net.ssl.keyStore","clientKeyStore.key");
System.setProperty("javax.net.ssl.keyStorePassword","qwerty");

这篇关于如何做ssl socket编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆