JAVA-JSSE-SSL/TLS Programming code example-bidirectional authentication

Source: Internet
Author: User
Tags rfc

Introduction to Ssl/tls/jsse:
1) SSL/TLS protocol operating mechanism
2) graphical SSL/TLS protocol
3) Use Wireshark to observe the SSL/TLS handshake process
4) The Java implementation of SSL/TLS--jsse

(i) Creating a keystore using Keytool

Using two-way authentication for SSL/TLS protocol communication, both the client and server are set up to authenticate themselves with the security certificate, and also set which security certificates to trust each other.
In theory altogether you need to prepare four files, two keystore files, and two truststore files.
The communicating parties each have a keystore and a truststore,keystore for storing their own keys and public keys, Truststore is used to store all the public keys that need to be trusted.

First use the Keytool tool that comes with the JDK to generate KeyStore and Truststore. The Java version used here is 1.7.
1) Create the server's KeyStore file to generate the server's public/private key pair. You need to specify the KeyStore password (storepass) and the password for the key pair (Keypass).
Access to KeyStore requires Storepass. The access key pair needs to be keypass.

C:\Program files\java\jre7\bin>keytool-genkey-alias catserver-keyalg rsa-keysize 1024-sigalg Sha256withrsa-keypa SS Catserver-keystore C:\_tmp\catserver.keystore-storepass Catserverkswhat is your first and last name? [Unknown]: Catwhat is the name of the Your organizational unit? [Unknown]: Catwhat is the name of your organization? [Unknown]: Catwhat is the name of your city or Locality? [Unknown]: Catwhat is the name of your state or province? [Unknown]: Catwhat is the Two-letter country code for this unit? [Unknown]: Ctis cn=cat, Ou=cat, O=cat, L=cat, st=cat, c=ct correct? [No]: Y


2) Create the client's KeyStore file. You also need to specify the password for the KeyStore password and key pair.

C:\Program files\java\jre7\bin>keytool-genkey-alias foxclient-keyalg dsa-keysize 512-sigalg sha1withdsa-keypass F Oxclient-keystore C:\_tmp\foxclient.keystore-storepass Foxclientkswhat is your first and last name? [Unknown]: Foxwhat is the name of the Your organizational unit? [Unknown]: Foxwhat is the name of your organization? [Unknown]: Foxwhat is the name of your city or Locality? [Unknown]: Foxwhat is the name of your state or province? [Unknown]: Foxwhat is the Two-letter country code for this unit? [Unknown]: Fxis cn=fox, Ou=fox, O=fox, L=fox, St=fox, c=fx correct? [No]: Y


3) Export the server's certificate (which includes the public key of the server) from the server's KeyStore.

C:\Program Files\java\jre7\bin>keytool-export-alias Catserver-keystore C:\_tmp\catserver.keystore-storepass Catserverks-file c:\_tmp\catserver.cercertificate stored in file <c:\_tmp\catserver.cer>

4) Export the client's certificate (including the client's public key) from the client's keystore.

C:\Program Files\java\jre7\bin>keytool-export-alias Foxclient-keystore C:\_tmp\foxclient.keystore-storepass Foxclientks-file c:\_tmp\foxclient.cercertificate stored in file <c:\_tmp\foxclient.cer>


