Java Security SSL/TLS

Source: Internet
Author: User
Tags configuration settings pkcs12

Some of the security techniques mentioned above, such as message digest, encryption and decryption algorithm, digital signature and data certificate, are not used directly by the developers, but have been encapsulated and even formed some security protocols, exposing certain interfaces for developers to use. Because of the direct use of these security tools, the cost of learning to developers is too high, need to understand the bottom line implementation, and directly use the interface exposed after the easy.

Behind these packages and protocols, many of them use the SSL/TSL protocol, the most common of which is the SSL/TLS protocol formed on the basis of the HTTP protocol to ensure the security of Web Access. The SSL/TLS protocol consists of two protocols: SSL (Secure Socket Layer) and TLS (Transport layers security, Transport layer Secure) protocol. SSL is developed by Netscape, a network transport layer in the TCP/IP reference Model, as a security protocol for network communication to provide security and complete data integrity. TLS is a generalized protocol based on SSL protocol, it is also located in the TCP/IP reference Model of the network transport layer, as the successor of the SSL protocol, become the next Generation network security and data Integrity security protocol.

The specific implementation and details of the SSL/TLS protocol is certainly very complex, can Baidu a bit slowly understand, the following is the main list of Java frequently encountered with SSL/TLS related situation:

I. Configuration of the HTTPS protocol in Tomcat

<connector port= "8443" protocol= "Org.apache.coyote.http11.Http11NioProtocol" sslenabled= "true"               maxthreads= "Scheme=" "https" secure= "true"               clientauth= "true" sslprotocol= "TLS"    keystorefile= "conf/ Serverkeystore.jks "   keystorepass=" Gitblit "   truststorefile=" CONF/CAKEYSTORE.P12 "   truststorepass=" Gitblit "   truststoretype=" pkcs12 "/>

Attribute Explanation:
Port: Protocol Listener Port number
Protocol: Protocol Implementation class
MaxThreads: Maximum number of threads
Sslenabled,scheme,secure,sslprotocol: Basically a fixed configuration
Keystorefile: Server KeyStore file path
Keystorepass: Server keystore password
ClientAuth: Whether to verify the client
Truststorefile: Server trusts keystore file path
Truststorepass: Server trusts keystore Password
Truststoretype: Server trusts KeyStore type, if not specified, defaults to JKS

In the server KeyStore file, it is best to have only one entry, of course, the keyentry type, because there is no way to configure the entry alias for secure communication in this configuration, if there are multiple entries, the server will arbitrarily select an entry, it will cause the use of the item is uncertain. The entries stored in the server trust KeyStore are certificateentry types, and in the correct case only the certificates that the server trusts are stored. In general, these certificates are issued to the client for use, and this root certificate must be owned by the server, so the server trust KeyStore is best to store only one root certificate for the client issued a certificate, so long as the root certificate is trusted, you will trust the root certificate issued by all certificates. Facilitates the addition of new clients. Of course, a more stupid way is to add the root certificate issued to the client to use the certificate is all added to the server trust KeyStore file. If the ClientAuth is configured to False, that is, one-way authentication, only the service side and not the authentication client, then, Truststorefile,truststorepass,truststoretype These properties are not used, not configured.

Second, the use of Sslsocket

