Ext.: http://www.cnblogs.com/devinzhang/archive/2012/02/28/2371631.html
1. HTTPS Concepts
1) Introduction
HTTPS (full name: Hypertext Transfer Protocol over secure Socket Layer) is a security-targeted HTTP channel and is simply a secure version of HTTP. That is, the SSL layer is added under HTTP, the security base of HTTPS is SSL, so the detailed content of encryption needs SSL. The initial development of the system, conducted by Netscape, provides an authentication and encryption method of communication, which is now widely used in security-sensitive communications on the World Wide Web, such as transaction payments.
2) The difference between HTTPS and HTTP
A. The HTTPS protocol requires a certificate to be applied to the CA, and the general free certificate is very small and requires a fee.
B. HTTP is a Hypertext Transfer Protocol, the information is transmitted in plaintext, and HTTPS is an SSL encrypted transport protocol with security.
C. http and HTTPS use a completely different way of connecting, with the same port, the former is 80, the latter is 443.
D. HTTP connection is simple and stateless; The HTTPS protocol is a network protocol built by the SSL+HTTP protocol for encrypted transmission and authentication, which is more secure than the HTTP protocol.
3) The role of HTTPS
Its main role can be divided into two kinds: 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 HTTPS in the general sense is 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 the 1th; all communication between the service and the client is encrypted.
B. Specifically, it is the client that generates a symmetric key, exchanging the key through the server's certificate, the handshake process in the general sense.
C. All the information that follows is encrypted. Even if a third party intercepts, it doesn't make any sense, because he doesn't have a key, and of course it doesn't make sense to tamper with it.
D In the case of a small client requirement, the client must also have a certificate.
Here the client certificate, in fact, similar to the personal information, in addition to the user name/password, there is a CA authenticated identity. Because personal certificates are generally not emulated by others, all this can be a deeper confirmation of their identity. Currently a small number of personal banking Professional Edition is this practice, the specific certificate may be to take a U-Shield as a backup carrier.
2.SSL Introduction
1) Introduction
SSL (Secure Socket Layer) has been developed by Netscape to secure data transmission over the Internet, and the use of encryption (encryption) technology ensures that data is not intercepted and tapped during transmission over the network. It has been widely used for authentication and encrypted data transfer between Web browsers and servers. The SSL protocol is located between the TCP/IP protocol and various application layer protocols, providing security support for data communication.
2) services provided by SSL
A. Authenticating users and servers to ensure that data is sent to the correct client and server
B. Encrypt data to prevent the data from being stolen in the middle
C. Maintain the integrity of the data to ensure that the data is not changed during transmission.
3) Handshake process for SSL protocol
SSL protocol uses both public-key cryptography and symmetric encryption technology, although symmetric encryption technology is faster than public-key cryptography, but public key cryptography provides better authentication technology. The SSL handshake protocol is very effective in enabling mutual authentication between the client and the server, and the main process is as follows:
The browser of the ① client transmits the version number of the client SSL protocol to the server, the type of cryptographic algorithm, the random number generated, and the various information needed to communicate between the server and the client.
The ② server transmits the version number of the SSL protocol to the client, the type of encryption algorithm, the random number, and other related information, and the server also transmits its own certificate to the client.
③ customers use the information sent by the server to verify the legitimacy of the server, the legitimacy of the server includes: whether the certificate expires, the issuing server certificate of the CA is reliable, the publisher certificate's public key can correctly unlock the server certificate "publisher's digital signature", the server certificate on the domain name and the server's actual domain name match. If the legitimacy verification is not passed, the communication will be disconnected, and if the legitimacy validation passes, the fourth step will continue.
The ④ client randomly generates a "symmetric password" for subsequent communication, encrypts it with the server's public key (obtained from the server's certificate in step ②), and then passes it to the server.
The ⑤ server decrypts the "symmetric password" with the private key (where the public and private keys are interrelated, the public key-encrypted data can only be decrypted with the private key, and the private key is reserved only on the server side.) Refer to: http://zh.wikipedia.org/wiki/RSA%E7%AE%97%E6%B3%95), and then use it as the server and client "call password" encryption and decryption communication. At the same time in the process of SSL communication to complete the integrity of data communication, to prevent any changes in data communication.
The ⑥ client sends a message to the server that indicates that subsequent data traffic will use the master password in the ⑤ as the symmetric key, and notifies the server client that the handshake process is complete.
The ⑦ server sends a message to the client indicating that the subsequent data traffic will use the master password in the ⑤ as the symmetric key, and notifies the client that the server side of the handshake process is complete.
⑧ssl The handshake part ends, the SSL secure channel data communication begins, the client and the server begin to use the same symmetric key for data communication, while the integrity of the communication test.
3. Configure server-side certificates
To be able to implement SSL, a Web server must have a corresponding certificate (Certificate) for each external interface (IP address) that accepts a secure connection. The theory of this design is that a server must provide some reasonable assurance that the owner of the server is the person you think it is. This certificate states the company associated with this site, as well as some basic contact information for the owner or system administrator of the site.
The certificate is signed by the owner in the form of a password, which is very difficult for others to forge. For any commercial transaction where e-commerce (e-commerce) websites, or other identity certifications are essential, the certificate is to be purchased from a well-known certification authority (Certificate Authority (CA)) such as VeriSign or Thawte. Such certificates can be verified by electronic technology. In fact, the certification authority will guarantee the authenticity of the certificate issued by it, and if you trust the certification authority to issue the certificate, you can believe that the certificate is valid.
For the application of the authoritative certificate, please refer to: http://www.cnblogs.com/mikespook/archive/2004/12/22/80591.aspx
In many cases, certification is not really a concern. The system administrator may only want to ensure that the data transmitted and received by the server is secret and will not be stolen by the thieves on the connection line. Fortunately, Java provides a relatively simple command-line tool called Keytool, which can simply produce a "self-signed" certificate. A certificate that is signed by itself is only a user-generated certificate and is not formally registered with a recognized authority, so it is not guaranteed to be authentic. But it can guarantee the security of data transmission.
There are two major steps to configuring SSL with Tomcat:
1) Generate certificate
A. Execute at the command line:
%java_home%\bin\keytool-genkey-alias Tomcat-keyalg RSA
In this command, Keytool is the tool that comes with the JDK to generate the certificate. The RSA algorithm is used as the primary security algorithm, which guarantees compatibility with other servers and components.
This command will produce a new file called ". KeyStore" in the user's home directory. After execution, you are first asked to show the KeyStore password. The default password used by Tomcat is "Changeit" (all lowercase letters), and you can specify your own password if you wish. You also need to specify your own password in the Server.xml configuration file, which will be described later.
B. You will be asked to produce general information about this certification, such as company, contact name, etc. This information is displayed to users who try to access secure pages in your program to ensure that the information provided here corresponds to what they expect.
C. You will be required to show the key (key) password, which is the unique password for this certificate (unlike other certificates stored in the same KeyStore file). You must use the same password as the KeyStore password here. (Currently, Keytool will prompt you to press ENTER to automatically do this for you).
If all goes well, you now have a KeyStore file that can be used by your server with a certified certificate.
2) Configure Tomcat
The second big step is to configure the secure socket in the $catalina_home/conf/server.xml file. $CATALINA _home represents the directory where Tomcat is installed. An example is an SSL connector element that 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= "debug=" 0 "scheme=" https "secure=" true ";
Clientauth= "false" sslprotocol= "TLS"/>
-
The connector element itself, whose default form is commented out (commented out), needs to be removed from the annotation flags around it. Then, you can customized (set yourself) specific properties as needed. Generally need to add keystorefile and Keystorepass two properties, specify the path where you store the certificate (such as: keystorefile= "C:/.keystore") and the password you just set (such as: keystorepass= "123456 ")。 For more information on the various other options, consult the server Configuration Reference.
After you complete these configuration changes, you must restart Tomcat, and then you can access any Web applications that Tomcat supports with SSL. But the instructions need to be like this: https://localhost:8443
4. Client code Implementation
In Java to access the HTTPS link, a key class httpsurlconnectionis used, see the following implementation code:
Create a URL object
URL myurl = new URL ("https://www.sun.com");
Create a 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 ());
Reads the response content of the server and displays
int respint = Insr.read ();
while (respint! =-1) {
System.out.print ((char) respint);
Respint = Insr.read ();
}
When connection is obtained, it will still verify that the server's certificate is trusted (issued by the Authority or signed by the Authority), as is the case with normal browser access, and if the server-side certificate is not trusted, the default implementation will be problematic, generally Sunjsse will throw the following exception message:
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 |
The above mentioned Sunjsse,jsse (Java secure Socket Extension) is a collection of a series of packages that enable secure communication over the Internet. It is a pure Java implementation of SSL and TLS, can transparently provide data encryption, server authentication, information integrity and other functions, you can enable us to use the same as normal sockets using Jsse established Secure sockets. Jsse is an open standard, not just for sun companies to achieve a sunjsse, in fact other companies have their own implementation of Jsse, and then through the JCA can be used in the JVM.
For more information about Jsse, refer to the official website 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 you dive into Jsse, you need to know a concept about Java security: The client's Truststore file. The client's Truststore file holds the certificate information for the server that is trusted by the client. When the client makes an SSL connection, Jsse determines whether to trust the server-side certificate based on the certificate in the file. In Sunjsse, there is a trust manager class responsible for deciding whether to trust the remote certificate, which has the following processing rules:
1) If the system attribute Javax.net.sll.trustStore Specifies the Truststore file, then trust manager will go to the lib/security/directory under the JRE installation path to look for and use this file to check the certificate.
2) If the system attribute 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 with J2SDK with a limited number of trusted basic certificates), then this default Truststore file is lib/security/cacerts.
How do you deal with this situation? The following two options are available:
1) Follow the rules of the above trust manager to import the server's public key into Jssecacerts, or set the path of the Truststore file to be loaded in the System properties; Certificate import can be used as follows: Keytool-import-file Src_cer_file–keystore Dest_cer_store; As for the certificate can be obtained through the browser export;
2), implement your own certificate trust manager class, such as Myx509trustmanager, which must implement three method in the X509trustmanager interface And then load the custom class in Httpsurlconnection, see the following two code snippets, one for the custom certificate trust manager, and the other for the Code at 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 the
* 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
* For the instance of X509trustmanager. If found,
* Use this 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-initialize, or else we have a to fail the
* 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 the
* Cert chain.
*/
}
}
/*
* Merely pass this through.
*/
Public x509certificate[] Getacceptedissuers () {
return Sunjssex509trustmanager.getacceptedissuers ();
}
}
Create the Sslcontext object and initialize it with the trust manager that we specified.
Trustmanager[] TM = {new Myx509trustmanager ()};
Sslcontext Sslcontext = sslcontext.getinstance ("SSL", "Sunjsse");
Sslcontext.init (NULL, TM, New Java.security.SecureRandom ());
Get the Sslsocketfactory object from the above Sslcontext object
Sslsocketfactory SSF = Sslcontext.getsocketfactory ();
Create a URL object
URL myurl = new URL ("https://ebanks.gdb.com.cn/sperbank/perbankLogin.jsp");
Create a 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 ());
Reads the response content of the server and displays
int respint = Insr.read ();
while (respint! =-1) {
System.out.print ((char) respint);
Respint = Insr.read ();
}
For the above two implementations, each has its advantages, the first way does not destroy the security of the Jsse , but to manually import the certificate, if the server is a lot, the JRE of each server must do the same, the second way more flexible , but be careful to implement , otherwise it may leave a safety hazard;
Reference documents:
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
(GO) Java Secure Communication: HTTPS and SSL