5) Create the server's Truststore file and import the client's certificate (which includes the client's public key).

C:\Program Files\java\jre7\bin>keytool-import-alias Foxclient-keystore C:\_tmp\catservertrust.keystore- Storepass catservertrustks-file C:\_tmp\foxclient.cerowner:cn=fox, Ou=fox, O=fox, L=fox, ST=fox, C=fxissuer:cn=fox, OU  =fox, O=fox, L=fox, St=fox, c=fxserial number:6eaf996fvalid from:wed Nov 16:15:41 CST until:tue Feb 03 16:15:41 CST 2015Certificate FINGERPRINTS:MD5:B5:B6:92:66:84:92:A0:C2:F5:40:39:25:F8:66:2A:17SHA1:07:42:A3:1A:49:7B:C9 : 34:4b:6b:fa:37:6c:20:98:d4:20:13:7c:91sha256:37:a5:00:a3:13:00:de:99:3b:08:47:f6:1e:8a:05:f1:4a:b2:c6:22:20: E1:af:0e:05:b2:ce:e0:2f:94:b6:94signature algorithm name:sha1withdsaversion:3extensions: #1: objectid:2.5.29.14 Criticality=falsesubjectkeyidentifier [KeyIdentifier [0000:69 3E 6A D0 B5 B1 1F BD/E1 A4 6C 1F-i>j ... Hf.. L.q.0010:29 3B 32).; 2]]trust this certificate? [No]: Ycertificate was added to KeyStore


6) Create the client's Truststore file and import the server's certificate (which includes the server's public key).

C:\Program Files\java\jre7\bin>keytool-import-alias Catserver-keystore C:\_tmp\foxclienttrust.keystore- Storepass foxclienttrustks-file C:\_tmp\catserver.cerowner:cn=cat, Ou=cat, O=cat, L=cat, ST=cat, C=ctissuer:cn=cat, OU  =cat, O=cat, L=cat, St=cat, c=ctserial number:3e421457valid from:wed Nov 16:13:52 CST until:tue Feb 03 16:13:52 CST 2015Certificate fingerprints:md5:20:44:7c:e5:30:e6:7a:21:c2:49:64:77:e1:3a:a0:77sha1:8b:02:d2:be:98:2f : 99:94:08:47:e2:96:ec:05:1b:5d:b1:8f:30:2fsha256:a6:66:85:f4:c2:b2:06:4e:2e:40:d8:52:84:6e:85:2b:5b:bb:c3:b0 : 9c:31:92:99:f5:91:5d:83:67:c8:4d:d8signature algorithm name:sha256withrsaversion:3extensions: #1: ObjectId: 2.5.29.14 criticality=falsesubjectkeyidentifier [KeyIdentifier [0000:f5] E6 EE EF 5F 4F AC 6F A6 B8 $ A6 11 .... .. _$O.O. 6..0010:2b 5C DF 04 +\ ...] Trust this certificate? [No]: Ycertificate was added to KeyStore


KeySize
If the encryption algorithm is Rsa,key size range 512->16384 bits, and must be a multiple of 64.
If the encryption algorithm is Dsa,key size range 512->1024 bits, and must be a multiple of 64.

Sigalg
If the encryption algorithm is RSA, the signature algorithm can be Md5withrsa/sha1withrsa/sha256withrsa/sha384withrsa/sha512withrsa
If the encryption algorithm is DSA, the signature algorithm can be SHA1WITHDSA

If you are familiar with socket programming in Java, you will find that using Jsse for SSL/TLS programming is actually similar to it.
The difference is that the ServerSocket object is replaced with a Sslserversocket,socket object and replaced with a Sslsocket object.

(ii) server-side processing processes and code

Processing Flow:
1) To load the server's KeyStore file, you need to specify the KeyStore password (storepass).
There are three types of KeyStore:
Jceks-the proprietary KeyStore implementation provided by the SUNJCE provider.
Jks-the proprietary KeyStore implementation provided by the SUN provider.
Pkcs12-the transfer syntax for personal identity information as defined in PKCS #12.

2) to load the server's Truststore file, you need to specify the Truststore password (storepass).

3) Create the Keymanagerfactory object and initialize it with the password (keypass) of the KeyStore and server key pair loaded in 1).

4) Create the Trustmanagerfactory object and initialize it with the Truststore loaded in 2). The truststore is stored in the client's public key and is not required to be keypass or accessible.

5) Create Sslcontext and initialize with Keymanagerfactory and Trustmanagerfactory objects created in 3) and 4.
Http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#SSLContext
Creating Sslcontext is required to give sslcontext algorithms. The above link gives a valid sslcontext algorithms, with the following available values.
Ssl-supports some version of SSL; May and other versions
Sslv2-supports SSL version 2 or later; May and other versions
Sslv3-supports SSL version 3; May and other versions
Tls-supports some version of TLS; May and other versions
Tlsv1-supports RFC 2246:TLS version 1.0; May and other versions
Tlsv1.1-supports RFC 4346:TLS version 1.1; May and other versions
Tlsv1.2-supports RFC 5246:tls version 1.2; May and other versions

