The simple implementation of SSL security protocol theory and two-way authentication

Source: Internet
Author: User
Tags ssl connection

Secure Socket layers (secure Sockets layer. SSL) is an Internet-based security protocol that guarantees privacy. It enables communication between customer service applications to be non-eavesdropping and always authenticates servers and clients. The SSL protocol is required to be based on a reliable transport layer protocol. The SSL protocol is independent of the application layer protocol, and the High-level application protocol can be transparently built on the SSL protocol. The SSL protocol has completed the encryption algorithm, the negotiation of the communication key and the server authentication work before the application layer protocol communication. Thereafter, the data transmitted by the application layer protocol is encrypted, thus guaranteeing the privacy of the communication.

    • Development status

The SSL protocol was introduced by Netscape Company in 1994 to encrypt the transmission protocol of Information about network information security. Its purpose is to build an encrypted secure channel for the information transfer between the client browser and the server side. The latest version is the V3.1 version, but most of them use the V3.0 version.
With the general promotion of network security awareness, more and more network applications are gradually using SSL encryption transmission. Because SSL technology adopts encryption, authentication, key negotiation and other mechanisms to ensure the confidentiality, integrity and authentication of communication endpoints, SSL protocol is widely used in online banking, mailbox landing and data encryption and transmission.
The SSL protocol, which runs on top of the TCP/IP layer, provides encrypted data channel for the application, and uses encryption algorithms such as RC4, MD5 and RSA to unify the encryption for business information. However, in the implementation of the SSL protocol in order to meet the requirements of compatibility and ease of use, there is still a certain degree of vulnerability, an attacker could exploit the SSL protocol's weaknesses to attack it for sensitive information.

    • Basic theory
      The Secure Socket LAYER,SSL protocol is the protocol for securely exchanging information between a Web browser and a Web server, providing two basic security services: Authentication and confidentiality.
      Summing up, the SSL protocol has three features:
      Confidentiality: After the session key is defined in the handshake protocol, all messages are encrypted.
      Authentication: Optional client authentication, and mandatory server-side authentication.
      Integrity: Messages that are delivered include message integrity checks (using MAC).
      SSL is between the application layer and the TCP layer. The application layer data is no longer passed directly to the transport layer, but is passed to the SSL layer, which encrypts the data received from the application layer and adds its own SSL header.

      Figure 1 where the SSL layer resides in the Internet model

The SSL protocol is divided into 2 tiers: The bottom layer is an SSL logging protocol based on a reliable transport protocol (TCP); the upper layer is an SSL handshake protocol based on the SSL logging protocol, an SSL-modified redaction protocol, and an SSL warning protocol. The SSL logging protocol involves information fragmentation, compression, data authentication, and encryption provided by the application to encapsulate different upper layer protocols; The SSL handshake protocol is used to exchange version numbers, negotiate encryption algorithms and compression algorithms, and Exchange keys before the server and client can transfer application data. SSL Modification redaction Protocol is used to indicate the change of password policy; The SSL alarm protocol is used to warn or terminate the current connection when a handshake or data encryption operation fails or an exception occurs. The SSL protocol provides services such as authenticating users and servers, ensuring that data is sent to the correct client and server, encrypting data to prevent theft in the middle of the data, and maintaining data integrity to ensure that data is not altered during transmission.

    • SSL Application theory
      (1) Anonymous SSL connection: Also known as one-way authentication. This is the basic mode of SSL secure connection, which is supported by major browsers and is suitable for unidirectional data secure transmission applications. In this mode, the client does not have a digital certificate, except that the server has a certificate. A typical application is the anonymous authentication of the user's website ID and password.
      (2) equivalent security certification: mutual authentication. In this mode, both sides of the communication can initiate and receive SSL connection requests. Both parties can take advantage of security applications or security agent software.
      (3) application in e-commerce. E-commerce and online banking transactions, because there are merchants to participate in, customers to the Merchant designated site to fill out orders, to the merchant reported credit card number, the merchant to the bank to check the credit card number, effective to continue trading. Where customers can have no digital certificates, merchants and banks must have digital certificates. Anonymous SSL connections are used in customer and merchant communications. But the merchant and the bank transmits the customer data, must verify each other's digital certificate, uses the SSL connection to guarantee the transmission information security.

    • SSL Application Example
      This demonstrates the use of a small Java program to demonstrate information communication based on the SSL security protocol. The main use of Java Sslsocket and Sslserversocket respectively as the client and server-side objects for the exchange of information.
      First, generate KeyStore from the Keytool tool that comes with Java. Use the Keytool–genkeypair command to generate a key below the default KeyStore.

