Configure SSL mutual authentication for tomcat and ssl for tomcat

Source: Internet
Author: User
Tags pkcs12

Configure SSL mutual authentication for tomcat and ssl for tomcat
I. Introduction to SSL

SSL (Secure Sockets Layer) is a protocol (specification) used to ensure the security of communication between the client and the server, so as to prevent information transmitted during communication from being stolen or modified.

A session key is generated when the client and the server perform a handshake (a handshake is called when the client and the server establish a connection and exchange parameters ), this "conversation key" is used to encrypt the next data transmission. This "conversation key" is only known to the client and server. That is to say, as long as the "conversation key" is not cracked, security can be ensured.

2. client certificate and server certificate

The client certificate and server certificate are used to prove your identity, just like everyone has an ID card. This ID card is unique. Generally, you only need a server certificate, but sometimes the client needs to provide its own certificate to prove its identity.

Ii. Generate a self-Signed server certificate and import the server-side trust certificate library

Generally, a certificate can be issued by an authority, such as veri sign. Baidu uses a certificate issued by veri sign. Such an authority is trusted, however, the certificates issued by these organizations are often charged, and such certificates are hard to obtain. For small enterprises, self-signed certificates are often used to save costs.

Next, use the JDK keytool to issue a certificate. If JDK is not installed, install JDK first (JDK 7 is used in this article ). All the certificate files in this article are stored in F: \ ca. You can select a directory to store them.

Keytool-genkeypair-v-alias server-keyalg RSA-validity 3650-keystore. /server. keystore-storepass 123456-keypass 123456-dname "CN = 127.0.0.1, OU = rm, O = rm, L = gz, ST = gd, C = cn"

Note: The CN in the-dname parameter should be the ip address or domain name of the server.

   

2. Export the server certificate

Keytool-exportcert-alias server-keystore./server. keystore-file./server. cer-storepass 123456

3. Import the server certificate to the trust certificate

Keytool-importcert-alias serverca-keystore./server_trust.keystore-file./server. cer-storepass 123456

3. Generate client certificates and import them to the server-side trust certificate library

Keytool-genkeypair-v-alias client-dname "CN = rorymo"-keyalg RSA-validity 3650-keypass 123456-keystore./client. p12-storepass 123456-storetype PKCS12

2. Export client certificates

Keytool-exportcert-alias client-file./client. cer-keystore./client. p12-storepass 123456-storetype PKCS12

3. Import the client certificate to the server-side trust certificate library

Keytool-importcert-alias clientca-keystore./server_trust.keystore-file./client. cer-storepass 123456

4. view the trust certificate information of the server-side trust certificate library

Keytool-list-keystore./server_trust.keystore-storepass 123456

You can see that a server certificate and a client certificate have been imported into the trust certificate library.

5. Now we have generated the following file:

  

4. Configure tomcat and web applications

Put server. keystore and server_trust.keystore in the root directory of tomcat. For example, my tomcat directory is F: \ ca \ apache-tomcat-7.0.64.

2. Configure tomcat

Edit the conf/server. xml file and add the following Configuration:

<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol" SSLEnabled="true"               maxThreads="150" scheme="https" secure="true"               clientAuth="true" sslProtocol="TLS"               keystoreFile="${catalina.base}/server.keystore" keystorePass="123456"               truststoreFile ="${catalina.base}/server_trust.keystore" truststorePass="123456"/>

Note:

  • If clientAuth is true, SSL mutual authentication is enabled.
  • KeystoreFile specifies the certificate location on the server
  • TruststoreFile specifies the server-side trust certificate library

3. Compile a servlet for obtaining the client certificate

