Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

java - how to do ssl socket programming

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

     }

}

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Create SSLSocket instead of Socket. Rest is the same.

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

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

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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...