Package Com.xtayfjpk.security.jsse;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;import Org.junit.test;public class Sslsockettest {@Testpublic void Testrunserver () throws Exception {//Get SSL context Sslcontext Context = Sslcontext.getinstance ("SSL"); String Keystorepassword = "password";//Gets the server Keystorekeystore Serverkeys = Getkeystore ("Serverkeys", "JKs", Keystorepassword);//Get Keymanagerfactorykeymanagerfactory keymanagerfactory = keymanagerfactory.getinstance ( Keymanagerfactory.getdefaultalgorithm ()); String Privatekeypassword = "password";//Initialize Keymanagerfactorykeymanagerfactory.init (Serverkeys, Privatekeypassword.tochararray ());//Get TrustmanagerfactorytrustmanagerfactoRy trustmanagerfactory = Trustmanagerfactory.getinstance (Trustmanagerfactory.getdefaultalgorithm ()); String Truststorepassword = "password";//Get Server-side trust Keystorekeystore Servertrustkeys = Getkeystore ("Servertrust", "JKs", Truststorepassword);//Initialize Trustmanagerfactorytrustmanagerfactory.init (Servertrustkeys);//Initialize SSL context Context.init ( Keymanagerfactory.getkeymanagers (), trustmanagerfactory.gettrustmanagers (), null);// Get sslserversocketfactorysslserversocketfactory SSF = (sslserversocketfactory) using SSL context Context.getserversocketfactory ();//Use Sslserversocketfactory to create the Sslserversocket and listen for the specified port Sslserversocket ServerSocket = (sslserversocket) ssf.createserversocket (9999);//Setup requires authentication to the client Serversocket.setneedclientauth (TRUE); while (true) {try {//waits for the client to connect sslsocket socket = (sslsocket) serversocket.accept (); InputStream in = Socket.getinputstream ( ); byte[] buf = new Byte[1024];int len = In.read (BUF); System.out.println (New String (buf, 0, Len)); In.close ();} catch (Exception e) {e.printstacktrace ();}}} @Testpublic void Testrunclient () throws Exception {Sslcontext context = sslcontext.getinstance ("SSL"); String Keystorepassword = "password"; KeyStore Clientkeys = Simplesslserver.getkeystore ("Clientkeys", "JKs", Keystorepassword); Keymanagerfactory keymanagerfactory = keymanagerfactory.getinstance (Keymanagerfactory.getdefaultalgorithm ()); String Privatekeypassword = "XTAYFJPK"; Keymanagerfactory.init (Clientkeys, Privatekeypassword.tochararray ()); Trustmanagerfactory trustmanagerfactory = trustmanagerfactory.getinstance (trustmanagerfactory.getdefaultalgorithm ()); String Truststorepassword = "password"; KeyStore Servertrustkeys = Getkeystore ("Clienttrust", "JKs", Truststorepassword); Trustmanagerfactory.init ( Servertrustkeys); Context.init (Keymanagerfactory.getkeymanagers (), trustmanagerfactory.gettrustmanagers (), NULL) ///Use SSL context to create sslsocketsslsocketfactory factory = (sslsocketfactory) context.getsocketfactory (); String host = "127.0.0.1";//create sslsocketsslsocket socket = (sslsocket) factory.createsocket (host, 9999);Communication with the server OutputStream outputstream = Socket.getoutputstream () outputstream.write ("XTAYFJPK". GetBytes ()); O Utputstream.flush (); Outputstream.close (); Socket.close ();} public static KeyStore Getkeystore (string Keystorepath, String type, String Keystorepassword) throws Exception {KeyStore K Eystore = keystore.getinstance (type); FileInputStream in = new FileInputStream (Keystorepath); Keystore.load (in, Keystorepassword.tochararray ()); In.close () ; return keyStore;}}

as can be seen in the example above, this is consistent with the configuration of the Tomcat HTTPS protocol, because the Tomcat bottom line must also use Sslsocket to implement the HTTPS protocol. Sslserversocketfactory also has a Getdefault method that returns a Sslserversocketfactory instance directly, if you do not need to create and initialize Sslcontext with this method, For SSL-related configuration settings in System Properties, there are two ways to set system properties: One is set when the virtual machine is started, as follows:
-djavax.net.ssl.keystore=clientkeys
-djavax.net.ssl.keystorepassword=password
-djavax.net.ssl.truststore=clienttrust
-djavax.net.ssl.truststorepassword=password
The second is set by System.setproperty.

Third, the use of Httpsurlconnection


Package Com.xtayfjpk.security.jsse;import Java.io.bufferedreader;import Java.io.fileinputstream;import Java.io.inputstream;import Java.io.inputstreamreader;import Java.net.url;import Java.security.KeyStore;import Javax.net.ssl.httpsurlconnection;import Javax.net.ssl.keymanagerfactory;import Javax.net.ssl.SSLContext;import Javax.net.ssl.sslsocketfactory;import Javax.net.ssl.trustmanagerfactory;import Org.junit.Test;public Class httpsurlconnectiontest {@Testpublic void Test () throws Exception {URL url = new URL ("https://localhost:8443/"); Httpsurlconnection connection = HttpsURLConnection.class.cast (Url.openconnection ()); Sslcontext context = sslcontext.getinstance ("SSL"); String Keystorepassword = "Gitblit"; KeyStore Clientkeys = Simplesslserver.getkeystore ("D:\\java-app\\apache-tomcat-6.0.35\\conf\\clientkeystore.p12", "PKCS12", Keystorepassword); Keymanagerfactory keymanagerfactory = keymanagerfactory.getinstance (Keymanagerfactory.getdefaultalgorithm ()); String Privatekeypassword = "Gitblit"; Keymanagerfactory.init (Clientkeys, Privatekeypassword.tochararray ()); Trustmanagerfactory trustmanagerfactory = trustmanagerfactory.getinstance (trustmanagerfactory.getdefaultalgorithm ()); String Truststorepassword = "Gitblit"; KeyStore Servertrustkeys = Getkeystore ("D:\\java-app\\apache-tomcat-6.0.35\\conf\\clienttruststore.jks", "JKs", Truststorepassword); Trustmanagerfactory.init (Servertrustkeys); Context.init (Keymanagerfactory.getkeymanagers (), Trustmanagerfactory.gettrustmanagers (), null);//create Sslsocketsslsocketfactory with SSL context factory = (sslsocketfactory) Context.getsocketfactory ();//If the server does not set the need to authenticate the client, you can not set Sslsocketfactoryconnection.setsslsocketfactory (factory); Connection.setdoinput (True); Connection.setdooutput (true); InputStream in = Connection.getinputstream (); String line = null; BufferedReader reader = new BufferedReader (new InputStreamReader (in)), while ((Line=reader.readline ())!=null) { System.out.println (line);}} public static KeyStore Getkeystore (string Keystorepath, String type, STRing Keystorepassword) throws Exception {KeyStore KeyStore = keystore.getinstance (type); FileInputStream in = new FileInputStream (Keystorepath); Keystore.load (in, Keystorepassword.tochararray ()); In.close () ; return keyStore;}}

Four, make the service side KeyStore support multiple entries, and can specify the use of the entry alias

In the configuration of the HTTPS protocol in Tomcat, it was said that the server KeyStore had better have only one entry, otherwise it would result in a situation where the entry used was indeterminate. But sometimes you might think that the KeyStore stores multiple entries, specifying specific entries by configuring the entry aliases at startup, because there is no alias configuration support available in Tomcat, so it is best to have only one entry in KeyStore. However, if you write your own sslsocket program, it may be supported by extension, as follows:

Package Com.xtayfjpk.security;import Java.net.socket;import Java.security.principal;import Java.security.privatekey;import Java.security.cert.x509certificate;import Java.util.arrays;import Javax.net.ssl.sslengine;import Javax.net.ssl.x509extendedkeymanager;import Javax.net.ssl.x509keymanager;public    Class Myaliasedx509extendkeymanager extends X509extendedkeymanager {private String keyalias;        Private X509keymanager Keymanager;    Public Myaliasedx509extendkeymanager (String Keyalias, X509keymanager keymanager) {this.keyalias = Keyalias;    This.keymanager = Keymanager; }//provided to the client to select an alias in client KeyStore @overridepublic String chooseclientalias (string[] keytypes, principal[] issuers,  Socket socket) {String alias = keyalias==null? Keymanager.chooseclientalias (keytypes, issuers, socket): Keyalias;return alias;} Available for server-side use to select an alias in the server-side KeyStore @overridepublic string Chooseserveralias (String keyType, principal[] issuers, Socket Socket) {String alias = keyalias==null? keymanagEr.chooseserveralias (KeyType, issuers, socket): Keyalias;return alias;} @Overridepublic x509certificate[] Getcertificatechain (String alias) {return keymanager.getcertificatechain (alias);} @Overridepublic string[] getclientaliases (String keyType, principal[] issuers) {return keymanager.getclientaliases ( KeyType, issuers);} @Overridepublic Privatekey Getprivatekey (String alias) {return keymanager.getprivatekey (alias);} @Overridepublic string[] getserveraliases (String keyType, principal[] issuers) {return keymanager.getserveraliases ( KeyType, issuers);} @Overridepublic string Chooseengineclientalias (string[] keyType, principal[] issuers, Sslengine engine) {string alias = K Eyalias==null? Super.chooseengineclientalias (KeyType, issuers, engine): Keyalias;return alias;} @Overridepublic string Chooseengineserveralias (String keyType, principal[] issuers, Sslengine engine) {string alias = key Alias==null? Super.chooseengineserveralias (KeyType, issuers, engine): Keyalias;return alias;}}


by inheriting X509extendedkeymanager, you implement a Keymanager, and the alias is passed through the constructor method, Then use your own Keymanager implementation class wrapper keymanagerfactory the Keymanager created by the alias to achieve the purpose of the specified KeyStore in the use of the entry.

Java Security SSL/TLS

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.