Java Secure Communication: https and SSL

Source: Internet
Author: User
Tags ssl connection

 

1. HTTPS Concept

1) Introduction

HTTPS (full name: Hypertext Transfer Protocol over Secure Socket Layer) is an HTTP channel targeted at security. It is simply a secure version of HTTP. That is, the SSL layer is added under HTTP. The Security Foundation of HTTPS is SSL, so the detailed content of encryption requires SSL. The system was initially developed by Netscape, which provides authentication and encrypted communication methods and is now widely used for secure and sensitive communications on the World Wide Web, such as transaction payment.

2) differences between HTTPS and HTTP

A. You need to apply for a certificate from the CA for HTTPS protocol. Generally, there are few free certificates and you need to pay the fee.

B. HTTP is a hypertext transfer protocol, and information is transmitted in plain text. HTTPS is a secure SSL encrypted transmission protocol.

C. HTTP and HTTPS use completely different connection methods, with different ports. The former is 80, and the latter is 443.

D. The HTTP connection is simple and stateless. the HTTPS protocol is a network protocol built by the SSL + HTTP protocol for encrypted transmission and identity authentication, which is safer than the HTTP protocol.

3) functions of https

The function can be divided into two types: one is to establish an Information Security channel to ensure the security of data transmission; the other is to confirm the authenticity of the website.

A. In general, https means that the server has a certificate. The main purpose is to ensure that the server is the server he claims. This is the same as 1.1. All communications between the server and the client are encrypted.

B. Specifically, the client generates a symmetric key and exchanges the key through the server certificate, that is, the handshake process in the general sense.

C. All subsequent information exchanges will be encrypted. Even if a third party intercepts the service, it makes no sense because it does not have a key. Of course, tampering is meaningless.

D. If you have a few requirements on the client, the client must also have a certificate.

The client certificate is similar to the user name/password and a ca-authenticated identity when it represents personal information. Because the personal certificate is generally not simulated by others, so that you can further confirm your identity. At present, this is the practice of Professional edition of a few individual banks. The specific certificate may be using a USB flash disk (that is, U shield) as a backup carrier.

 

2. SSL Overview

1) Introduction

SSL (Secure Socket Layer) is developed by Netscape to ensure the security of data transmission over the Internet, it ensures that data is not intercepted or eavesdropped during network transmission. It has been widely used for identity authentication and encrypted data transmission between Web browsers and servers. The SSL protocol is located between the TCP/IP protocol and various application layer protocols to provide security support for data communication.

2) Services provided by SSL

A. authenticate users and servers to ensure that data is sent to the correct client and server

B. Data Encryption to prevent data theft

C. maintain data integrity and ensure that data is not changed during transmission.

3) handshake process of the SSL protocol

SSL uses both public key encryption and symmetric encryption. Although symmetric encryption is faster than public key encryption, public key encryption provides better identity authentication. The SSL handshake protocol is very effective for customers and servers to complete identity authentication. The main process is as follows:

① The client browser transmits the SSL protocol version number of the client to the server, encryptedAlgorithmTypes, random numbers, and various information required for communication between other servers and clients.

② The server sends the version number, type of encryption algorithm, random number, and other related information of the SSL protocol to the client, and the server also sends its own certificate to the client.

③ The client uses the information sent from the server to verify the server's legitimacy. The server's legitimacy includes: whether the certificate expires, and whether the CA that issues the server certificate is reliable, whether the public key of the issuer certificate can properly unbind the "digital signature of the issuer" of the server certificate, and whether the domain name on the server certificate matches the actual Domain Name of the server. If the legality verification fails, the communication will be disconnected. If the legality verification passes, the fourth step will continue.

④ The user end generates a random "symmetric password" for subsequent communication, and then encrypts it with the server's public key (the server's public key is obtained from the server certificate in step 2, then it is sent to the server.

