Use SSL to Build Secure Sockets

Source: Internet
Author: User
Use SSL to Build Secure Sockets

Original bromon Copyright

SSL (Secure Sockets Layer) was developed by Netscape in 1994 and was originally used in Web browsers to provide security for data transmission between browsers and servers, provides encryption, source authentication, and data integrity. SSL3.0 is now widely used, and its transport layer TLS (Transport Layer Security) has become the Internet standard. SSL itself is very similar to TCP socket connections. In the protocol stack, SSL can be simply considered as a secure TCP connection, but it does not support some TCP connection features, for example, out-of-bound ).

When building a socket-based c/s program, it is a good way to ensure data security and integrity by adding SSL support. The complete Java provides us with a simple implementation method: JSSE (Java Secure Socket Extension ). JSSE is a Java-only SSL and TLS Protocol framework. It abstracts complex SSL and TLS algorithms to simplify security. JSSE has become a standard component in j2se1.4 and supports SSL 3.0 and TLS 1.0. We will use a specific example to demonstrate some basic applications of JSSE. In this example, the server opens an SSL socket, and only the client that holds the specified certificate can connect to it. All data transmission is encrypted.

Constructing an sslsocket is very simple:

Sslserversocketfactory factory = (sslserversocketfactory) sslserversocketfactory. getdefault ();
Sslserversocket Server = (sslserversocket) Factory. createserversocket (portnumber );
Sslsocket socket = (sslsocket );

However, executing such a program causes an exception and the report cannot find a trusted certificate. Sslsocket is different from a common socket. It requires a certificate for security authentication.

I. Certificate

Generate a CA certificate and run the following command on the command line:

Keytool-genkey-keystore sslkey-keyalg RSA-alias SSL

The simhei part is a parameter that you can specify by yourself. The first parameter is the name of the certificate to be generated, and the second parameter is the certificate alias. RSA indicates the encryption method we use.

The system will require you to enter the information of the issuer of the certificate, which can be entered one by one, for example:

The file generated by the system will have the same name as the certificate. The certificate can be submitted to an authoritative CA Certification Organization for review. If the certificate is approved, the Organization will provide a trust guarantee to assure the customer that your connection is secure. Of course this is not necessary. In our example, the certificate is directly packaged into the client program to ensure that the client is an authorized user and avoid forging the customer, so it does not need to be submitted for review.

Ii. Server Side

Now you can write the server code. Unlike the common socket code, we need to import the certificate in the program and use the certificate to construct sslsocket. It must be noted that:

● Keystore Ks = keystore. getinstance ("jks ");

Access the Java keystore. jks is the Java keystore created by keytool and stores the keystore.

● Keymanagerfactory kmf = keymanagerfactory. getinstance ("sunx509 ");

Create an X.509 key manager for managing the jks keystore.

● Sslcontext = sslcontext. getinstance ("SSLv3 ");

Build an SSL environment, specify the SSL version as 3.0, or use tlsv1, but SSLv3 is more commonly used.

● Sslcontext. INIT (kmf. getkeymanagers (), null, null );

Initialize the SSL environment. The second parameter indicates the source of the trusted certificate used by JSSE. If it is set to null, the certificate is obtained from javax.net. SSL. truststore. The third parameter is the random number generated by JSSE. This parameter affects the security of the system. Setting it to NULL is a good choice to ensure the security of JSSE.

The complete code is as follows:

/*
* SSL socket server
* @ Author bromon
*/

Package org. ec107.ssl;

Import java.net .*;
Import javax.net. SSL .*;
Import java. Io .*;
Import java. Security .*;

