Java SSL Socket communication example, sslsocket

Source: Internet
Author: User

Java SSL Socket communication example, sslsocket

As mentioned in the previous article "OpenSSL and KeyStore instruction Collection", the recent research on SSL encryption will provide a small Java example. Copying a piece of code that can be run to production is very irresponsible, but small examples can take us to get started and quickly see the essence of things. Rome was not built in one day.

This article provides a small Java SSL Socket example, including Server and Client. I hope you will study the relevant materials and understand the basic concepts after getting started. The advantage of Java is that it is completely encapsulated and requires less intervention. The disadvantage is that with the upgrade and Development of Java, many new concepts and classes will emerge, make it clear that it takes a lot of effort, and the amount of code is also relatively large (production-level code ).

Code

In the simplest way, you only need to configure several system attributes in Java and create and call several SSL-related objects. These four attributes are:

  • Javax.net. ssl. keyStore
    The Local Password, certificate, and other storage locations (KeyStore file address ).
  • Javax.net. ssl. keyStorePassword
    The password of the KeyStore. You can leave it empty without a password.
  • Javax.net. ssl. trustStore
    The location where the trusted certificate is stored (the TrustKeyStore file address ).
  • Javax.net. ssl. trustStorePassword
    The password of the TrustKeyStore. You can leave it empty without a password.

The default KeyStore type is JKS. Otherwise, you must set javax.net. ssl. keyStoreType and javax.net. ssl. trustStoreType.

Server code

Each time a new connection is received, a new thread reception is opened. Use thread pools and other technologies in production. We recommend that you use Netty or Mina.

Public class SslServer {public static void main (String [] args) throws Exception {System. setProperty ("javax.net. debug "," ssl, handshake "); System. setProperty ("javax.net. ssl. keyStore ",". /cfg/server. jks "); System. setProperty ("javax.net. ssl. keyStorePassword "," 123456 "); System. setProperty ("javax.net. ssl. trustStore ",". /cfg/clienttrust. jks "); System. setProperty ("javax.net. ssl. trustStorePassword "," 123456 "); SSLServerSocketFactory serverSocketFactory = (SSLServerSocketFactory) SSLServerSocketFactory. getDefault (); SSLServerSocket serverSocket = (SSLServerSocket) serverSocketFactory. createServerSocket (9100); // client authentication is required. setNeedClientAuth (true); while (true) {SSLSocket socket = (SSLSocket) serverSocket. accept (); Accepter accepter = new Accepter (socket); accepter. service () ;}} static class Accepter Implements Runnable {private SSLSocket socket; public Accepter (SSLSocket socket) {this. socket = socket;} public void service () {Thread thread = new Thread (this); thread. start () ;}@ Overridepublic void run () {try {InputStream inputStream = socket. getInputStream (); InputStreamReader inputstreamreader = new InputStreamReader (inputStream); BufferedReader bufferedreader = new BufferedReader (inputstreamreader); String string = null; while (string = bufferedreader. readLine ())! = Null) {System. out. println (string); System. out. flush () ;}} catch (Exception e) {// replace with other codee. printStackTrace ();}}}}
Client code

Establish a connection and send a message to the Server. Very simple. Remember the line break and call the flush method.

Public class SslClient {public static void main (String [] args) throws Exception {System. setProperty ("javax.net. debug "," ssl, handshake "); System. setProperty ("javax.net. ssl. keyStore ",". /cfg/client. jks "); System. setProperty ("javax.net. ssl. keyStorePassword "," 123456 "); System. setProperty ("javax.net. ssl. trustStore ",". /cfg/servertrust. jks "); System. setProperty ("javax.net. ssl. trustStorePassword "," 123456 "); SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory. getDefault (); SSLSocket sslsocket = (SSLSocket) sslsocketfactory. createSocket ("127.0.0.1", 9100); OutputStream outputStream = sslsocket. getOutputStream (); BufferedWriter bufferedWriter = new BufferedWriter (new OutputStreamWriter (outputStream); bufferedWriter. write ("Sleeping Lion \ n"); bufferedWriter. flush (); TimeUnit. SECONDS. sleep (2000 );}}
Conclusion

JDK later added the SSLEngine class, which has the ability of asynchronous communication. But read the official documentation and the code is very long. In other words, it is recommended that Netty or Mina be used for communication, which is better than self-writing.

Java official SSL Socket documentation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.