⑤ The server uses the private key to decrypt the "symmetric password" (the public key and the private key are mutually related. The data encrypted by the Public Key can only be decrypted by the private key, and the private key is only kept on the server side. For details, see: http://zh.wikipedia.org/wiki/RSA%E7% AE %97%E6%B3%95), and then use it as the "Call password" for the server and client to encrypt and decrypt the communication. At the same time, data communication integrity must be completed during SSL communication to prevent any changes in data communication.

⑥ The client sends a message to the server, indicating that the next data communication will use the master password in step 5 as a symmetric key, and notifying the Server client that the handshake process is complete.

7. The server sends a message to the client, indicating that the master password in step 5 will be used for subsequent data communication as a symmetric key, and notifying the client server end of the handshake process.

The handshake part of the SSL protocol ends, and the data communication of the SSL Secure Channel begins. The customer and the server start to use the same symmetric key for data communication, and the communication integrity is verified.

 

3. Configure the server certificate

To implement SSL, a Web server must have a certificate (certificate) for each external interface (IP address) that accepts secure connections ). The theory of this design is that a server must provide a reasonable guarantee to prove that the host of the server is the one you think. This certificate indicates the company associated with the website and some basic contact information of the website owner or system administrator.

This certificate is signed by everyone using a password, and it is very difficult for others to forge it. For websites that conduct e-commerce or any business transaction that is essential to identity authentication, the certificate should be issued to the well-known Certification Authority (CA )) for example, Verisign or thawte. This certificate can be proved by electronic technology. In fact, the certification authority will guarantee the authenticity of the certificate it issued. If you trust the authority that issued the certificate, you can believe that the certificate is valid.

For more information about how to apply for an authoritative certificate, see: http://www.cnblogs.com/mikespook/archive/2004/12/22/80591.aspx

In many cases, authentication is not really worrying. The system administrator may only want to ensure that the data transmitted and received by the server is confidential and will not be stolen by the leader on the connection line. Fortunately, Java provides a relatively simple command line tool called keytool, which can generate a "self-signed" certificate. A self-signed certificate is only a user-generated certificate. It has not been officially registered with the well-known authentication authority. Therefore, it cannot be ensured. But it can ensure the security of data transmission.

To configure SSL using tomcat, follow these two steps:

1) generate a certificate

A. execute the following command line:

% Java_home % \ bin \ keytool-genkey-alias tomcat-keyalg RSA

In this command, keytool is a tool that comes with JDK to generate certificates. The RSA algorithm is the primary security algorithm, which ensures compatibility with other servers and components.

This command will generate a new file named ". keystore" in your home directory. After the command is executed, you must first display the keystore password. The default password for Tomcat is "changeit" (all in lower case). If you want to use it, you can specify your own password. You also need to specify your password in the server. xml configuration file, which will be described later.

B. You will be asked to provide general information about the certificate, such as the company name and contact name. This information will be displayed to those who attempt to access youProgramTo ensure that the information provided here corresponds to what they expect.

C. You will be asked to present the key password, which is the unique password of the certificate (different from other certificates stored in the same keystore file ). You must use the same password as the keystore password here. (Currently, keytool prompts you to press enter to automatically help you do this ).

If everything goes well, you now have a keystore file that can be used by your server.

2) Configure Tomcat

The second step is to configure the secure socket in the $ catalina_home/CONF/server. xml file. $ Catalina_home indicates the directory where Tomcat is installed. One example is that the SSL connector element is included in the default server. xml file installed with Tomcat. It looks like this:

$ Catalina_home/CONF/server. xml

<  --  Define a SSL coyote HTTP/1.1 Connector on port 8443 --  > 

< ! --

<Connector

Port = "8443" Minprocessors = "5" Maxprocessors = "75"

Enablelookups = "True" Disableuploadtimeout = "True"

Acceptcount = "100" Debug = "0" Scheme = "HTTPS" Secure = "True" ;

Clientauth = "False" Sslprotocol = "TLS" />

-->

