Use SSL to build a secure Socket

zhaozj2021-02-16  38

Use SSL to build a secure Socket

Bromon original copyright

SSL (Secure Sockets) is Netscape, which is developed in 1994, initially used for web browsers, providing security to browser and server data transfer, providing encryption, source authentication, and data integrity. SSL3.0 is now universally used, and its improvement version of TLS (transport layer security) has become an Internet standard. SSL itself and TCP socket connections are very similar. In the protocol stack, SSL can be simply regarded as a secure TCP connection, but some TCP connection features It is not supported, such as external data (OUT) -of-bound).

When building a Socket-based C / S program, the support of the SSL is added to ensure data security and complete methods. Perfect Java provides us with a simple implementation method: JSSE (Java security socket expansion). JSSE is a SSL and TLS protocol framework implemented by pure Java, abstract SSL and TLS complex algorithms, making security issues simple. JSSE has become a standard component in the J2SE 1.4 version, supports SSL 3.0 and TLS 1.0. We will demonstrate some of the basic applications of JSS through a specific example. The server side in the example will open an SSL Socket, and only the client holds the specified certificate can be connected to it, all data passes are encrypted.

Constructing a sslsocket is very simple:

SSLServerSocketFactory factory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault (); SSLServerSocket server = (SSLServerSocket) factory.createServerSocket (portNumber); SSLSocket socket = (SSLSocket);

However, the execution of such a program will generate an exception, and the report cannot be trusted. Sslsocket and ordinary socket are different, it requires a certificate to make secure authentication.

First, certificate

Generate a CA certificate and execute it under the command line:

KeyTool -Genkey -Keystore Sslkey -Keyalg RSA -Alaias SSL

The black body part is the parameter specified by the user, the first parameter is the name of the certificate to be generated, and the second parameter is the alias of the certificate. RSA indicates the encryption method we use.

The system will be required to enter the information of the certificate issuer, and you can input item by item, as shown below:

The system generated by the system will be the same as the certificate name. The certificate can be submitted to the authoritative CA certification organization audit. If you have been reviewed, organizations will provide trust warrants to ensure that your connection is secure. Of course this is not necessary. In our example, you will packed the certificate directly to the client program to ensure that the client is an authorized user to avoid fake customers, so do not submit an audit.

Second, the server side

You can now write the code of the server side. Unlike normal socket code, we need to import certificates in the program and use this certificate to construct SSLSocket. What is needed is:

● KeyStore Ks = KeyStore.GetInstance ("jks");

Access the Java keystore, JKS is a Java keystore created by KeyTool, saving the key.

● KeyManagerFactory KMF = KeyManagerFactory.GetInstance ("sunx509");

Create an X.509 Key Manager for managing the JKS keystore.

● sslcontext sslcontext = sslcontext.getinstance ("sslv3");

Construct an SSL environment, specifying the SSL version of 3.0, or using TLSV1, but SSLV3 is more common. ● SSLContext.init (kmf.getKeyManagers (), null, null;

Initialize the SSL environment. The second parameter is to tell the source of the trusted certificate used by JSS, set to null is a certificate from javax.net.ssl.trustStore. The third parameter is the random number of JSSE generated. This parameter will affect the security of the system, and set to null is a good choice to ensure the security of JSSE.

The full code is as follows:

/ * * SSL Socket server side * @ 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 system will be listened to the port number, 82.6.6 is an eclipus girlfriend's birthday ^ _ ^ static sslserversocket server; / * * constructor * / public sslserver () {} / * @ @ Param port listening port number * @ return returns a SSLServersocket object * / private static sslserversocket getServersocket (int theport) {sslserversocket s = null; try {string key = "sslkey"; // To use certificate name

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

Char keypassword [] = "12345678" .tochararray (); // Certificate noted the main password used

KeyStore Ks = KeyStore.GetInstance ("jks"); // Create a JKS keystore

Ks.Load (New FileInputStream (Key), KeyStorepass;

// Create an X.509 key manager for the management JKS keystore KeyManagerFactory KMF = keymanagerFactory.GetInstance ("sunx509");

Kmf.init (KS, Keypassword);

SSLContext sslcontext = sslcontext.getInstance ("SSLV3");

SSLCONText.init (kmf.getKeyManagers (), null, null; // generates SSLServersocketFactory, different SSLSERVERSOCKETFAACTORY FACTORY = SSLContext.getServerse = sslcontext.getServerse = SSLCONText.getSerVersocketFactory (), based on the SSL context configured above.

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 (" In the " port " port waiting to be connected ... "); while {sslsocket socket = (sslsocket) server.accept (); // Get gave to the CreateThread object processing, the main thread continues to listen to New CreateThread Socket);}} catch (exception e) {system.out.println ("MAIN method error 80:" e);}}}

/ * * Internal class, get the Socket connection of the main thread, generated subclocking to process * /

class CreateThread extends Thread {static BufferedReader in; static PrintWriter out; static Socket s; / * * constructor, obtaining a socket connection initialization in and out the object * / public CreateThread (Socket socket) {try {s = socket; in = new BufferedReader (new inputStreamReader (S.GETITINPUTSTREAM (), "GB2312")

OUT = New PrintWriter (S. GetOutputStream (), TRUE);

START (); // Open new thread to execute RUN method

} Catch (Exception E) {system.out.println (e);}} / * * thread method, processing Socket passed data * / 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 have just generated into the directory where the program is located, the code above can execute after compiling:

Java org.ec107.ssl.sslserver

Wait to connect at 8266 port ...

Third, the client

The client's code is relatively simple, we may not specify an SSL environment in the program, but specified when performing a client program. It should be noted that the client does not import the certificate, but the default factory method constructs SSLSocket:

● SslsocketFactory factory = (sslsocketfactory) sslsocketfactory.getDefault ();

Construct the default factory method

● Socket S = Factory.createsocket ("LocalHost", Port);

Open a 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 (); out.println ("Security Say Hello"); out.close (); S.Close ();} catch (exception e) {system.out. Println (E);}}}

Copy the certificate generated by the server to the directory where the program is located, you need to enter the javax.net.ssl.trustStore environment variable when performing this program:

Java -djavax.net.ssl.truststore = SSLKey Org.ec107.ssl.sslclient

You can see the data sent by the client at the server's console.

Executing the client can have another method, copy the certificate to the java home / lib / security directory, the name is changed to jssecacerts, then you can execute the client directly:

Java org.ec107.ssl.sslclient

The program will automatically go to the above directory to find the JSsecacerts file as the default certificate. It is important to note that Java Home here is not the java_home you specified when you install J2SE. You can perform 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"));}}

Under normal circumstances, the location of HAVA HOME is in C: Program Filesjavaj2re1.4.0_02, relative, certificate should be copied to C: Program Filesjavaj2re1.4.0_02libsecurity, if you have JDK JAVA IDE, such as JBuilder There may be different situations.

If the programmer is directly connected without holding a certificate, the server side generates an abnormality at runtime and does not allow connection.

Operating environment: Windows 2k Server, J2SDK1.4.1

转载请注明原文地址:https://www.9cbs.com/read-21745.html

New Post(0)