SSL authentication and KeyStore use in Java

Source: Internet
Author: User
Long time no use of SSL authentication, things for a long time, a little rusty. Blog is the advantage, you can do a memo. Java is authenticated through SSL, using Sslsocket, sslsocketfactory can get sslsocket instance objects. Usually sslsocketfactory need a sslcontext environment object to build, build a Sslcontext environment: Sslcontext sslc=sslcontext.getinstance ("SSLv3");
Construct an SSL environment, specify SSL version 3.0, or use TLSV1, but SSLv3 is more common. Sslc.init (Keymanager[],trustmanager[]null);
Keymanager[] The first parameter is the authoritative Key Manager, which is used to authorize authentication. Trustmanager[] The second is a licensed Certificate manager to authenticate the server-side certificate. The third parameter is a random value that can be filled in with null. If only the server transmits data to the client to authenticate, the first parameter is passed in, and the client build environment passes in the second parameter. Two-way authentication, you use two managers at the same time. Service side: [Code]java code:
Import Java.io.FileInputStream;
Import java.io.*;
Import Java.net.Socket;

Import Java.security.KeyStore;
Import Javax.net.ssl.KeyManagerFactory;
Import Javax.net.ssl.SSLContext;
Import Javax.net.ssl.SSLServerSocket;


Import Javax.net.ssl.SSLServerSocketFactory; public class Keystoretest {/** * name:keystoretest * Author:suju/public static void main (string[] args) throw
		s exception{String key= "C:/.keystore";
		KeyStore keystore=keystore.getinstance ("JKS");
		KeyStore type, default is JKs keystore.load (new FileInputStream (key), "123456". ToCharArray ());
		Creating a JKD Key Access library 123456 is a keystore password.
		Keymanagerfactory kmf=keymanagerfactory.getinstance ("SunX509");
		Kmf.init (KeyStore, "Asdfgh". ToCharArray ());
		ASDFGH is the key password.
		Create a X509 Key Manager that manages the JKs KeyStore, which is used to manage the key and requires the password of the key Sslcontext sslc=sslcontext.getinstance ("SSLv3");
		Construct an SSL environment, specify SSL version 3.0, or use TLSV1, but SSLv3 is more common.
		Sslc.init (Kmf.getkeymanagers (), null,null); The second parameter, trustmanager[], is the authentication manager, used when two-way authentication is required,//constructs the SSL environment Sslserversocketfactory SSLfactory=sslc.getserversocketfactory ();
		Sslserversocket serversocket= (Sslserversocket) sslfactory.createserversocket (9999);
			 Create ServerSocket, listen, and transmit data to verify authorization for (int i=0;i<15;i++) {final Socket socket=serversocket.accept ();
						 New Thread () {public void run () {try{inputstream is=socket.getinputstream ();
						 
						 OutputStream Os=socket.getoutputstream ();
						 Byte[] Buf=new byte[1024];
						 int Len=is.read (BUF);
						 System.out.println (New String (BUF));
						 Os.write ("SSL Test". GetBytes ());
						 Os.close ();
					 Is.close ();
		 }catch (Exception e) {//}}}.start ();	
	} serversocket.close ();
 }
}

Client: [Code]java code:
Import Java.io.FileInputStream;
Import Java.io.InputStream;
Import Java.io.OutputStream;

Import Java.security.KeyStore;
Import Javax.net.ssl.KeyManagerFactory;
Import Javax.net.ssl.SSLContext;
Import Javax.net.ssl.SSLServerSocket;
Import Javax.net.ssl.SSLServerSocketFactory;
Import Javax.net.ssl.SSLSocket;
Import Javax.net.ssl.SSLSocketFactory;

Import Javax.net.ssl.TrustManagerFactory; public class Keystoretestclient {/** * name:keystoretestclient * Author:suju/public static void Main (string[)
		args) throws exception{String key= "C:/client";	KeyStore keystore=keystore.getinstance ("JKS");
		Create a keystore to manage KeyStore keystore.load (new FileInputStream (key), "123456". ToCharArray ());
		Create JKD key Access library trustmanagerfactory tmf=trustmanagerfactory.getinstance ("SunX509");					Tmf.init (KeyStore);
		Verify the data, you can not pass in key password//create trustmanagerfactory, Management authorization certificate Sslcontext sslc=sslcontext.getinstance ("SSLv3");
		Construct an SSL environment, specify SSL version 3.0, or use TLSV1, but SSLv3 is more common. Sslc.init (Null,tmf.gettrustmanagers (), null); Keymanager[] The first parameter is the authoritative Key Manager, which is used to authorize authentication. The second is the Licensed Certificate Manager,//to authenticate the server-side certificate.
		 Only validate server data, the first manager can be null//constructed SSL Environment Sslsocketfactory sslfactory=sslc.getsocketfactory ();
		Sslsocket socket= (Sslsocket) sslfactory.createsocket ("127.0.0.1", 9999);
		 Create ServerSocket to verify authorization InputStream is=socket.getinputstream () by transmitting data;		 
		 OutputStream Os=socket.getoutputstream ();		 
		 Os.write ("Client". GetBytes ());
		 Byte[] Buf=new byte[1024];
		 int Len=is.read (BUF); 
		 System.out.println (New String (BUF));
		 Os.close ();
	Is.close ();
 }
}
Use the Keytool in Java to manage keystore with your own. * * Often forget the parameters, write down to remember. Create a key under Default KeyStore Keytool-genkeypair

Displays the default KeyStore key details Keytool-list-v


Use other KeyStore to create a key, and create a new one if the KeyStore does not exist. Keytool--genkeypair-keystore c:\client

Export a key Keytool-exportcert-alias mykey-file c:\mykey.cer

Import a key to a keystore, Keytool-importcert-alias mykey-file c:\mykey.cer-keystore c:\client

There is also a lot of action on key, Keytool provides-HELP help command

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.