6) Create the sslserversocketfactory, create the Sslserversocket on the specified port and set the required client certificate: Setneedclientauth (TRUE)

7) Call the Accept () method on the Sslserversocket object to wait for the client to connect.
After the client is connected, the function returns a Sslsocket object that reads and writes on the input and output stream of the object.
A Handshakecompletedlistener listener can be added to this Sslsocket object, and the Handshakecompleted method of the listener will be called after the SSL/TLS handshake is over.
There are three ways that a client can trigger a handshake:
-Explicitly call the Starthandshake method/calling Starthandshake which explicitly begins handshakes, or
-Read or write operations on the socket object/any attempt to read or write application data in this socket causes an implicit handshake, or
-Calls the GetSession method on the socket object/a call to GetSession tries to set up a session if there is no currently valid session, and an I Mplicit handshake is done.

Package Learning.net.ssl;import Java.io.bufferedreader;import Java.io.fileinputstream;import java.io.IOException; Import Java.io.inputstreamreader;import java.io.printwriter;import java.net.socket;import java.security.KeyStore; Import Java.security.cert.x509certificate;import Javax.net.ssl.handshakecompletedevent;import Javax.net.ssl.handshakecompletedlistener;import Javax.net.ssl.keymanagerfactory;import Javax.net.ssl.SSLContext; Import Javax.net.ssl.sslpeerunverifiedexception;import Javax.net.ssl.sslserversocket;import Javax.net.ssl.sslserversocketfactory;import Javax.net.ssl.sslsocket;import javax.net.ssl.TrustManagerFactory;    public class Catserver implements Runnable, Handshakecompletedlistener {public static final int server_port = 11123;    Private final Socket _s;    Private String Peercername;    Public Catserver (Socket s) {_s = s; public static void Main (string[] args) throws Exception {String serverkeystorefile = "C:\\_tmp\\catserver.key        Store ";String serverkeystorepwd = "Catserverks";        String catserverkeypwd = "Catserver";        String servertrustkeystorefile = "C:\\_tmp\\catservertrust.keystore";        String servertrustkeystorepwd = "Catservertrustks";        KeyStore Serverkeystore = keystore.getinstance ("JKS");        Serverkeystore.load (New FileInputStream (Serverkeystorefile), Serverkeystorepwd.tochararray ());        KeyStore Servertrustkeystore = keystore.getinstance ("JKS");        Servertrustkeystore.load (New FileInputStream (Servertrustkeystorefile), Servertrustkeystorepwd.tochararray ());        Keymanagerfactory KMF = keymanagerfactory.getinstance (Keymanagerfactory.getdefaultalgorithm ());        Kmf.init (Serverkeystore, Catserverkeypwd.tochararray ());        Trustmanagerfactory TMF = trustmanagerfactory.getinstance (Trustmanagerfactory.getdefaultalgorithm ());        Tmf.init (Servertrustkeystore);        Sslcontext Sslcontext = sslcontext.getinstance ("TLSv1"); Sslcontext.init (Kmf.getkeymanagers (), tmf.geTtrustmanagers (), NULL);        Sslserversocketfactory sslserversocketfactory = Sslcontext.getserversocketfactory ();        Sslserversocket Sslserversocket = (sslserversocket) sslserversocketfactory.createserversocket (SERVER_PORT);        Sslserversocket.setneedclientauth (TRUE);            while (true) {Sslsocket s = (sslsocket) sslserversocket.accept ();            Catserver cs = new Catserver (s);            S.addhandshakecompletedlistener (CS);        New Thread (CS). Start (); }} @Override public void Run () {try {BufferedReader reader = new BufferedReader (New Inputstr            Eamreader (_s.getinputstream ()));            PrintWriter writer = new PrintWriter (_s.getoutputstream (), true);            Writer.println ("welcome~, enter exit to leave.");            String s; while ((s = reader.readline ()) = null &&!s.trim (). Equalsignorecase ("Exit")) {writer.println ("Ech            O: "+ S"); } writer.println ("bye~, "+ peercername);        } catch (Exception e) {e.printstacktrace ();            } finally {try {_s.close ();            } catch (IOException e) {e.printstacktrace (); }}} @Override public void handshakecompleted (Handshakecompletedevent event) {try {X5            09Certificate cert = (x509certificate) event.getpeercertificates () [0];        Peercername = Cert.getsubjectx500principal (). GetName ();        } catch (Sslpeerunverifiedexception ex) {ex.printstacktrace (); }    }}


(iii) client-side processing flow and Code
Processing flow: (same as the same as server)
1) Load the client's KeyStore file.

2) Loads the client's Truststore file.

3) Create the Keymanagerfactory object and initialize it.

4) Create the Trustmanagerfactory object and initialize it. The truststore is stored in the server's public key and is not required to be keypass or accessible.

5) to initialize the Keymanagerfactory and Trustmanagerfactory objects created in Sslcontext with 3 and 4).