The default form of the connector element is commented out, so you need to delete the annotation mark around it. Then, you can customize (set by yourself) specific attributes as needed. Generally, you need to add the keystorefile and keystorepass attributes to specify the path for storing the certificate (for example, keystorefile = "C :/. keystore ") and the password you just set (for example, keystorepass =" 123456 "). For more information about other options, see server configuration reference.

After completing these configuration changes, you must restart tomcat, and then you can access any web applications supported by Tomcat through SSL. The command must be as follows: https: // localhost: 8443

 

4. ClientCodeImplementation

A key class is used to access HTTPS links in Java.HttpsurlconnectionSee the following implementation code:

         //  Create a URL object  
URL myurl = New URL ("https://www.sun.com ");

// Create an httpsurlconnection object and set its sslsocketfactory object
Httpsurlconnection httpsconn = (httpsurlconnection) myurl. openconnection ();

// Gets the input stream of the connection to read the response content
Inputstreamreader insr = New Inputstreamreader (httpsconn. getinputstream ());

// Read Server Response Content and Display
Int Respint = insr. Read ();
While (Respint! =-1 ){
System. Out. Print (( Char ) Respint );
Respint = insr. Read ();
}

When the connection is obtained and accessed by a normal browserVerify that the server certificate is trusted(Issued by an authority or signed by an authority). If the server certificate is not trusted, the default implementation will be problematic.SunjsseThe following exception is thrown:

 
Javax.net. SSL. sslhandshakeexception: Sun. Security. validator. validatorexception: pkix path Building
 
Failed: Sun. Security. provider. certpath. suncertpathbuilderexception: unable to find valid certification path to requested target

As mentioned above, sunjsse (Java Secure Socket Extension) is a collection of packages for secure Internet communication. It is a pure Java implementation of SSL and TLS. It can transparently provide data encryption, server authentication, information integrity, and other functions, this allows us to use a secure socket established by JSSE just like a common socket. JSSE is an open standard. Not only can Sun implement a sunjsse, but in fact other companies have their own JSSE, which can then be used in JVM through JCA.

For details about JSSE, refer to reference: http://java.sun.com/j2se/1.5.0/docs/guide/security/jsse/jsserefguide.html;
And Java security guide: http://java.sun.com/j2se/1.5.0/docs/guide/security /;

Before learning about JSSE, you need to understand a Java security concept: the truststore file of the client. The client's truststore file stores the certificate information of the server trusted by the client. When the client performs an SSL connection, JSSE determines whether to trust the server certificate based on the Certificate in this file. In sunjsse, a trust manager class determines whether to trust a remote certificate. This class has the following processing rules:
1) if the system propertyJavax.net. SLL. truststoreIf the truststore file is specified, the trust manager searches for and uses the file in the LIB/security/directory under the JRE installation path to check the certificate.
2) If the system property does not specify the truststore file, it will go to the JRE installation path to find the default truststore file, the relative path of this file is: lib/security/Jssecacerts.
3) If jssecacerts does not exist but cacerts exists (it is released along with j2sdk and contains a limited number of trusted Basic certificates), the default truststore file is lib/security/Cacerts.

How can we deal with this situation? There are two solutions:
1) according to the above rules of the trust manager,Import the public key of the server to jssecacertsOr set the path of the truststore file to be loaded in the system properties. For certificate import, run the following command: keytool-import-file src_cer_file-keystore dest_cer_store. For certificates, you can export them in the browser;
2) implement your own certificate trust manager class, suchMyx509trustmanagerThis class must implement three methods in the x509trustmanager interface. Then, load the custom class in httpsurlconnection. For details, see the following two code snippets. One is the custom certificate trust manager, the second is the code for CONNECT:

 Package Test;