1 package com. rorymo. demo. ssl; 2 3 import java. io. IOException; 4 import java. io. printWriter; 5 import java. security. cert. x509Certificate; 6 7 import javax. servlet. servletException; 8 import javax. servlet. annotation. webServlet; 9 import javax. servlet. http. httpServlet; 10 import javax. servlet. http. httpServletRequest; 11 import javax. servlet. http. httpServletResponse; 12 13/** 14*15 * SSLServlet16 * 17 * @ Author rorymo18 * @ version 1.019 */20 @ WebServlet ("/SSLServlet") 21 public class SSLServlet extends HttpServlet {22 23 private static final long serialVersionUID = 1601507150278487538L; 24 private static final String REQUEST_ATTR_CERT = "javax. servlet. request. x509Certificate "; 25 private static final String CONTENT_TYPE =" text/plain; charset = UTF-8 "; 26 private static final String DEFAULT_ENCODING = "UTF-8"; 27 private static final String SCHEME_HTTPS = "https"; 28 29 public void doGet (HttpServletRequest request, HttpServletResponse response) 30 throws ServletException, IOException {31 response. setContentType (CONTENT_TYPE); 32 response. setCharacterEncoding (DEFAULT_ENCODING); 33 PrintWriter out = response. getWriter (); 34 X509Certificate [] certs = (X509Certificate []) request. getAttribute (REQUEST_ATT R_CERT); 35 if (certs! = Null) {36 int count = certs. length; 37 out. println ("[" + count + "] client certificates detected"); 38 for (int I = 0; I <count; I ++) {39 X509Certificate cert = certs [I]; 40 out. println ("client certificate [" + cert. getSubjectDN () + "]:"); 41 out. println ("is the certificate valid:" + (verifyCertificate (cert )? "Yes": "no"); 42 out. println ("certificate details: \ r" + cert. toString (); 43} 44} else {45 if (SCHEME_HTTPS.equalsIgnoreCase (request. getScheme () {46 out. println ("this is an HTTPS request, but there is no available client certificate"); 47} else {48 out. println ("this is not an HTTPS request, so you cannot obtain the client certificate List"); 49} 50} 51 out. close (); 52} 53 54 public void doPost (HttpServletRequest request, HttpServletResponse response) 55 throws ServletException, IOException {56 doGet (request, response ); 57} 58 59/** 60*61 * check whether the certificate has expired 62*63*64 * @ param certificate65 * @ return66 */67 private boolean verifyCertificate (X509Certificate certificate) {68 boolean valid = true; 69 try {70 certificate. checkValidity (); 71} catch (Exception e) {72 e. printStackTrace (); 73 valid = false; 74} 75 return valid; 76} 77 78}

 

 

4. Add the following configuration to the web. xml file of the web application:

  <security-constraint>    <web-resource-collection>      <web-resource-name>SSL</web-resource-name>      <url-pattern>/SSLServlet</url-pattern>    </web-resource-collection>    <user-data-constraint>      <description>SSL required</description>      <transport-guarantee>CONFIDENTIAL</transport-guarantee>    </user-data-constraint>  </security-constraint>

Note:

  • If this configuration is not added, all access addresses must use SSL for access. Sometimes, we only need to obtain client certificates through one or more SSL addresses to authenticate user identities, after successful authentication, you do not need to use SSL for access. (Multiple security-constraint can be configured)
  • Url-pattern: Specifies the address that requires SSL for access.
  • Transport-guarantee: Valid values include NONE, INTEGRAL, and CONFIDENTIAL. If transport-guarantee is set to NONE, the communication protocols used are not limited. The INTEGRAL value indicates that the data must be transmitted in a way that prevents the person who intercepts it from reading it. Although, in principle (and in future HTTP versions), there may be differences between INTEGRAL and CONFIDENTIAL, in the current practice, they simply require the use of SSL
  • Create SSLServlet to obtain client certificate
V. Test

Because we use two-way authentication, we also need the client certificate. Next we import the client certificate:

  • Double-click client. p12

  

  • Click Next

  • Click Next until the certificate is installed. (follow the prompts to perform the operation)
  • View the installed client certificate. Because I use the Google Chrome browser (other browsers may be different), choose Settings> Advanced Settings> Manage certificates.

 

  

 

2. Re-access the above address: http: // 127.0.0.1: 8080/SSL/SSLServlet

The browser prompts you to select the client certificate for authentication. We click OK to open a warning page, prompting us that the server certificate is untrusted.

  

 

 

The icon in the address bar has a Red Cross:

Of course, you can click it to open it.

  

To avoid this warning, you can import the server certificate to the client.

A. Import the server certificate to the client

    • Double-click server. cer

    • Click "Install Certificate", select the storage location of the Certificate "Trusted Root Certificate Authority", and click "Next" until the certificate is installed.

      

 

    • View the server certificate we have installed

 

B. Close the browser and visit again.

Vi. Appendix
    • -Genkeypair creates a default file in the user's home directory ". "keystore" will also generate an alias for mykey, which contains the user's public key, private key, and certificate (if no generated location is specified, the keystore will have the user's default directory)
    • -Alias generates aliases. Each keystore is associated with this unique alias. This alias is usually case insensitive.
    • -Keystore specifies the path of the keystore (the generated information will not be in the. keystore file)
    • -Keyalg specifies the key algorithm (such as RSA and DSA). The default value is DSA)
    • -Validity: Specifies the validity period of the created certificate (90 by default)
    • -Keysize: Specifies the key length (1024 by default)
    • -Storepass: Specifies the password of the keystore (the password required for obtaining keystore Information)
    • -Keypass: Specifies the password of an Alias Entry (private key password)
    • -Dname indicates the issuer of the Certificate. "CN = first and last names, OU = organization name, O = Organization Name, and L = Name of the city or region, ST = state or province name, C = two-letter country code of the unit"
    • -List: displays the certificate information in the keystore, for example, keytool-list-v-keystore path/to/keystore-storepass password.
    • -V: displays the certificate details in the keystore.
    • -Exportcert: export the certificate of the specified alias, for example, keytool-exportcert-alias theAlias-keystore path/to/keystore-file path/to/keystore/cert-storepass pass
    • -The file parameter specifies the file name to be exported.
    • -Delete: delete the keytool-delete-alias theAlias-keystore path/to/keystore-storepass pass entry in the keystore.
    • -Print the certificate details on the printcert console, for example, keytool-printcert-file path/to/keystore/cert-v
    • -Keypasswd: Modify the keytool-keypasswd-alias theAlias-keypass oldPass-new newPass-storepass keystorePass-keystore path/to/keystore
    • -Storepasswd: Modify the keystore password keytool-storepasswd-keystore path/to/keystore-storepass oldPass-new newPass
    • -Importcert: import the signed digital certificate to the keystore keytool-importcert-alias certAlias-keystore path/to/keystore-file path/to/keystore/cert


2. Download the source code of this Article

 


[End]

Thank you for reading

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.