Public class sslserver
{
Static int Port = 8266; // The port number to be listened on by the system. 82.6.6 is the birthday of my girlfriend.
Static sslserversocket server;

/*
* Constructor
*/

Public sslserver ()
{

}


/*
* @ Param port: Port Number of the listener
* @ Return returns an sslserversocket object.
*/

Private Static sslserversocket getserversocket (INT theport)
{
Sslserversocket S = NULL;
Try
{
String key = "sslkey"; // Certificate Name to use

Char keystorepass [] = "12345678". tochararray (); // certificate Password

Char keypassword [] = "12345678". tochararray (); // key password used for the certificate alias

Keystore Ks = keystore. getinstance ("jks"); // create a jks keystore

KS. Load (New fileinputstream (key), keystorepass );

// Create an X.509 key manager for managing the jks keystore
Keymanagerfactory kmf = keymanagerfactory. getinstance ("sunx509 ");

Kmf. INIT (KS, keypassword );

Sslcontext = sslcontext. getinstance ("SSLv3 ");

Sslcontext. INIT (kmf. getkeymanagers (), null, null );

// Generate sslserversocketfactory based on the preceding SSL context, which is different from the common generation method.
Sslserversocketfactory factory = sslcontext. getserversocketfactory ();

S = (sslserversocket) Factory. createserversocket (theport );

} Catch (exception E)
{
System. Out. println (E );
}
Return (s );
}


Public static void main (string ARGs [])
{
Try
{
Server = getserversocket (port );
System. Out. println ("waiting for connection on the" + port + "port ...");

While (true)
{
Sslsocket socket = (sslsocket) server. Accept ();

// Send the obtained socket to the createthread object for processing, and the main thread continues to listen
New createthread (socket );

}
} Catch (exception E)
{
System. Out. println ("main method error 80:" + E );
}
}
}

/*
* Internal class, obtain the socket connection of the main thread, and generate a sub-thread for processing
*/

Class createthread extends thread
{
Static bufferedreader in;
Static printwriter out;
Static socket S;

/*
* Constructor to obtain socket connections and initialize In and out objects
*/

Public createthread (Socket socket)
{
Try
{
S = socket;
In = new bufferedreader (New inputstreamreader (S. getinputstream (), "gb2312 "));

Out = new printwriter (S. getoutputstream (), true );

Start (); // open a new thread to execute the run Method

} Catch (exception E)
{
System. Out. println (E );
}

}

/*
* The thread method is used to process the data passed by the socket.
*/

Public void run ()
{
Try
{
String MSG = in. Readline ();
System. Out. println (MSG );
S. Close ();
} Catch (exception E)
{
System. Out. println (E );
}
}
}

Put the certificate we just generated in the directory where the program is located. The above code can be compiled and executed:

Java org. ec107.ssl. sslserver

Wait for connection on port 8266...

Iii. Client

The client code is relatively simple. Instead of specifying the SSL environment in the program, we can specify the environment when executing the client program. Note that the client does not import the certificate, but uses the default factory method to construct sslsocket:

● Sslsocketfactory factory = (sslsocketfactory) sslsocketfactory. getdefault ();

Construct the default factory Method

● Socket S = factory. createsocket ("localhost", Port );

Open an sslsocket connection

/*
* SSL Socket Client
* @ Author bromon
*/

Package org. ec107.ssl;

Import java.net .*;
Import javax.net. SSL .*;
Import javax.net .*;
Import java. Io .*;

Public class sslclient
{
Static int Port = 8266;
Public static void main (string ARGs [])
{
Try
{
Sslsocketfactory factory = (sslsocketfactory) sslsocketfactory. getdefault ();

Socket S = factory. createsocket ("localhost", Port );

Printwriter out = new printwriter (S. getoutputstream (), true );
Out. println ("Safe say hello ");
Out. Close ();
S. Close ();
} Catch (exception E)
{
System. Out. println (E );
}
}
}

Copy the certificate (sslkey) generated by the server to the directory where the program is located. When executing this program, you need to input the certificate name to the javax.net. SSL. truststore environment variable:

Java -djavax.net. SSL. truststore = sslkey org. ec107.ssl. sslclient

You can view the data sent from the client on the server console.

The execution client can have another method: copy the certificate to the Java home/lib/security directory, change the name to jssecacerts, and then directly execute the client:

Java org. ec107.ssl. sslclient

The program will automatically go to the above directory to find the jssecacerts file as the default certificate. Note that the Java home here is not the java_home we specified when installing j2se. You can execute a program to get the location of Java home:

Public class getjavahome
{
Public static void main (string ARGs [])
{
System. Out. println (system. getproperty ("Java. Home "));
}
}

Generally (Windows 2 k) Hava home is located in C: Program filesjavaj2re1.4.0 _ 02, and the certificate should be copied to C: Program filesjavaj2re1.4.0 _ 02libsecurity, if Java ide with built-in JDK is installed, such as JBuilder, the situation may be different.

If the client directly connects without a certificate, the server will encounter an exception during running and the connection is not allowed.

Running Environment: Windows 2 k server, j2sdk1.4.1

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.