Import Java. Io. fileinputstream;
Import Java. Security. keystore;
Import Java. Security. cert. certificateexception;
Import Java. Security. cert. x509certificate;
Import Javax.net. SSL. trustmanager;
Import Javax.net. SSL. trustmanagerfactory;
Import Javax.net. SSL. x509trustmanager;
Public Class Myx509trustmanager Implements X509trustmanager {
/*
* The default x509trustmanager returned by sunx509. we'll delegate
* Decisions to it, and fall back to the logic in this class if
* Default x509trustmanager doesn' t trust it.
*/
X509trustmanager sunjssex509trustmanager;
Myx509trustmanager () Throws Exception {
// Create a "default" JSSE x509trustmanager.
Keystore Ks = keystore. getinstance ("jks ");
KS. Load ( New Fileinputstream ("trustedcerts "),
"Passphrase". tochararray ());
Trustmanagerfactory TMF =
Trustmanagerfactory. getinstance ("sunx509", "sunjsse ");
TMF. INIT (KS );
Trustmanager TMS [] = TMF. gettrustmanagers ();
/*
* Iterate over the returned trustmanagers, look
* For an instance of x509trustmanager. If found,
* Use that as our "default" trust manager.
*/
For ( Int I = 0; I <TMS. length; I ++ ){
If (TMS [I] Instanceof X509trustmanager ){
Sunjssex509trustmanager = (x509trustmanager) TMS [I];
Return ;
}
}
/*
* Find some other way to initialize, or else we have to fail
* Constructor.
*/
Throw New Exception ("couldn't initialize ");
}
/*
* Delegate to the default trust manager.
*/
Public Void Checkclienttrusted (x509certificate [] Chain, string authtype)
Throws Certificateexception {
Try {
Sunjssex509trustmanager. checkclienttrusted (chain, authtype );
} Catch (Certificateexception excep ){
// Do any special handling here, or rethrow exception.
}
}
/*
* Delegate to the default trust manager.
*/
Public Void Checkservertrusted (x509certificate [] Chain, string authtype)
Throws Certificateexception {
Try {
Sunjssex509trustmanager. checkservertrusted (chain, authtype );
} Catch (Certificateexception excep ){
/*
* Possibly pop up a dialog box asking whether to trust
* Cert chain.
*/
}
}
/*
* Merely pass this through.
*/
Public X509certificate [] getacceptedissuers (){
Return Sunjssex509trustmanager. getacceptedissuers ();
}
}
// Create an sslcontext object and use the trusted manager we specified to initialize it.
Trustmanager [] TM = { New Myx509trustmanager ()};
Sslcontext = sslcontext. getinstance ("SSL", "sunjsse ");
Sslcontext. INIT ( Null , TM, New Java. Security. securerandom ());
// Obtain the sslsocketfactory object from the sslcontext object.
Sslsocketfactory SSF = sslcontext. getsocketfactory ();
// Create a URL object
URL myurl = New URL ("https://ebanks.gdb.com.cn/sperbank/perbankLogin.jsp ");
// Create an httpsurlconnection object and set its sslsocketfactory object
Httpsurlconnection httpsconn = (httpsurlconnection) myurl. openconnection ();
Httpsconn. setsslsocketfactory (SSF );
// Gets the input stream of the connection to read the response content
Inputstreamreader insr = New Inputstreamreader (httpsconn. getinputstream ());
// Read Server Response Content and Display
Int Respint = insr. Read ();
While (Respint! =-1 ){
System. Out. Print (( Char ) Respint );
Respint = insr. Read ();
}

The two methods have their own advantages. The first methodJSSE security will not be damagedBut manually import the certificate. If there are many servers, the JRE of each server must perform the same operation. method 2Higher flexibilityBut be careful with the implementation, otherwise it may leave security risks;

 

References:

Http://baike.baidu.com/view/14121.htm

Http://zh.wikipedia.org/wiki/RSA%E7% AE %97%E6%B3%95

Http://blog.csdn.net/sfdev/article/details/2957240

Http://blog.csdn.net/cyberexp2008/article/details/6695691

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.