The file generated here. keystore file is placed by default in the current path, where the key file is the two sides to communicate the credentials, the following we use the KEYTOOL-LIST–V command can display the default KeyStore key details.

    • Implementation of server-side code

Using the above steps to generate the KeyStore, the following can be used by code to use the key for SSL-based information communication. The server side communicates with the client through Sslserversocket.

 Public classkeystoretest { Public Static void Main(string[] args) throws exception{String key="C:\\users\\administrator\\desktop\\.keystore"; KeyStore Keystore=keystore.getinstance ("JKS"); Keystore.load (NewFileInputStream (Key),"123456". ToCharArray ());//Create JKD Key Access library 123456 is the keystore password. Keymanagerfactory Kmf=keymanagerfactory.getinstance ("SunX509"); Kmf.init (KeyStore,"123456". ToCharArray ());//Create a X509 Key Manager that manages the JKs KeyStore, which is used to manage keys and requires a key passwordSslcontext Sslc=sslcontext.getinstance ("SSLv3");//Constructs an SSL environment, specifies that the SSL version is 3.0, or you can use TLSV1, but SSLv3 is more commonly used. Sslc.init (Kmf.getkeymanagers (),NULL,NULL);         Sslserversocketfactory sslfactory=sslc.getserversocketfactory (); Sslserversocket serversocket= (sslserversocket) Sslfactory.createserversocket (9999); while(true) {Socket socket=serversocket.accept ();Try{OutputStream os=socket.getoutputstream (); InputStream is=socket.getinputstream ();byte[] buf=New byte[1024x768];intlen= is. read (BUF); System. out. println ("Server receives client information:"+NewString (BUF)); Os.write ("SSL test from Server". GetBytes ()); Os.close (); is. Close (); }Catch(Exception e) { }         }    }}
    • Client code Implementation
      The client implementation also needs to KeyStore, here is the same sub-keystore, of course, you can not use the same copy, you can export the KeyStore information to another file for the client to use. Here for convenience, use the same copy of the KeyStore for communication. The main client code is as follows:
 Public classkeystoretestclient { Public Static void Main(string[] args) throws exception{String key="C:\\users\\administrator\\desktop\\.keystore"; KeyStore Keystore=keystore.getinstance ("JKS");//Create a keystore to manage the KeyStoreKeystore.load (NewFileInputStream (Key),"123456". ToCharArray ()); Trustmanagerfactory Tmf=trustmanagerfactory.getinstance ("SunX509");         Tmf.init (KeyStore); Sslcontext Sslc=sslcontext.getinstance ("SSLv3");//Constructs an SSL environment, specifies that the SSL version is 3.0, or you can use TLSV1, but SSLv3 is more commonly used. Sslc.init (NULL, Tmf.gettrustmanagers (),NULL);         Sslsocketfactory sslfactory=sslc.getsocketfactory (); Sslsocket socket= (sslsocket) Sslfactory.createsocket ("127.0.0.1",9999);//Create ServerSocket to verify authorization by transmitting dataInputStream is=socket.getinputstream ();         OutputStream Os=socket.getoutputstream (); Os.write ("info from client". GetBytes ());byte[] buf=New byte[1024x768];intlen= is. read (BUF); System. out. println ("Client Receives server information:"+NewString (BUF)); Os.close (); is. Close (); }}
    • Test results

After the completion of the Code section, to test, you need to start the server-side program, server-side running after the wait, mainly using the accept method of blocking, let the server side waiting for information from the client, the test results are as follows:
The server-side code console prints output as

Figure Server-side output


Figure Client Output

Through the output of the console printout information can be seen, the client and the server to complete the communication of information, print out the expected results, the implementation of SSL security protocol based information communication.

Through further understanding, we know that the implementation of the above code only realizes the one-way authentication, and communicates with each other. If you want to achieve two-way authentication, how to implement it?

    • Two-way authentication

Two-way authentication and one-way authentication are only one more, the specific process is as follows:

In order to achieve message authentication.
Server requires:
1) KeyStore: Where the private key of the server is saved
2) Trust KeyStore: Which saves the client's authorization certificate
Similarly, the client needs:
1) KeyStore: Where the private key of the client is saved
2) Trust KeyStore: Which saves the license certificate of the service side