6) Create a sslsocketfactory to create a sslsocket on the specified network address and port.

7) reads and writes on the input and output stream of the Sslsocket object.

Package Learning.net.ssl;import Java.io.bufferedreader;import Java.io.fileinputstream;import java.io.IOException; Import Java.io.inputstreamreader;import java.io.printwriter;import java.net.socket;import java.security.KeyStore; Import Javax.net.ssl.keymanagerfactory;import Javax.net.ssl.sslcontext;import javax.net.ssl.SSLSocketFactory; Import Javax.net.ssl.trustmanagerfactory;public class Foxclient {public static void main (string[] args) throws Excepti        on {String clientkeystorefile = "C:\\_tmp\\foxclient.keystore";        String clientkeystorepwd = "Foxclientks";        String foxclientkeypwd = "Foxclient";        String clienttrustkeystorefile = "C:\\_tmp\\foxclienttrust.keystore";        String clienttrustkeystorepwd = "Foxclienttrustks";        KeyStore Clientkeystore = keystore.getinstance ("JKS");        Clientkeystore.load (New FileInputStream (Clientkeystorefile), Clientkeystorepwd.tochararray ());        KeyStore Clienttrustkeystore = keystore.getinstance ("JKS"); CliEnttrustkeystore.load (New FileInputStream (Clienttrustkeystorefile), Clienttrustkeystorepwd.tochararray ());        Keymanagerfactory KMF = keymanagerfactory.getinstance (Keymanagerfactory.getdefaultalgorithm ());        Kmf.init (Clientkeystore, Foxclientkeypwd.tochararray ());        Trustmanagerfactory TMF = trustmanagerfactory.getinstance (Trustmanagerfactory.getdefaultalgorithm ());        Tmf.init (Clienttrustkeystore);        Sslcontext Sslcontext = sslcontext.getinstance ("TLSv1");                Sslcontext.init (Kmf.getkeymanagers (), tmf.gettrustmanagers (), NULL);        Sslsocketfactory socketfactory = Sslcontext.getsocketfactory ();                Socket socket = Socketfactory.createsocket ("localhost", catserver.server_port);        PrintWriter out = new PrintWriter (Socket.getoutputstream (), true);                BufferedReader in = new BufferedReader (New InputStreamReader (Socket.getinputstream ()));        Send ("Hello", out);        Send ("Exit", out);        Receive (in); Socket.cLose (); The public static void is send (String s, printwriter out) throws IOException {System.out.println ("sending:" + S             );    Out.println (s);        public static void Receive (BufferedReader in) throws IOException {String s;        while ((s = in.readline ()) = null) {System.out.println ("reveived:" + s); }    }}

JAVA-JSSE-SSL/TLS Programming code example-bidirectional authentication

Related Article

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.