Here I still recommend using the Java Keytool command to generate such information files. Of course the current very popular open source generated SSL certificate also has OpenSSL. OpenSSL is written in C language, cross-system. However, we may consider the convenience of using Java programs to generate certificates in a later process, or use the keytool that comes with the JDK.

1) generate the server-side private key and import it into the server-side KeyStore file
Keytool-genkey-alias Serverkey-keystore Kserver.keystore
process, you need to fill in, according to the needs of their own set on the line

Serverkey the password of the private key, does not fill in and keystore the password consistent. It is important to note that the direct return to the line, do not change the password. Otherwise in the later program and can not directly apply the private key, will be error. (I did not verify this statement)

You can generate a Kserver.keystore file
Server.keystore is for the server, which holds its own private key.

There is no key generation location specified above, so where is the Kserver.keystore file?

2) Export the server-side certificate according to the private key
Keytool-export-alias Serverkey-keystore Kserver.keystore-file SERVER.CRT
SERVER.CRT is the service-side certificate

3) Import the service-side certificate into the trust KeyStore of the client
Keytool-import-alias serverkey-file Server.crt-keystore Tclient.keystore
Tclient.keystore is for the client, which holds the trusted certificate

Using the same method, generate the client's private key, the client's certificate, and import it into the trust KeyStore on the server.
1) Keytool-genkey-alias Clientkey-keystore Kclient.keystore
2) Keytool-export-alias Clientkey-keystore kclient.keystore-file client.crt
3) Keytool-import-alias Clientkey-file Client.crt-keystore Tserver.keystore

As a result, the resulting file is split into two groups
Server-side Save: Kserver.keystore Tserver.keystore
Client Save: Kclient.keystore Tclient.kyestore

Client:

/** * * * SSL Client * */   Public  class sslclient {      Private Static FinalString Default_host ="127.0.0.1";Private Static Final intDefault_port =7777;Private Static FinalString Client_key_store_password ="123456";Private Static FinalString Client_trust_key_store_password ="123456";PrivateSslsocket Sslsocket;/** * Start client program * * @param args */       Public Static void Main(string[] args) {Sslclient client =NewSslclient ();          Client.init ();      Client.process (); }/** * Connect to the server via SSL socket and send a message */       Public void Process() {if(Sslsocket = =NULL) {System.out.println ("ERROR");return; }Try{InputStream input = Sslsocket.getinputstream ();              OutputStream output = Sslsocket.getoutputstream (); Bufferedinputstream bis =NewBufferedinputstream (input); Bufferedoutputstream BOS =NewBufferedoutputstream (output); Bos.write ("Client Message". GetBytes ()); Bos.flush ();byte[] buffer =New byte[ -];              Bis.read (buffer); System.out.println (NewString (buffer));          Sslsocket.close (); }Catch(IOException e)          {System.out.println (e); }      }/** * <ul> * <LI>SSL connection Focus:</li> * <li> Initialize sslsocket</li> * <li > Import Client private key KeyStore, import client trusted KeyStore (server-side certificate) </li> * </ul> * *       Public void Init() {Try{Sslcontext CTX = sslcontext.getinstance ("SSL"); Keymanagerfactory KMF = keymanagerfactory.getinstance ("SunX509"); Trustmanagerfactory TMF = trustmanagerfactory.getinstance ("SunX509"); KeyStore KS = Keystore.getinstance ("JKS"); KeyStore tks = keystore.getinstance ("JKS"); Ks.load (NewFileInputStream (".../kclient.keystore"), Client_key_store_password.tochararray ());//change to the appropriate file pathTks.load (NewFileInputStream (".../tclient.keystore"), Client_trust_key_store_password.tochararray ());//change to the appropriate file pathKmf.init (KS, Client_key_store_password.tochararray ());              Tmf.init (TKS); Ctx.init (Kmf.getkeymanagers (), Tmf.gettrustmanagers (),NULL);          Sslsocket = (sslsocket) ctx.getsocketfactory (). Createsocket (Default_host, Default_port); }Catch(Exception e)          {System.out.println (e); }      }  }

Server:

/********************************************************************************************************** * * 1) Generate server-side private key </li> * Keytool-genkey-alias serverkey-keystore Kserver.keystore * 2) based on private key, service-side certificate everywhere * Keytool-exoport-alias serverkey-keystore kserver.keystore-file SERVER.CRT * 3) Add the certificate to the client trusted KeyStore * Keytool-imp Ort-alias serverkey-file Server.crt-keystore Tclient.keystore * *************************************************** *******************************************************************/  /** * */SSL Server * */   Public  class sslserver {      Private Static Final intDefault_port =7777;Private Static FinalString Server_key_store_password ="123456";Private Static FinalString Server_trust_key_store_password ="123456";PrivateSslserversocket ServerSocket;/** * Startup program * * @param args */       Public Static void Main(string[] args) {Sslserver Server =NewSslserver ();          Server.init ();      Server.start (); }/** * * Listen to SSL Server socket * Because the program is not a demo socket listener, it is simple in single threaded form, and only accepts the client message, and returns the client-specified message * */       Public void Start() {if(ServerSocket = =NULL) {System.out.println ("ERROR");return; } while(true) {Try{Socket s = serversocket.accept ();                  InputStream input = S.getinputstream ();                  OutputStream output = S.getoutputstream (); Bufferedinputstream bis =NewBufferedinputstream (input); Bufferedoutputstream BOS =NewBufferedoutputstream (output);byte[] buffer =New byte[ -];                  Bis.read (buffer); System.out.println (NewString (buffer)); Bos.write ("Server Echo". GetBytes ());                  Bos.flush ();              S.close (); }Catch(Exception e)              {System.out.println (e); }          }      }/** * * SSL connection Focus: * Initialize Sslserversocket * Import server-side private key KeyStore, import server-side trusted keystore (client's certificate) * */       Public void Init() {Try{Sslcontext CTX = sslcontext.getinstance ("SSL"); Keymanagerfactory KMF = keymanagerfactory.getinstance ("SunX509"); Trustmanagerfactory TMF = trustmanagerfactory.getinstance ("SunX509"); KeyStore KS = Keystore.getinstance ("JKS"); KeyStore tks = keystore.getinstance ("JKS"); Ks.load (NewFileInputStream (".../kserver.keystore"), Server_key_store_password.tochararray ());//change to the appropriate file pathTks.load (NewFileInputStream (".../tserver.keystore"), Server_trust_key_store_password.tochararray ());//change to the appropriate file pathKmf.init (KS, Server_key_store_password.tochararray ());              Tmf.init (TKS); Ctx.init (Kmf.getkeymanagers (), Tmf.gettrustmanagers (),NULL);              ServerSocket = (sslserversocket) ctx.getserversocketfactory (). Createserversocket (Default_port); Serversocket.setneedclientauth (true); }Catch(Exception e)          {E.printstacktrace (); }      }  }

So far, the two-way authentication has been completed, on the basis of two-way authentication communication, two words: Security!!

Reference: http://www.cnblogs.com/yqskj/p/3142006.html

The simple implementation of SSL security protocol theory and two-way authentication

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.