Thursday, May 6, 2010

WebService|mutual way ssl certificate with coding and installation

Using JAX-WS-Based Web Services with SSL E-mail
User Rating: / 23 
PoorBest 

This Tech Tip reprinted with permission by java.sun.com

In Java EE 5, a web service that is based on JAX-WS can be implemented either as an EJB endpoint or servlet endpoint. An example of a JAX-WS-based web service implemented as an EJB endpoint is provided in the Tech Tip Developing Web Services Using EJB 3.0. A JAX-WS-based web service implemented as a servlet endpoint is provided in the Tech Tip Developing Web Services Using JAX-WS.

Irrespective of the way a web service is implemented, most enterprise applications, including those that use web services, need to run in asecure environment. Transport Layer Security (TLS)/Secure Sockets Layer (SSL) is a point-to-point secure transport mechanism that can be used for authentication, message integrity, and confidentiality. TLS/SSL (or in this tip, simply "SSL") meets the security requirements of most enterprise application environments, and is widely adopted.

This Tech Tip shows you how to construct a JAX-WS-based web service that runs with SSL, and how to access the web service from an application client. A sample package accompanies the Tech Tip. It demonstrates a Java client accessing a JAX-WS web service using SSL. Examples are provided for web services implemented as EJB and servlet endpoints. The sample uses an open source reference implementation of Java EE 5 called GlassFish. You can download GlassFish from the GlassFish Community Downloads page.

Write the Class for the Web Service Endpoint

Let's begin by writing a Java class for the web service. SSL has no impact on the Java code for the web service endpoint. The same code works for web services that use SSL or that don't use SSL.

In Java EE 5, you can use annotations to easily construct a JAX-WS web service. Here's an example of a web service implemented as an EJB endpoint:

   package ejbws;

   import javax.annotation.Resource;
   import javax.ejb.Stateless;
   import javax.jws.WebService;
   import javax.xml.ws.WebServiceContext;

   @Stateless
   @WebService
   public class HelloEjb {
       @Resource WebServiceContext wsContext;

       public String hello(String msg) {
           return "Ejb WS: " + wsContext.getUserPrincipal() 
           + ": " + msg;
       }
   }

The @Stateless annotation marks the class as a stateless session bean, and the @WebService annotation marks the class as a web service. The @Resource annotation is used to declare resource dependencies that the class has -- in essence, what resources the class needs. These resources are then injected into the endpoint implementation. In this example, the annotation identifies a resource dependency on the WebServiceContext. The class needs the WebServiceContext to get context information about requests, such as related security information.

Here's the same web service implemented as a servlet endpoint:

   package servletws;

   import javax.annotation.Resource;
   import javax.jws.WebService;
   import javax.xml.ws.WebServiceContext;

   @WebService
   public class HelloServlet {
       @Resource WebServiceContext wsContext;

       public String hello(String msg) {
           return "Servlet WS: " + wsContext.getUserPrincipal() 
           + ": " + msg;
       }
   }

Specify Security Information in Deployment Descriptors

To use SSL in a web service that is implemented as an EJB endpoint, you need to specify security information in a vendor-specific deployment descriptor (in this tip, sun-ejb-jar.xml). For a web service implemented as a servlet, you need to specify the security information in the web.xml descriptor.

One important aspect of secure communication through SSL is server authentication, that is, confirming the identity of the server to the client. Another aspect is client authentication, where the server confirms the identity of the client. In SSL, you can have either server authentication or the combination of server and client authentication (but not client authentication alone). This tip uses the term "mutual authentication" to mean the combination of server and client authentication. (Note however that other documents might attach a different meaning to mutual authentication. For example, in some documents, the term client authentication is synonymous with mutual authentication.)

To enable SSL server authentication, you need to set the <transport-guarantee> element to CONFIDENTIAL. For a web service implemented as an EJB endpoint, you set the element in the sun-ejb-jar.xml deployment descriptor. For a web service implemented as a servlet, you set the element in the web.xml deployment descriptor. As an example, for the HelloEjb web service, the <transport-guarantee> element in the sun-ejb-jar.xml deployment descriptor should look this:

   <ejb>
     <ejb-name>HelloEjb</ejb-name>
     <webservice-endpoint>
       <port-component-name>HelloEjb</port-component-name>
       <transport-guarantee>CONFIDENTIAL</transport-guarantee>
     </webservice-endpoint>
   </ejb>

For the HelloServletService service, the <transport-guarantee> element web.xml deployment descriptor should look like this:

   <security-constraint>
     <web-resource-collection>
       <web-resource-name>Secure Area</web-resource-name>
       <url-pattern>/HelloServletService/HelloServlet
       </url-pattern>
       <http-method>POST</http-method>
     </web-resource-collection>
     <auth-constraint>
       <role-name>EMPLOYEE</role-name>
     </auth-constraint>
     <user-data-constraint>
       <transport-guarantee>CONFIDENTIAL</transport-guarantee>
     </user-data-constraint>
   </security-constraint>

Notice the <http-method> element value of POST in web.xml. JSR-109, "Implementing Enterprise Web Services", specifies that the service endpoint authorization must be defined using an http-method element value of POST.

In GlassFish, WSDL files are protected by SSL for endpoints with SSL or SSL mutual authentication. For SSL mutual authentication, you need to set the <auth-method> subelement of the <login-config> element to CLIENT-CERT. You also need to set the <transport-guarantee> element to CONFIDENTIAL. For instance, in sun-ejb-jar.xml;

   <ejb>
     <ejb-name>HelloEjb</ejb-name>
     <webservice-endpoint>
       <port-component-name>HelloEjb</port-component-name>
       <login-config>
         <auth-method>CLIENT-CERT</auth-method>
         <realm>certificate</realm>
       </login-config>
       <transport-guarantee>CONFIDENTIAL</transport-guarantee>
     </webservice-endpoint>
  </ejb>

   <security-constraint>
     <web-resource-collection>
       <web-resource-name>Secure Area</web-resource-name>
       <url-pattern>/HelloServletService/HelloServlet
       </url-pattern>
       <http-method>POST</http-method>
     </web-resource-collection>
     <auth-constraint>
       </role-name>EMPLOYEE</role-name>
     </auth-constraint>
     <user-data-constraint>
       <transport-guarantee>CONFIDENTIAL</transport-guarantee>
     </user-data-constraint>
   </security-constraint>
   <login-config>
     <auth-method>CLIENT-CERT</auth-method>
     <realm-name>certificate</realm-name>
   </login-config>

No deployment descriptor is needed for the client program.

Package and Deploy the Web Service Application

Packaging and deploying a web service application that uses SSL is the same as for a web service application that doesn't use SSL. Keep in mind however, that if the web service is implemented as a servlet endpoint in an enterprise archive (that is, a .ear file), you need to include the application.xml file to specify the context-root for the web application.

Write the Client

After deploying the web service, you can access it from a client program. The client program for a web service application that uses SSL is essentially the same as one that doesn't use SSL. The major difference is that instead of using HTTP as the internet protocol, you need to use HTTPS. In the client, you use the @WebServiceRef annotation to declare a reference to a web service. The value of the wsdlLocation parameter in @WebServiceRef is a URL that points to the location of the WSDL file for the service being referenced. So for a web service client that uses SSL, the wsdlLocation parameter in the @WebServiceRef annotation needs to specify an HTTPS URL. For example:

   @WebServiceRef(wsdlLocation=        "https://serverName:8181/HelloEjbService/HelloEjb?WSDL")    private static HelloEjbService helloEjbService; 

You can then access the port for the web service and invoke the web service:

    HelloEjb helloEjbPort = helloEjbService.getHelloEjbPort();    helloEjbPort.hello("Hello World"); 

Client-side artifacts are generated by accessing the WSDL file through HTTPS. To do that, you need to specify the location of a truststore file for the server and its password in the environment variable VMARGS. In SSL, you can use certificates to authenticate the server or for mutual authentication of both the server and client. The truststore file for the server contains the trusted certificates for the server and its keys.

You can specify the location of the server's truststore file and its password in various ways, for example, you can specify them in an ant script as follows:

   <exec executable="wsimport">
     <env key="VMARGS" 
         value="-Djavax.net.ssl.trustStore=${truststore.location} 
         -Djavax.net.ssl.trustStorePassword=${ssl.password}"/>
    <arg line="-keep -d ${client.build} 
    https://serverName:8181/HelloEjbService/HelloEjb?WSDL"/>
   </exec>

Set Up the Client Truststore and Keystore

In addition to a truststore file for the server, you also need a truststore file for the client. The client validates the server certificate against a set of certificates in its truststore. For a secure connection to be made using SSL, the client-side truststore needs to trust the server certificate. For SSL mutual authentication, the server-side truststore also needs to trust the client certificate. If you modify the server-side truststore, you need to restart the server (this allows use of the new certificate). You might not need to do this in a production environment because production certificates are signed by a common Certificate Authority (CA). The GlassFish builds include certificates for several common root CAs.

For SSL mutual authentication, you need to provide your own key in a client keystore (a file that contains the client's keys and certificates). You can use keytool, a key and certificate management utility in JDK 5.0, to generate the keystore.

Run the Client

Before you run the client that access a web service with SSL, you need to set the value of the environment variable, VMARGS. After that, you can run the application as usual. For SSL, set the value of VMARGS to:

   -Djavax.net.ssl.trustStore=${truststore.location}     -Djavax.net.ssl.trustStorePassword=${ssl.password} 

For SSL mutual authentication, set the value of VMARGS to:

   -Djavax.net.ssl.trustStore=${truststore.location}     -Djavax.net.ssl.trustStorePassword=${ssl.password}     -Djavax.net.ssl.keyStore =${keystore.location}     -Djavax.net.ssl.keyStorePassword=${ssl.password} 

Running the Sample Code

To install and run the sample code that accompanies this tip:

  1. If you haven't already done so, download GlassFish from the GlassFish Community Downloads Page, and install it.
  2. Set the following environment variables:
    •  GLASSFISH_HOME. This should point to where you installed GlassFish.
    • ANT_HOME. This should point to where ant is installed. Ant is included in the GlassFish bundle that you downloaded. (In Windows, it's in the lib\ant subdirectory.)
    • JAVA_HOME. This should point to the location of JDK 5.0 on your system.

    Add $JAVA_HOME/bin, $ANT_HOME/bin, and $GLASSFISH_HOME/bin to your PATH environment variable.

  3. Download the sample package and extract its contents. You should now see the newly extracted directory as <sample_install_dir>/ttmay2006ws-ssl, where <sample_install_dir> is the directory in which you installed the sample package. The ws-ssl directory below ttmay2006ws-ssl contains the source files and other support files for the sample.
  4. Change to the ws-ssl directory and edit the build.properties file as appropriate. For example, if the admin host is remote, change the value of admin.host from the default localhost to the appropriate remote host. Also, make sure that the following properties are correctly specified:
    •  server.cert.cn. The CN name of the server certificate. It should be the host name or the fully-qualified domain name. In the default installation of GlassFish, the server certificate has the alias name s1as. You can display the CN by issuing the following command:
    •                     keytool -list -v -alias s1as -keystore                      $GLASSFISH_HOME/domains/domain1/config/cacerts.jks 

      In response, you'll be prompted for a keystore password. Respond with the default password, changeit. You can change the password.

    • admin.user. The ID of the administrator who starts and stops the domain.
    • admin.port. The http port number of administrative server.
    • https.port. The https port number of server.
  5. Update the value of AS_ADMIN_PASSWORD in the passwd file to the administrator password.
  6. Set up the client key and certificate, by entering the following command:
  7.             ant setup 

    This creates a private key in a local keystore, exports the certificate, and imports it to the common truststore. Note that a self-signed certificate is installed in the truststore. This is for testing purposes only and is not recommended for production.

  8. If GlassFish is running, stop it as follows:
  9.             $GLASSFISH_HOME/bin/asadmin stop-domain domain1 

    Then start it:

                        $GLASSFISH_HOME/bin/asadmin start-domain domain1 

    This picks up the new certificate in the truststore.

  10. Build and deploy the sample. First enter the following command:
  11.             ant build 

    This compiles the EJB and Servlet Web Services classes and creates an ear file.

    Then enter the command:

                ant deploy 

    This deploys the ear file in GlassFish.

    And finally, the following command:

                ant build-client 

    This generates artifacts and compiles the client-side code.

  12. Run the client application to access the web service with SSL. Enter the following command:
  13.             ant run 

    You should see results that look something like this:

                [exec] Retrieving port from the service              ejbws.HelloEjbService@4e21db             [exec] Invoking hello operation on the              HelloEjbService port             [exec] Ejb WS: CN=serverName, OU=SSLClient, O=EJTechTips,              L=Santa Clara, ST=California, C=US: Hello World             [exec] Retrieving port from the service              servletws.HelloServletService@ea7549             [exec] Invoking hello operation on the              HelloServletService port             [exec] Servlet WS: CN=serverName, OU=SSLClient,              O=EJTechTips, L=Santa Clara, ST=California,              C=US: Hello World 

    You can see additional information, such as information about the SSL handshake, by adding jvm option -Djavax.net.debug=ssl,handshake. You can do this for the sample by entering the following command:

                 ant run-debug 

    You can verify that this is an SSL mutual authentication by looking at the CertificateRequest during handshake.

    If you want to see more debugging information, use the jvm option -Djavax.net.debug=all.

  14. You can undeploy the Web Service ear file, by entering the command:
  15.              ant undeploy 
  16. After you undeploy the application, remove the generated client certificate from the keystores and restart the server so that the certificate is removed from memory. To do that, enter the commands:
  17.              ant unsetup              $GLASSFISH_HOME/bin/asadmin stop-domain domain1              $GLASSFISH_HOME/bin/asadmin start-domain domain1   

About the Author

Shing Wai Chan is a senior member of the Sun Java Application Server and Java EE SDK development teams. He has been focusing on development projects that relate to security, annotations, CMP, B2B and B2C.

Copyright (c) 2004-2005 Sun Microsystems, Inc.
All Rights Reserved.


WebService|client ssl/https using code example

FRIDAY, OCTOBER 13, 2006

Using HTTPS with Web Services

Prerequisites:
In this article you have 


Add HTTPS to OC4J

Creating of the Keystore

The first thing to do to secure OC4J would be to create a new keystore that will contain the different certificates. The easiest way to do that for a Java developer is to use SUN's keytool:
keytool -genkey -alias oracle-server -dname "CN=Tug Grall, OU=Blog O=Grall And Co L=Redwood Shores, S=CA, C=US" -keyalg RSA -keypass welcome -storepass welcome -keystore server.keystore
You can copy the server.keystore into the $ORACLE_HOME/j2ee/home/config to simplify the next steps.


Configuring OC4J

OC4J stand alone is using the notion of Web-Site to expose HTTP resources (Web Applications). The default-web-site is define is he $ORACLE_HOME/j2ee/home/config/default-web-site.xml. To secure an OC4J you can follow the steps describe in the OC4J Security guidethat I have summarized in the following section.

What we want to achieve for the purpose of the demonstration is to have OC4J using HTTP and HTTPS, on port 8888 and 4443 for example. 

1. Copy default-web-site.xml to  secure-web-site.xml

2. Edit the secure-web-site.xml:
    2.1. Change the web-site tag by changing the port to 4443 and adding the element secure="true"
    2.1. Add the ssl-config element and point this to the new created keystore.
    The file looks like:

<web-site   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:noNamespaceSchemaLocation="http://xmlns.oracle.com/oracleas/schema/web-site-10_0.xsd"
            port="4443"
            secure="true"
            display-name="OC4J 10g (10.1.3) Default Web Site"
            schema-major-version="10"
            schema-minor-version="0" >
        ...
        <ssl-config keystore="server.keystore" keystore-password="welcome" />
        ...
</web-site>

3. Import the new Web site in your OC4J instance by editing the $ORACLE_HOME/j2ee/home/server.xml file. You need to add or replace the web-site tag. In my case I want to add the secure web site to my instance so the configuration looks like:

    ...    
    <web-site default="true" path="./default-web-site.xml" />
    <web-site path="./secure-web-site.xml" />
    ...

Since we have copied the file from the default-web-site, all applications are available using HTTP and HTTPS 

Start OC4J and test the HTTPS port

Start OC4J using the standard Java command or shell script, I am adding the Java Network debug flag that would help you to see what is happening at the SSL level.

    java -Djavax.net.debug=ssl -jar oc4j.jar

You should be able to access the service WSDL using the HTTPS port for example in my case:


Consuming the Service using HTTPS

Generate and configure a client Keystore

Event if this is possible to use the same keystore for the server and the client, I will guide you in the steps to create a client certificate and import the certificate from the existing -server- one. Here the command to create a new keystore:
keytool -genkey -alias oracle-client -dname "CN=John Doe, OU=Blog O=MyDummyClient, S=CA, C=US" -keyalg RSA -keypass welcomeClient -storepass welcomeClient -keystore client.keystore

The next step is to export the certificate from the server keystore to be able to import it in the client:
keytool -keystore server.keystore -export -alias oracle-server -file server.cer

You can now import the cerificate in the client keystore:
keytool -keystore client.keystore -import -file server.cer

Generate the proxy

You have now the client certificate so you can use the Oracle Web Service Assembler to generate the proxy. The only specific thing you have to do is to specify which key store to use when running the tool. The command to use when generating the proxy is:

java -Djavax.net.ssl.trustStore=/Users/tgrall/ssl/client.keystore
     -Djavax.net.ssl.keyStore=/Users/tgrall/ssl/client.keystore 
     -Djavax.net.ssl.trustStorePassword=welcomeClient 
     -Djavax.net.ssl.keyStorePassword=welcomeClient 
     -jar $ORACLE_HOME/webservices/lib/wsa.jar 
     -genProxy 
     -wsdl https://127.0.0.1:4443/math-service/MathServiceSoapHttpPort?WSDL


Calling the Service using secure endpoint

Configure the Java Environment to use the client store is made using the following System properties:
  • javax.net.ssl.trustStore
  • javax.net.ssl.keyStore
  • javax.net.ssl.trustStorePassword
  • javax.net.ssl.keyStorePassword
        
This could be done using different approach, property file, -D command line parameter or programmatically. To simply the example I am using the programmatic approach, the following code is part of the main method of the Client class:
  ...
   System.setProperty("javax.net.ssl.trustStore", "/Users/tgrall/ssl/client.keystore");
   System.setProperty("javax.net.ssl.keyStore", "/Users/tgrall/ssl/client.keystore");
   System.setProperty("javax.net.ssl.trustStorePassword", "welcomeClient");
   System.setProperty("javax.net.ssl.keyStorePassword", "welcomeClient");
   ...
   // Adding Debug information
   
System.setProperty("javax.net.debug", "ssl");
   ...


It is possible to change the Endpoint dynamically in the Proxy using the setEndpoint method.
  ...
  democlient.proxy.MathServiceSoapHttpPortClient myPort = new democlient.proxy.MathServiceSoapHttpPortClient();
  ...
  String ep = "https://127.0.0.1:4443/math-service/MathServiceSoapHttpPort";
  myPort.setEndpoint(ep);
  System.out.println("Result of the operation is "+ myPort.add(2,2));
  ...


You should now be able to run the client and call the service using HTTPS. This would look like:

Wednesday, May 5, 2010

java数字签名(签名生成,用证书验证签名)

来源:赛迪网
                                                                                                                                                   作者:李素科

(转载序:网上找的好文章,一篇就把我找了几天的所有东西都概括进来了,真是非常感谢作者:李素科  其实在找资料的过程当中,主要没解决的问题在于如何获得KeyStore文件中的PrivateKey,本来查jsdk 1.4 api文档就可以知道了,但是居然从上到下看了2遍,没有发现这个方法:load()  .......)
                                                                                                                                                   
证 书(Certificate,也称public-key certificate)是用某种签名算法对某些内容(比如公钥)进行数字签名后得到的、可以用来当成信任关系中介的数字凭证。证书发行机构通过发行证书 告知证书使用者或实体其公钥(public-key)以及其它一些辅助信息。证书在电子商务安全交易中有着广泛的应用,证书发行机构也称 CA(Certificate Authority)。

应用证书



证书在公钥加密应用中的作用是保证公钥在某些可信的机构发布,其在协议SSL、电子交易协议SET等方面有重要的应用。图1显示了 一个最简单的证书应用方法:



图1 证书应用方法



证书的应用步骤是:

(1) A把自己的公钥PKA送到CA(Certificate Authority);

(2) CA用自己的私钥和A的公钥生成A的证书,证书内包括CA的数字签名。签名对象包括需要在证书中说明的内容,比如A的公钥、时间戳、序列号等,为了简化这 里不妨假设证书中只有三项内容:A的公钥PKA、时间戳TIME1、序列号IDA。那么CA发送给A的简单证书凭证可表达 为:CertA=Eca[TIME1,IDA,PKA];

(3) B同样把自己的公钥PKB送到CA;

(4) B得到CA发布的证书CertB;

(5) A告知B证书CertA;

(6) B告知A证书CertB。

A、 B各自得到对方证书后,利用从CA得到的公钥(在CA的自签证书中)验证彼此对方的证书是否有效,如果有效,那么就得到了彼此的公钥。利用对方的公钥,可 以加密数据,也可以用来验证对方的数字签名。

本文为了方便说明,并没有使用从CA获得的证书,而是通信双方各自产生自签证书,也就是说 图1的A和B并没有经过CA,不过前提是A和B之间是互相拥有对方的证书。

证书的内容和意义如表1所示(这里以通用X .509证书格式为例)。

表1 证书内容和意义


证书内容 意义
Version 告诉这个X.509证书是哪个版本的,目前有v1、V2、v3
Serial Number 由证书分发机构设置证书的序列号
Signature Algorithm Identifier 证书采用什么样的签名算法
Issuer Name 证书发行者名,也就是给这个证书签名的机构名
Validity Period 证书有效时间范围
Subject Name 被证书发行机构签名后的公钥拥有者或实体的名字,采用X.500协议,在Internet上的标志是惟一的。例 如:CN=Java,OU=Infosec,O=Infosec Lab,C=CN表示一个subject name。



对证书的详细定义及其应用相关的各种协议,这里不加详细说明,详细细节请查看RFC2450、RFC2510、RFC2511、 RFC2527、RFC2528、RFC2559、RFC2560、RFC2585、RFC2587等文档。

生成自签证书



个人或机构可以从信任的证书分发机构申请得到证书,比如说,可以从http://ca.pku.edu.cn 得到一个属于个人的证书。这里可以利用J2SDK的安全工具keytool手工产生自签证书,所谓自签证书是指证书中的"Subject Name"和"Issuer Name"相同的证书。

下面产生一个自签证书。安装完J2SDK(这里用的是J2SDK1.4)后,在J2SDK安装目录的bin目录下,有一个keytool的可执行程 序。利用keytool产生自签证书的步骤如下:

第一步,用-genkey命令选项,产生公私密钥对。在控制台界面输 入:keytool -genkey -alias testkeypair -keyalg RSA -keysize 1024 -sigalg MD5withRSA。这里的-alias表示使用这对公私密钥产生新的keystore入口的别名(keystore是用来存放管理密钥对和证书链的, 缺省位置是在使用者主目录下,以.keystore为名的隐藏文件,当然也可指定某个路径存放.keystore文件);-keyalg是产生公私钥对所 用的算法,这里是RSA;-keysize定义密钥的长度;-sigalg是签名算法,选择MD5withRSA,即用RSA签名,然后用MD5哈希算法 摘要。接下来,系统会提示进行一些输入:

输入keystore密码:  abc123
您的名字与姓氏是什么?
[Unknown]: Li
您的组织单位名称是什么?
[Unknown]: InfosecLab
您的组织名称是什么?
[Unknown]: InfosecLab Group
您所在的城市或区域名称是什么?
[Unknown]: Beijing
您所在的州或省份名称是什么?
[Unknown]: Beijing
该单位的两字母国家代码是什么
[Unknown]: CN
CN=Li, OU=InfosecLab, O=InfosecLab Group, L=Beijing, ST=Beijing, C=CN 正确吗?
[否]: y
输入<testkeypair>的主密码 (如果和 keystore 密码相同,按回车):


第二步,产生自签证书,输入以下命令:

keytool -selfcert -alias testkeypair -dname "CN=Li, OU=InfosecLab, O=InfosecLab
Group, L=Beijing, ST=Beijing, C=CN"
输入keystore密码: abc123


第三步,导出自签证书,由上面两步产生的证书,已经存放在以"testkeypair"为别名的 keystore入口了,如果使用其文件,必须导出证书。输入:

keytool -export -rfc -alias testkeypair -file mycert.crt
输入keystore密码: abc123
保存在文件中的认证 <mycert.crt>


这样,就得到了一个自签的证书mycert.crt。注意,选项rfc是把证书输出为RFC1421定义的、用 Base64最终编码的格式。

读取证书



Java为安全应用提供了丰富的API,J2SDK1.4 的JSSE (JavaTM Secure Socket Extension) 包括javax.security.certificate包,并且提供对证书的操作方法。而对证书的读操作,只用 java.security.cert. CertificateFactory和java.security.cert.X509Certificate就可以了。下面是读取证书内容的部分代 码:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.table.*;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.io.*;
public class CARead extends JPanel {
private String CA_Name;
private String CA_ItemData[][] = new String[9][2];
private String[] columnNames = {"证书字段标记","内容" };
public CARead(String CertName) {
CA_Name=CertName;
/* 三个Panel用来显示证书内容*/
JTabbedPane tabbedPane = new JTabbedPane();
JPanel panelNormal = new JPanel();
tabbedPane.addTab("普通信息", panelNormal);
JPanel panelAll=new JPanel();
panelAll.setLayout(new BorderLayout());
tabbedPane.addTab("所有信息",panelAll);
JPanel panelBase64=new JPanel();
panelBase64.setLayout(new BorderLayout());
tabbedPane.addTab("Base64编码信息",panelBase64);
/* 读取证书常规信息 */
Read_Normal(panelNormal);
/* 读取证书文件字符串表示内容 */
Read_Bin(panelAll);
/* 读取证原始Base64编码形式的证书文件 */
Read_Raw(panelBase64);
tabbedPane.setSelectedIndex(0);
setLayout(new GridLayout(1, 1));
add(tabbedPane);
}
/*以下是定义的Read_Normal(),Read_Bin(),Read_Raw()以及main()
这里省略... */
}


定义证书信息的读取函数如下:

private int Read_Normal(JPanel panel){
String Field;
try{
CertificateFactory certificate_factory=CertificateFactory.getInstance("X.509");
FileInputStream file_inputstream=new FileInputStream(CA_Name);
X509Certificate
x509certificate=(X509Certificate)certificate_factory.generateCertificate
(file_inputstream);
Field=x509certificate.getType();
CA_ItemData[0][0]="类型";
CA_ItemData[0][1]=Field;
Field=Integer.toString(x509certificate.getVersion());
CA_ItemData[1][0]="版本";
CA_ItemData[1][1]=Field;
Field=x509certificate.getSubjectDN().getName();
CA_ItemData[2][0]="标题";
CA_ItemData[2][1]=Field;
/* 以下类似,这里省略
Field=x509certificate.getNotBefore().toString();得到开始有效日期
Field=x509certificate. getNotAfter().toString();得到截止日期
Field=x509certificate.getSerialNumber().toString(16);得到序列号
Field=x509certificate.getIssuerDN().getName();得到发行者名
Field=x509certificate.getSigAlgName();得到签名算法
Field=x509certificate.getPublicKey().getAlgorithm();得到公钥算法 */
file_inputstream.close();
final JTable table = new JTable(CA_ItemData, columnNames);
TableColumn tc=null;
tc = table.getColumnModel().getColumn(1);
tc.setPreferredWidth(600);
panel.add(table);
}catch(Exception exception){
exception.printStackTrace();
return -1;
}
return 0;
}


如果以字符串形式读取证书,加入下面Read_Bin这个函数。其中 CertificateFactory.generateCertificate() 这个函数可以从证书标准编码(RFC1421定义)中解出可读信息。Read_Bin函数代码如下:

private int Read_Bin(JPanel panel){
try{
FileInputStream file_inputstream=new FileInputStream(CA_Name);
DataInputStream data_inputstream=new DataInputStream(file_inputstream);
CertificateFactory certificatefactory=CertificateFactory.getInstance("X.509");
byte[] bytes=new byte[data_inputstream.available()];
data_inputstream.readFully(bytes);
ByteArrayInputStream bais=new ByteArrayInputStream(bytes);
JEditorPane Cert_EditorPane;
Cert_EditorPane=new JEditorPane();
while(bais.available()>0){
X509Certificate
Cert=(X509Certificate)certificatefactory.generateCertificate(bais);
Cert_EditorPane.setText(Cert_EditorPane.getText()+Cert.toString());
}
Cert_EditorPane.disable();
JScrollPane edit_scroll=new JScrollPane(Cert_EditorPane);
panel.add(edit_scroll);
file_inputstream.close();
data_inputstream.close();
}catch( Exception exception){
exception.printStackTrace();
return -1;
}
return 0;
}


如果要得到原始证书编码后的信息,则可用如下代码:

private int Read_Raw(JPanel panel){
try{
JEditorPane Cert_EditorPane=new JEditorPane();
String CertText=null;
File inputFile = new File(CA_Name);
FileReader in = new FileReader(inputFile);
char[] buf=new char[2000];
int len=in.read(buf,0,2000);
for(int i=1;i<len;i++)
{
CertText=CertText+buf[i];
}
in.close();
Cert_EditorPane.setText(CertText);
Cert_EditorPane.disable();
JScrollPane edit_scroll=new JScrollPane(Cert_EditorPane);
panel.add(edit_scroll);
}catch( Exception exception){
exception.printStackTrace();
return -1;
}
return 0;
}


最后用这个小程序看一看刚才生成的证书mycert.crt内容,把文件名写入main()中:

public static void main(String[] args) {
JFrame frame = new JFrame("证书阅读器");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});
frame.getContentPane().add(new CARead("mycert.crt"),BorderLayout.CENTER);
frame.setSize(700, 425);
frame.setVisible(true);
}


证书mycert.crt的内容显示如图2所示,所有信息和Base64的显示内容,这里不再列举。



 

图2 证书mycert.crt的内容显示
 
现在已经读取了证书的一些内容,那么怎样使用证书呢?我们可以假设A和B要共享一个绝密的文件F,B信任并拥有A的 证书,也就是说B拥有A的公钥。那么A通过A和B共知的加密算法(对称密钥算法,比如DES算法)先加密文件F,然后对加密后的F进行签名和散列摘要(比 如MD5算法,目的是保证文件的完整性),然后把F发送到B。B收到文件后,先用A的证书中的公钥验证签名,然后再用通过共知的加密算法解密,就可以得到 原文件了。这里使用的数字签名,可以保证B得到的文件,就是A的,A不能否认其不拥有文件F,因为只有A拥有可以让A的公钥验证其签名的私钥,同时这里使 用DES算法加密,使得文件有保密性。

使用DES算法的加密解密函数类似,这里不对加密算法做进一步讨论,详细请看J2SDK的JSE 部分内容,加密签名、解密验证文件结构见图3。



图3 加密签名、解密验证文件结构图


加密函数中的desKeyData存放DES加密密钥,如果要在 程序中指定,可以设置为:

static byte[] desKeyData = { (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04,
(byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08 };


加密函数写成:

public static void crypt(byte[] cipherText,String outFileName){
try{
DESKeySpec desKeySpec = new DESKeySpec(desKeyData);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
Cipher cdes = Cipher.getInstance("DES");
cdes.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] ct = cdes.doFinal(cipherText);
try{
FileOutputStream out=new FileOutputStream(outFileName);
out.write(ct);
out.close();
}catch(IOException e){
e.printStackTrace();
}
}catch (Exception e){
e.printStackTrace();
}
}


其中ct就是加密后的内容,outFileName保存加密后文件的文件名。把 cdes.init(Cipher.ENCRYPT_MODE, secretKey)换成cdes.init(Cipher.DECRYPT_MODE, secretKey)就是解密文件了。

文件 加密后就要对文件签名,保证A发送到B的文件不可伪造。下面是用存放在.keystore中的私钥进行签名的函数,签名使用的摘要算法是MD5。其中 sigText是被签名内容的输入数组,outFileName是保存签名后输出文件的名称,KeyPassword是读取Keystore使用的密 码,KeyStorePath是存放.keystore文件的路径,函数代码如下:

public static void sig(byte[] sigText, String outFileName,String
KeyPassword,String KeyStorePath){
char[] kpass;
int i;
try{
KeyStore ks = KeyStore.getInstance("JKS");
FileInputStream ksfis = new FileInputStream(KeyStorePath);
BufferedInputStream ksbufin = new BufferedInputStream(ksfis);
kpass=new char[KeyPassword.length()];
for(i=0;i<KeyPassword.length();i++)
kpass[i]=KeyPassword.charAt(i);
ks.load(ksbufin, kpass);
PrivateKey priv = (PrivateKey) ks.getKey(KeystoreAlias,kpass );
Signature rsa=Signature.getInstance("MD5withRSA");
rsa.initSign(priv);
rsa.update(sigText);
byte[] sig=rsa.sign();
System.out.println("sig is done");
try{
FileOutputStream out=new FileOutputStream(outFileName);
out.write(sig);
out.close();
}catch(IOException e){
e.printStackTrace();
}
}catch(Exception e){
e.printStackTrace();
}
}


验证签名需要存放签名文件和被签名的文件以及证书,其中,updateData存放被签名文件的内 容,sigedText存放得到的签名内容,CertName是证书名。验证签名代码如下:

public static void veriSig(byte[] updateData, byte[] sigedText){
try{
CertificateFactory
certificatefactory=CertificateFactory.getInstance("X.509");
FileInputStream fin=new FileInputStream(CertName);
X509Certificate
certificate=(X509Certificate)certificatefactory.generateCertificate(fin);
PublicKey pub = certificate.getPublicKey();
Signature rsa=Signature.getInstance("MD5withRSA");
rsa.initVerify(pub);
rsa.update(updateData);
boolean verifies=rsa.verify(sigedText);
System.out.println("verified "+verifies);
if(verifies){
System.out.println("Verify is done!");
}else{
System.out.println("verify is not successful");
}
}catch(Exception e){
e.printStackTrace();
}
}


可以用keytool产生两个自签的签名证书,或者到某个CA去申请两个证书。用Java编写加密和验证程序, 上述例子只是一个非常简单的证书应用,实际协议对证书的使用(比如SSL)要比这个复杂多了。

DigitalCertificate|JAVA对于数字证书的常用操作方法 _天极网

 import java.security.*;

  import java.io.*;

  import java.util.*;

  import java.security.*;

  import java.security.cert.*;

  import sun.security.x509.*

  import java.security.cert.Certificate;

  import java.security.cert.CertificateFactory;

  二:从文件中读取证书

  用keytool将.keystore中的证书写入文件中,然后从该文件中读取证书信息

  CertificateFactory cf=CertificateFactory.getInstance("X.509");

  FileInputStream in=new FileInputStream("out.csr");

  Certificate c=cf.generateCertificate(in);

  String s=c.toString();

  三:从密钥库中直接读取证书

  String pass="123456";

  FileInputStream in=new FileInputStream(".keystore");

  KeyStore ks=KeyStore.getInstance("JKS");

  ks.load(in,pass.toCharArray());

  java.security.cert.Certificate c=ks.getCertificate(alias);//alias为条目的别名

  四:JAVA程序中显示证书指定信息

  System.out.println("输出证书信息:\n"+c.toString());

  System.out.println("版本号:"+t.getVersion());

  System.out.println("序列号:"+t.getSerialNumber().toString(16));

  System.out.println("主体名:"+t.getSubjectDN());

  System.out.println("签发者:"+t.getIssuerDN());

  System.out.println("有效期:"+t.getNotBefore());

  System.out.println("签名算法:"+t.getSigAlgName());

  byte [] sig=t.getSignature();//签名值

  PublicKey pk=t.getPublicKey();

  byte [] pkenc=pk.getEncoded();

  System.out.println("公钥");

  for(int i=0;i< p>

  五:JAVA程序列出密钥 库所有条目

  String pass="123456";

  FileInputStream in=new FileInputStream(".keystore");

  KeyStore ks=KeyStore.getInstance("JKS");

  ks.load(in,pass.toCharArray());

  Enumeration e=ks.aliases();

  while(e.hasMoreElements())

  java.security.cert.Certificate c=ks.getCertificate((String)e.nextElement());

  六:JAVA程序修改密钥库口令

  String oldpass="123456";

  String newpass="654321";

  FileInputStream in=new FileInputStream(".keystore");

  KeyStore ks=KeyStore.getInstance("JKS");

  ks.load(in,oldpass.toCharArray());

  in.close();

  FileOutputStream output=new FileOutputStream(".keystore");

  ks.store(output,newpass.toCharArray());

  output.close();

  七:JAVA程序修改密钥库条目的口令及添加条目

  FileInputStream in=new FileInputStream(".keystore");

  KeyStore ks=KeyStore.getInstance("JKS");

  ks.load(in,storepass.toCharArray());

  Certificate [] cchain=ks.getCertificate(alias);获取别名对应条目的证书链

  PrivateKey pk=(PrivateKey)ks.getKey(alias,oldkeypass.toCharArray());获取别名对应条目的私钥

  ks.setKeyEntry(alias,pk,newkeypass.toCharArray(),cchain);向密钥库中添加条目

  第一个参数指定所添加条目的别名,假如使用已存在别名将覆盖已存在条目,使用新别名将增加一个新条目,第二个参数为条目的私钥,第三个为设置的 新口令,第四个为该私钥的公钥的证书链

  FileOutputStream output=new FileOutputStream("another");

  ks.store(output,storepass.toCharArray())将keystore对象内容写入新文件

  八:JAVA程序检验别名和删除条目

  FileInputStream in=new FileInputStream(".keystore");

  KeyStore ks=KeyStore.getInstance("JKS");

  ks.load(in,storepass.toCharArray());

  ks.containsAlias("sage");检验条目是否在密钥库中,存在返回true

  ks.deleteEntry("sage");删除别名对应的条目

  FileOutputStream output=new FileOutputStream(".keystore");

  ks.store(output,storepass.toCharArray())将keystore对象内容写入文件,条目删除成功

  九:JAVA程序签发数字证书

  (1)从密钥库中读取CA的证书

  FileInputStream in=new FileInputStream(".keystore");

  KeyStore ks=KeyStore.getInstance("JKS");

  ks.load(in,storepass.toCharArray());

  java.security.cert.Certificate c1=ks.getCertificate("caroot");

  (2)从密钥库中读取CA的私钥

  PrivateKey caprk=(PrivateKey)ks.getKey(alias,cakeypass.toCharArray());

  (3)从CA的证书中提取签发者的信息

  byte[] encod1=c1.getEncoded();  提取CA证书的编码

  X509CertImpl cimp1=new X509CertImpl(encod1); 用该编码创建X509CertImpl类型对象

  X509CertInfo cinfo1=(X509CertInfo)cimp1.get(X509CertImpl.NAME+"."+X509CertImpl.INFO);  获取X509CertInfo对象

  X500Name issuer=(X500Name)cinfo1.get(X509CertInfo.SUBJECT+"."+CertificateIssuerName.DN_NAME); 获取X509Name类型的签发者信息

  (4)获取待签发的证书

  CertificateFactory cf=CertificateFactory.getInstance("X.509");

  FileInputStream in2=new FileInputStream("user.csr");

  java.security.cert.Certificate c2=cf.generateCertificate(in);

  (5)从待签发的证书中提取证书信息

  byte [] encod2=c2.getEncoded();

  X509CertImpl cimp2=new X509CertImpl(encod2); 用该编码创建X509CertImpl类型对象

  X509CertInfo cinfo2=(X509CertInfo)cimp2.get(X509CertImpl.NAME+"."+X509CertImpl.INFO);  获取X509CertInfo对象

  (6)设置新证书有效期

  Date begindate=new Date(); 获取当前时间

  Date enddate=new Date(begindate.getTime()+3000*24*60*60*1000L); 有效期为3000天

  CertificateValidity cv=new CertificateValidity(begindate,enddate); 创建对象

  cinfo2.set(X509CertInfo.VALIDITY,cv); 设置有效期

  (7)设置新证书序列号

  int sn=(int)(begindate.getTime()/1000);  以当前时间为序列号

  CertificateSerialNumber csn=new CertificateSerialNumber(sn);

  cinfo2.set(X509CertInfo.SERIAL_NUMBER,csn);

  (8)设置新证书签发者

   cinfo2.set(X509CertInfo.ISSUER+"."+CertificateIssuerName.DN_NAME,issuer); 应用第三步的结果

  (9)设置新证书签名算法信息

  AlgorithmId algorithm=new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid);

   cinfo2.set(CertificateAlgorithmId.NAME+"."+CertificateAlgorithmId.ALGORITHM,algorithm);

  (10)创建证书并使用CA的私钥对其签名

  X509CertImpl newcert=new X509CertImpl(cinfo2);

  newcert.sign(caprk,"MD5WithRSA"); 使用CA私钥对其签名

  (11)将新证书写入密钥库

  ks.setCertificateEntry("lf_signed",newcert);

  FileOutputStream out=new FileOutputStream("newstore");

  ks.store(out,"newpass".toCharArray()); 这里是写入了新的密钥库,也可以使用第七条来增加条目

  十:数字证书的检验

  (1)验证证书的有效期

  (a)获取X509Certificate类型对象

  CertificateFactory cf=CertificateFactory.getInstance("X.509");

  FileInputStream in1=new FileInputStream("aa.crt");

  java.security.cert.Certificate c1=cf.generateCertificate(in1);

  X509Certificate t=(X509Certificate)c1;

  in2.close();

  (b)获取日期

  Date TimeNow=new Date();

  (c)检验有效性

  try{

  t.checkValidity(TimeNow);

  System.out.println("OK");

  }catch(CertificateExpiredException e){ //过期

  System.out.println("Expired");

  System.out.println(e.getMessage());

  }catch((CertificateNotYetValidException e){ //尚未生效

  System.out.println("Too early");

  System.out.println(e.getMessage());}

  (2)验证证书签名的有效性

  (a)获取CA证书

  CertificateFactory cf=CertificateFactory.getInstance("X.509");

  FileInputStream in2=new FileInputStream("caroot.crt");

  java.security.cert.Certificate cac=cf.generateCertificate(in2);

  in2.close();

  (c)获取CA的公钥

  PublicKey pbk=cac.getPublicKey();

  (b)获取待检验的证书(上步已经获取了,就是C1)

  (c)检验证书

  boolean pass=false;

  try{

  c1.verify(pbk);

  pass=true;

  }

DigitalCertificate|java安全通信、数字证书及数字证书应用实践

Java 安全通信、数字证书及数字证书应用实践

Abnerchai(柴政) 2004年6月

摘要:

在本文中,我用详细的语言和大量的图片及完整的程序源码向你展示了在 JAVA中如何实现通过消息摘要、消息验证码达到安全通信、以及用Java的工具生成数字证书,和用程序给数字证书签名、以及用签名后的数学证书签名 applet突破applet的访问权限的过程,给出了全部例子的详细代码。

通过本文中你可以学到以下知识:

•  程序间如何安全通信

•  什么是 及 如何生成消息摘要

•  什么是 及 如何生成消息验证码

•  如何使用 Java工具生成和维护数字证书库

•  如何用程序给数字证书验证签名

•  如何利用数字证书给 applet签名突破applet的访问权限

关键字:

消息摘要、消息验证码、指纹、加密、安全、 Java、数字签名、applet、数字证书

一、基础知识

计算机安全通信过程中,常使用消息摘要和消息验证码来 保证传输的数据未曾被第三方修改。

消息摘要是对原始数据按照一定算法进行计算得到的结果,它主要检测原始数据是否被修改过。消息摘要与 加密不同,加密是对原始数据进行变换,可以从变换后的数据中获得原始数据,而消息摘要是从原始数据中获得一部分信息,它比原始数据少得多,因此消息摘要可 以看作是原始数据的指纹。

例:下面一段程序计算一段字符串的消息摘要

package com.messagedigest;

import java.security.*;

public class DigestPass {

public static void main(String[] args) throws Exception{

String str="Hello,I sent to you 80 yuan.";

MessageDigest md = MessageDigest.getInstance("MD5");//常用的有MD5,SHA算法等

md.update(str.getBytes("UTF- 8"));//传入原始字串

byte[] re = md.digest();//计算消息摘要放入byte数组中

// 下面把消息摘要转换为字符串

String result = "";

for(int i=0;i<re.length;i++){

result += Integer.toHexString((0x000000ff&re[i])|0xffffff00).substring(6);

}

System.out.println(result);

}

}

当我 们有时需要对一个文件加密时,以上方式不再适用。

又例:下面一段程序计算从输入(出)流中计算消息摘要。

package com.messagedigest;

import java.io.*;

import java.security.*;

public class DigestInput {

public static void main(String[] args) throws Exception{

String fileName = "test.txt";

MessageDigest md = MessageDigest.getInstance("MD5");

FileInputStream fin = new FileInputStream(fileName);

DigestInputStream din = new DigestInputStream(fin,md);//构造输入流

//DigestOutputStream dout = new DigestOutputStream(fout,md);

//使用输入(出)流可以自己控制何时开始和关闭计算摘要

//也可以不控制,将全过程计算

//初始时是从开始即开始计算,如我们可以开始时关闭,然后从某一部分开始,如下:

//din.on(false);

int b;

while((b=din.read())!=-1){

//做一些对文件的处理

//if(b=='$') din.on(true); //当遇到文件中的符号$时才开始计算

}

byte[] re = md.digest();//获得消息摘要

//下面把消息摘要转换为字符串

String result = "";

for(int i=0;i<re.length;i++){

result += Integer.toHexString((0x000000ff&re[i])|0xffffff00).substring(6);

}

System.out.println(result);

}

}

当 A和B通信时,A将数据传给B时,同时也将数据的消息摘要传给B,B收到后可以用该消息摘要验证A传的消息是否正确。这时会产生问题,即若传递过程中别人 修改了数据时,同时也修改了消息摘要。B就无法确认数据是否正确。消息验证码可以解决这一问题。

使用消息验证码的前提是 A和B双方有一个共同的密钥,这样A可以将数据计算出来的消息摘要加密后发给B,以防止消息摘要被改。由于使用了共同的密钥,所以称为"验证码"。

例、下面的程序即可利用共同的密钥来计算消息摘要的验证码

package com.mac;

import java.io.*;

import java.security.*;

import javax.crypto.*;

import javax.crypto.spec.*;

public class MyMac {

public static void main(String[] args) throws Exception{

//这是一个消息摘要串

String str="TestString";

// 共同的密钥编码,这个可以通过其它算法计算出来

byte[] kb={11,105,-119,50,4,-105,16,38,-14,-111,21,-95,70,-15,76,-74,

67,-88,59,-71,55,-125,104,42};

//获取共同的密钥

SecretKeySpec k = new SecretKeySpec(kb,"HMACSHA1");

//获取Mac对象

Mac m = Mac.getInstance("HmacMD5");

m.init(k);

m.update(str.getBytes("UTF-8"));

byte[] re = m.doFinal();//生成消息码

//下面把消息码转换为字符串

String result = "";

for(int i=0;i<re.length;i++){

result += Integer.toHexString((0x000000ff&re[i])|0xffffff00).substring(6);

}

System.out.println(result);

}

}

使用 以上两种技术可以保证数据没有经过改变,但接收者还无法确定数据是否确实是某个人发来的。尽管消息码可以确定数据是某个有同样密钥的人发来的,但这要求双 方具有共享的密钥,若有一组用户共享,我们就无法确定数据的来源了。

数字签名可以解决这一问题。数字签名利用非对称加密技术,发送者使 用私钥加密数据产生的消息摘要(签名),接收者使用发送者的公钥解密消息摘要以验证签名是否是某个人的。由于私钥只有加密者才有,因此如果接收者用某个公 钥解密了某个消息摘要,就可以确定这段消息摘要必然是对应的私钥持有者发来的。

使用数字签名的前提是接收数据者能够确信验证签名时(用 发送者的私钥加密消息摘要)所用的公钥确实是某个人的 (因为有可能有人假告公钥)。数字证书可以解决这个问题。

数字证书含有两部分数 据:一部分是对应主体(单位或个人)的信息,另一部分是这个主体所对应的公钥。即数字证书保存了主体和它的公钥的一一对应关系。同样,数字证书也有可能被 假造,如何判定数字证书的内容的真实性呢?所以,有效的数字证书必须经过权威 CA的签名,即权威CA验证数字证书的内容的真实性,然后再在数字证书上使用自己的私钥签名(相当于在证书加章确认)。

这样,当用户收 到这样的数字证书后,会用相应的权威 CA的公钥验证该证书的签名(因为权威的CA的公钥在操作系统中己经安装)。根据非对称加密的原理,如果该证书不是权威CA签名的,将不能通过验证,即该 证书是不可靠的。

若通过验证,即可证明此证书含的信息(发信人的公钥和信息)是无误的。于是可以信任该证书,便可以通过该证书内含的公 钥来确认数据确实是发送者发来的。

于是,双方通信时, A把数据的消息摘要用自己的私钥加密(即签名),然后把自己的数字证书和数据及签名后的消息摘要一起发送给B,B处查看A的数字证书,如果A的数字证书是 经过权威CA验证可靠的,便信任A,便可使用A的数字证书中附带的A的公钥解密消息摘要(这一过程同时确认了发送数据的人又可以解密消息摘要),然后通过 解密后的消息摘要验证数据是否正确无误没被修改。

利用这一原理,我们可以突破 java的applet小程序在浏览器中的权限,由于默认的applet权限控制不允许它访问操作系统级的一切。于是我们可以用我们数字证书来给 applet签名,然后客户端收到该applet时,系统会自动查看给该applet签名的数字证书并提供给终端用户判定是否信认该数字证书,如果用户信 认,则该applet便有了访问系统的权限。

二、 Java中的数字证书的生成及维护方法

一、前言

Java中的keytool.exe可以用来创建数字证书,所有的数字证书是以一条一条(采用别名区别)的形式存入证书库的中,证书库中的一条证 书包含该条证书的私钥,公钥和对应的数字证书的信息。证书库中的一条证书可以导出数字证书文件,数字证书文件只包括主体信息和对应的公钥。

每 一个证书库是一个文件组成,它有访问密码,在首次创建时,它会自动生成证书库,并要求指定访问证书库的密码。

在创建证书的的时候,需要 填写证书的一些信息和证书对应的私钥密码。这些信息包括 CN=xx,OU=xx,O=xx,L=xx,ST=xx,C=xx,它们的意思是:

CN(Common Name名字与姓氏)

OU(Organization Unit组织单位名称)

O(Organization 组织名称)

L(Locality城市或区域名称)

ST(State州或省份名称)

C(Country 国家名称)

可以采用交互式让工具提示输入以上信息,也可以采用参数

-dname "CN=xx,OU=xx,O=xx,L=xx,ST=xx,C=xx"来自动创建。

二、示例

如下所示一句采用 交互式创建一个证书,指定证书库为 abnerCALib,创建别名为abnerCA的一条证书,它指定用RSA算法生成,

且指定密钥 长度为 1024,证书有效期为3650天:

C:\j2sdk1.4.1_01\mykeystore>keytool -genkey -alias abnerCA -keyalg RSA -keysize 1024 -keystore abnerCALib -validity 3650

如下图所示:

上图中最后一步,我们输入的是 CN,代表中国的缩写,也可以直接输入"中国"两个字。

三、证书的操作方法

•  证书的显示

如:

keytool –list –keystore abnerCALib

将显示 abnerCALib证书库的的所有证书列表:如下图示:

又如: keytool -list -alias abnerCA -keystore abnerCALib

将显示 abnerCALib证书库中别名为abnerCA的证书的信息。如下图所示:

又如: keytool -list -v -alias abnerCA -keystore abnerCALib

将显示证书的详细信息( -v参数)如下图所示:

•  将证书导出到证书文件

如: keytool -export -alias abnerCA -file abnerCA.cer -keystore abnerCALib

将把 证书库 abnerCALib中的别名为abnerCA的证书导出到abnerCA.cer证书文件中,

它包含证书主体的信息及证书的 公钥,不包括私钥,可以公开,如下图所示 :

上面导出的证书文件是以二进制编码文件,无法用文本编辑器正确显示,因此不利用公布证 书,可以加上 -rfc参数以一种可打印的编者编码输出。

如:

keytool -export -alias abnerCA -file abnerCA.cer -keystore abnerCALib -storepass 100200 –rfc

这个命令在命令行中指定了证书库的访问密码,同时指定以可查看编码的方式输出。

3、通过证书文件查看证书的信息

通 过命令 :keytool –printcert –file abnerCA.cer可以查看证书文件的信息。

也可以在 windows中双击产生的证书文件直接查看。

•  证书条目的删除

keytool的命令行参数-delete可以 删除密钥库中的条目,如:

keytool -delete -alias abnerCA -keystore abnerCALib

这条命令将 abnerCALib库中的abnerCA这一条证书删除了。

•  证书条目口令的修改

如:

keytool –keypasswd –alias abnerCA –keystore abnerCALib

可 以以交互的方式修改 abnerCALib证书库中的条目为abnerCA的证书。

Keytool –keypasswd –alias abnerCA –keypass 123456 –new 200100 –storepass 1002 00 –keystore abnerCALib

这一行命令以非交互式的方式修改库中别名为 abnerCA的证书的密码为新密码123456,行中的200100是指该条证书的原密码, 1002 00是指证书库的密码。

三、 数字证书的签发(签名)

我们在上面创建好了数字证书,但这些数字证书还没有经过权威 CA的证实(即签名)。一般情况下,我们需要将这些证书发送给权威的CA,并申请其签名以确认数字证书让客户信任。

下面我们将模仿自己 是一个权威的数字证书认证机构 CA,这个机构将采用自己的私钥来签发其它的证书。这个签发过程是这样的:我们自己是CA,我们自己有一个自签的数字证书存入数字证书库中。在数字证书库 中的这个我们的CA数字证书,它含有私钥,公钥和我们这个CA的主体信息。下面这一个指令可以创建一个CA的自签的数字证书:

keytool –genkey –dname "CN=美森系统软件有限公司,OU=美森系统软件有限公司,O=美森系统软件有限公司,L=成都市,ST=四川省,C=中国" –alias MissionCA –keyalg RSA –keysize 1024 –keystore abnerCALib –keypass 200100 –storepass 100200 –validity 3650

上面,我们在 abnerCALib这个数字证书库中创建了一个别名为:missionCA、有效期为3650天、算法为RSA且密钥长度为1024的数字证书,这条证 书的私钥密码为:200100,证书库的访问密码为:100200。这条别名为missionCA的证书代表我们自己的权威CA即:美森系统软件有限公司 这个权威CA。以后我们将用这个证书来签名其它的数字证书。

现在我要给自己申请一个数字证书,我可以这么做:先在数字证书库中创建一条 证书:

keytool –genkey –dname "CN=柴政,OU=美森系统软件有限公司,O=美森系统软件有限公司,L=成都市,ST=四川省,C=中国" –alias abnerCA –keyalg RSA –keysize 1024 –keystore abnerCALib –keypass 200100 –storepass 100200 –validity 3650

这样创建了一个别名为 abnerCA的数字证书,我们可以将它导出为cer文件(见前)。

接着,我们可以用上一步生成的 CA的自签证书来签名我这个数字证书了。

CA签名数字证书的过程需用以下程序来进行,这个程序是自解释的:

package com.security;

import java.io.*;

import java.security.*;

import java.security.cert.*;

import java.util.*;

import java.math.*;

import sun.security.x509.*;

/**

* <p>Description: 该程序根据签发者(CA)的证书信息(即CA的私钥)来对被签发者

* 的证书进行签名,过程即是使用CA的证书和被签证书来重构形成一个新的证书</p>

* @author abnerchai

* @version 1.0

*/

public class SignCert {

public static void main(String[] args) throws Exception{

char[] storepass = "100200".toCharArray();//存放CA证书和被签证书的证书库的访问密码

char[] cakeypass = "200100".toCharArray();//CA数字证书条目的访问密码

String alias = "missionCA";//CA证书在证书库中的别名,这个CA的证书用来签名其它的证书

String name = "abnerCALib";//存放CA证书和被签证书的证书库的名字

String newLib = "SignedLib";//新证书库的名字,如果需要将签名后的证书放入新库,这是新库的名字

char[] newLibPass = "100200".toCharArray();//设置新库的访问密码

String cerFileName = "abnerCA.cer";//被签证书的证书文件名

String aliasName = "abnerCA";//被签证书在证书库中的alias别名

char[] namePass = "200100".toCharArray();//被签证书的条目在证书库的私钥密码

int n =3; //被签证书的有效期,以年为单位,以当前时间开始计算

int sn = 200406001;//序列号可自己定义,这里定义的意义为2004年6月签发,是本年度CA签发的第多少个以001计算,要求唯一

String afteraliasName = "abnerCA_Signed"; //签名后新产生的被签过名的证书在库中的别名

char[] afterNewPass = "200100".toCharArray(); //签名后新产生的被签过名的证书在库的条目的私钥的密码

//装载证书库

FileInputStream in = new FileInputStream(name);

KeyStore ks = KeyStore.getInstance("JKS");//JKS为证书库的类型

ks.load(in,storepass);

//从证书库中读出签发者(CA)的证书

java.security.cert.Certificate cl = ks.getCertificate(alias);//读出一个CA证书,这里的l是字母l不是数据字1

PrivateKey privateKey = (PrivateKey)ks.getKey(alias,cakeypass);//根据别名和证书密码读出CA证书的私钥

in.close();

//从证书库中读出的签发者(CA)的证书中提取签发者的信息

byte[] encodl = cl.getEncoded();//提取证书的编码,这里是字母l不是数据字1

X509CertImpl cimpl = new X509CertImpl(encodl);//这里是字母l不是数据字1,根据证书的编码创建X509CertImpl类型的对象

// 根据上面的对象获得X509CertInfo类型的对象,该对象封装了证书的全部内容。

X509CertInfo cinfo_first =

(X509CertInfo)cimpl.get(X509CertImpl.NAME+"."+X509CertImpl.INFO);

//然后获得X500Name类型的签发者信息

X500Name issuer = (X500Name)

cinfo_first.get(X509CertInfo.SUBJECT+"."+CertificateIssuerName.DN_NAME);

//获取待签发的证书,即获取被签发者的证书

//可从密钥库中获取,也可从导出的证书文件中获取,这里给出两种方式 ///////////////////////////////////////////////////////////////////////////////

//方式一、采用从导出的cer文件中获取 start

///////////////////////////////////////////////////////////////////////////////

/*

CertificateFactory cf = CertificateFactory.getInstance("X.509");//X.509是使用最多的一种数字证书标准

FileInputStream in2 = new FileInputStream(cerFileName);//被签证书文件

java.security.cert.Certificate c2 = cf.generateCertificate(in2);//生成需要被签的证书

in2.close();

byte[] encod2 = c2.getEncoded();

X509CertImpl cimp2 = new X509CertImpl(encod2);

//获得被签证书的详细内容,然后根据这个证书生成新证书

X509CertInfo cinfo_second =

(X509CertInfo)cimp2.get(X509CertImpl.NAME+"."+X509CertImpl.INFO);

*/

///////////////////////////////////////////////////////////////////////////////

//end 方式一

///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////

//方式二、从证书库中读出被签的证书 start

///////////////////////////////////////////////////////////////////////////////

java.security.cert.Certificate c3 = ks.getCertificate(aliasName);//从证书库中读出被签证书,然后生成新的证书

byte[] encod3 = c3.getEncoded();

X509CertImpl cimp3 = new X509CertImpl(encod3);

X509CertInfo cinfo_second =

(X509CertInfo)cimp3.get(X509CertImpl.NAME+"."+X509CertImpl.INFO); ///////////////////////////////////////////////////////////////////////////////

//end方式二

/////////////////////////////////////////////////////////////////////////////// //设置新证书的有效期,使之为当前向后n年有效,新证书的

//截止日期不能超过CA证书的有效日期

Date beginDate = new Date();

Calendar cal = Calendar.getInstance();

cal.setTime(beginDate);

cal.add(cal.YEAR,n);

Date endDate = cal.getTime();

CertificateValidity cv = new CertificateValidity(beginDate,endDate);

cinfo_second.set(X509CertInfo.VALIDITY,cv);

//设置新证书的序列号

CertificateSerialNumber csn = new CertificateSerialNumber(sn);

cinfo_second.set(X509CertInfo.SERIAL_NUMBER,csn);

//设置新证书的签发者

cinfo_second.set(X509CertInfo.ISSUER+"."+CertificateIssuerName.DN_NAME,

issuer);

//新的签发者是CA的证书中读出来的

//设置新证书的算法,指定CA签名该证 书所使用的算法为md5WithRSA

AlgorithmId algorithm =

new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid);

cinfo_second.set(CertificateAlgorithmId.NAME+"."+

CertificateAlgorithmId.ALGORITHM,algorithm);

//创建新的签名后的 证书

X509CertImpl newcert = new X509CertImpl(cinfo_second);

// 签名,使用CA证书的私钥进行签名,签名使用的算法为MD5WithRSA

newcert.sign(privateKey,"MD5WithRSA");// 这样便得到了经过CA签名后的证书

//把新证书存入证书库

//把新生成的证书存入一个新的证书库,也可以存入原证书 库,

//存入新证书库,则新证书库中不仅包含原证书库中的所有条目,

//而且新增加了一个这次产生的条目。注意,这 时,新产生的签名后的证书只

//包括公钥和主体信息及签名信息,不包括私钥信息。这里给出两种方式。

///////////////////////////////////////////////////////////////////////////

//方式一:存入新密钥库

///////////////////////////////////////////////////////////////////////////

/*

ks.setCertificateEntry(afteraliasName,newcert);

FileOutputStream out = new FileOutputStream(newLib);

//存入新库 signedLib,并设置新库的库访问密码

ks.store(out,newLibPass);

out.close();

*/

///////////////////////////////////////////////////////////////////////////

//end 方式一

///////////////////////////////////////////////////////////////////////////

//也可以采用另外一种方式,存入原证书库中

//存入原库中,即在原证书库中增加一条证书,这个证书是原证书经过签 名后的证书

//这个新证书含有私钥和私钥密码

///////////////////////////////////////////////////////////////////////////

//方式二,存入原密钥库

///////////////////////////////////////////////////////////////////////////

//先在原库中读出被签证书的私钥

PrivateKey prk = (PrivateKey)ks.getKey(aliasName,namePass);

java.security.cert.Certificate[] cchain = {newcert};

//存入原来的库,第二个参数为原证书的私钥,第三个参数为新证书的私钥密码,第三个参数为 新证书

ks.setKeyEntry(afteraliasName,prk,afterNewPass,cchain); //用新密钥替代原来的没有签名的证书的密码

FileOutputStream out2 = new FileOutputStream(name);

ks.store(out2,storepass);//存入原来的库中,第二个参数 为该库的访问密码

///////////////////////////////////////////////////////////////////////////

//end 方式二

///////////////////////////////////////////////////////////////////////////

}

}

运行以上程序,即可运用 MissionCA证书来签发abnerCA证书,运行后在abnerCALib中增加一条别名为abnerCA_Signed的数字证书,我们将它导出 为cer文件(导出方法见前)。

至此,我们己经用 CA的证书以我们的数字证书签名了。在windows中,双击导出的abnerCA_Signend.cer文件,出现如下图所示:

上图中证书信息一栏显示"不能验证该证书",原因是因为,我们的这个数字证书的签发 者 missionCA证书没有安装到系统中。我们可以将证书库中别名为missionCA的自签数字证书导出为cer文件,然后安装到系统中。再次查双击看 此证书,如下图所示:

到此,我们己经获得了一个由我们自己的 CA签名颁发的个人数字证书。并且将我们自己的CA证书安装到系统中成为系统信任的根证书。于是,以后只要是由我们的这个CA证书签名颁发的数字证书都会 受到系统的信任。

四、利用数字证书给 applet签名

现在假设我们公司给 xx公司做一个项目,这个项目中需要用到applet,且这些applet需要特权以实现一些特殊的功能(如读出客户端用户系统中C:\winNT \system.ini文件中的内容并显示)。那么我们可以颁发一个数字证书,并给这个数字证书签名,然后用签名后的这个数字证书来签名我们的 applet,使客户信任。具体过程如下:

一、生成一个用于此项目签名 applet 的数字证书,别名定为: mission_water

生成一个用于此项目签名的数字证书如下:

keytool –genkey –dname "CN=美森软件-水公司项目,OU=美森系统软件有限公司,O=美森系统软件有限公司,L=成都市,ST=四川省,C=中国" –alias Mission_Water –keyalg RSA –keysize 1024 –keystore abnerCALib –keypass 200100 –storepass 100200 –validity 3650

二、用我们的 CA(missinCA) 来签发这个数字证书

然后,运行我们在前面第三节中给定的程序,注意:运行此程序前,请修改以下参数:

String cerFileName = "Mission_Water.cer";

String aliasName = "Mission_Water";

String afteraliasName = "Mission_Water_Signed";

然后运行,程序会在 abnerCALib证书库中产生一个别名为:Mission_Water_Signed的数字证书,这个证书是经过我们的CA(MissionCA)签 发的。

下面,我们用以下指令导出这个证书:

keytool -export -alias Mission_Water_Signed -file Mission_Water_Signed.cer -keystore abnerCALib -rfc

会生成一个 Mission_Water_Signed.cer 文件。

三、用签发后的数字证书来签名 我们的 applet

我们现在来做一个简单的 applet,它的代码如下:

package com.applet;

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

import javax.swing.*;

import java.io.*;

public class ShowFileApplet extends JApplet {

private boolean isStandalone = false;

private String content = "文件的内容是:"; //自定义的提示信息

private String fileName = "C:\\WINNT\\system.ini";//读出这个文件的内容

private TextArea ta = new TextArea(10,80);//自定义的输出框

public String getParameter(String key, String def) {

return isStandalone ? System.getProperty(key, def) :

(getParameter(key) != null ? getParameter(key) : def);

}

public ShowFileApplet() {

}

public void init() {

try {

jbInit();

myInit();//自己定义的方法

}

catch(Exception e) {

e.printStackTrace();

}

}

private void jbInit() throws Exception {

this.setSize(new Dimension(400,300));

}

/**

* 自定义的初始化方法,读入系统中的一个文件的内容并保存起来,然后,增加一个

* 可视化的输出框

*/

private void myInit(){

String s;

BufferedReader in;

try {

in = new BufferedReader(new FileReader(fileName));

while ( (s = in.readLine()) != null) {

content +=s + "\n";

}

}catch (IOException ex) {

ex.printStackTrace();

}

System.out.println(content);

ta.setText(content);

getContentPane().add(ta);

}

/*

*重载的方法,输出内容

**/

public void paint(Graphics g){

ta.setText(content);

}

public String getAppletInfo() {

return "Applet Information";

}

public String[][] getParameterInfo() {

return null;

}

//static initializer for setting look & feel

static {

try {

}

catch(Exception e) {

}

}

}

好了,这个 applet写好了,下面我们来把这个applet编译打包成jar文件。

编译此 applet文件,会在当前目录(当前目录为classes目录)下生成一个com\applet的目录结构,在applet目录下有一个 ShowFileApplet.class,进入当前目录,执行:

jar cvf myapplet.jar com/applet/*.*

于是在当前目录下产生一个 myapplet.jar文件。

然后再在当前目录(当前目 录为 classes目录)下新建一个applet目录,专门存放applet的jar文件,把前面生成的数字证书库abnerCALib这个文件也copy到 applet目录下面来,同时把刚才生成的myapplet.jar文件也移到applet目录下面来。然后进入该目录执行:

jarsigner -keystore abnerCALib myapplet.jar Mission_Water_Signed

Enter Passphrase for keystore: 100200

Enter key password for Mission_Water_Signed: 200100

即用 Mission_Water_Signed这个我们的CA签发的数字证书给这个applet签名了。

四、运行我们的 applet

我们来写一个 html文件来运行这个签名后的applet,内容如下:

<!-- ShowFileApplet.html -->

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=GB2312">

<title>HTMLTestPage</title>

</head><body>

applet将会显示,如果你的浏览器支持Java<br>

<applet

archive = "./applet/myapplet.jar"

code = "com.applet.ShowFileApplet.class"

name = "TestApplet"

width = "400"

height = "300"

hspace = "0"

vspace = "0"

align = "middle"

>

</applet>

</body>

</html>

这个 HTML文件可以运行applet,但如果浏览器不支持Java,即没有安装JRE,它不会提示用户去下载安装。我们可以用Java自带的 htmlconverter工具转换一下这个HTML文件,转换后的文件可以在支持JAVA2的浏览器中(不管该浏览器是否设置了使用java2运行 applet,它都会在Java2环境中运行applet,如果浏览器不支持Java2,则会自动下载所需的文件。

在 DOS方式下运行htmlconverter,弹出如下图所示画框,按图中所示选择刚才的那个HTML文件,如下图所示:

点"转换",将会在当前目录下生成一个 HTML文件,并把原来的HTML文件备份了。

生成后的 HTML文件内容如下所示:

<!-- ShowFileApplet.html -->

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=GB2312">

<title>HTMLTestPage</title>

</head>

<body>

applet将会显示,如果你的浏览器支持 Java<br>

<OBJECT

classid = "clsid:CAFEEFAC-0014-0001-0001-ABCDEFFEDCBA"

codebase = "http://java.sun.com/products/plugin/autodl/jinstall-1_4_1_01-windows-i586.cab#Version=1,4,1,1"

WIDTH = "400" HEIGHT = "300" NAME = "TestApplet" ALIGN = "middle" VSPACE = "0" HSPACE = "0" >

<PARAM NAME = CODE VALUE = "com.applet.ShowFileApplet.class" >

<PARAM NAME = ARCHIVE VALUE = "./applet/myapplet.jar" >

<PARAM NAME = NAME VALUE = "TestApplet" >

<PARAM NAME = "type" VALUE = "application/x-java-applet;jpi-version=1.4.1_01">

<PARAM NAME = "scriptable" VALUE = "false">

<COMMENT>

<EMBED

type = "application/x-java-applet;jpi-version=1.4.1_01"

CODE = "com.applet.ShowFileApplet.class"

ARCHIVE = "./applet/myapplet.jar"

NAME = "TestApplet"

WIDTH = "400"

HEIGHT = "300"

ALIGN = "middle"

VSPACE = "0"

HSPACE = "0"

scriptable = false

pluginspage = "http://java.sun.com/products/plugin/index.html#download">

<NOEMBED>

</NOEMBED>

</EMBED>

</COMMENT>

</OBJECT>

</body>

</html>

双击打开运行这个文件或把这个文件及 applet目录发布到WEB Server中去,可以访问运行这个applet。运行时,弹出如下图所示对话框:

如果此时你点"是",则在这次会话过程中,此 applet具有访问本地文件系统的权限,但下次运行时还要提示此信息。如果你点"总是有效"则以后每次访问此类含有由 Mission_Water_Signed数字证书签发的applet页面,都不会再弹出此选择框。因为:你选择了总是有效,这样,Java会在Java Plug-in中记录这个信任的数字证书,除非你把Java Plug-in中记录的这个信任证书删除。在win2k中,可以在"控制面版"->Java Plug-in中看到。如下图所示:

点选择"总是有效"后,该程序运行的结果如下图所示:

五、作者简介:

abnerchai( 柴政 ), 24岁,西南交通大学计算机与通信工程学院~计算机应用技术硕士研究生、高级程序员。熟悉VC++/JAVA编程,主要研究方向为:网络安全,j2EE /中间件技术,工作流技术(wfmc)。个人联系方式为:josserchai@yahoo.com ;目前在成都美森系统软件有限公司兼职从事基于IBM WAS/WSAD平台的J2EE/EJB/JCE/JMS/JDBC/Servlets/JSP/JavaScript/开发。

DigitalCertificate|浅析数字证书

浅析数字 证书

  hyddd原创,转载请说明出 处:>

  最近看会Session hijack的东西,劫持现在已经实现,yahoo等一些没有用Https协议的邮箱被成功地劫持了(迟下发文章),由于对Https不熟悉,所以看了一 下为什么Https的会话不能劫持。

  本文主要介绍的SSL中的涉及到的"数字证书"这个东东。

一.什么是数字证书?

  数字证书是一种权威性的电子文档。它提供了一种在Internet上验证您身份的方式,其作用类似于司机的驾驶执照或日常生活中的身份证。它是 由一个由权威机构----CA证书授权(Certificate Authority)中心发行的,人们可以在互联网交往中用它来识别对方的身份。当然在数字证书认证的过程中,证书认证中心(CA)作为权威的、公正的、 可信赖的第三方,其作用是至关重要的。

  Ok,知道什么是数字证书后,先看看它长的什么样吧:>,文件缩略图如下:

  

  双击后打开如下:

  

 

二.CA认证机构/CA认证中心

  1.CA认证中心是什么?

  CA认证中心是负责签发,管理,认证数字证书的机构,是基于国际互联网平台建立的一个公正,权威,可信赖的第三方组织机构。

  2.世界上的CA认证中心不止一间,那他们之间的关系是什么(CA认证中心之间的关系)?

  嗯,回答这个问题之前可以先看看下图:

  

  从图中可以看到,CA认证中心之间是一个树状结构,根CA认证中心可以授权多个二级的CA认证中心,同理二级CA认证中心也可以授权多个3级的 CA认证中心...如果你是数字证书申请人(比如说:交通银行),你可以向根CA认证中心,或者二级,三级的CA认证中心申请数字证书,这是没有限制的, 当你成功申请后,你就称为了数字证书所有人。值得注意的是,根CA认证中心是有多个的,也就是说会有多棵这样的结构树。FireFox里面默认记录了一些 根CA认证机构的信息,如图:

  

  看到这里,肯定有人会问,如果有现在新的根CA认证机构成立,FireFox肯定是没有这个CA认证中心的信息的(这些信息是用来验证子CA认 证机构的,很重要,后面来会讲到),那怎么办呢?嗯~~确实,如果今天2009-1-8日突然在哪里成立一个新的CA认证中心,我FireFox里面肯定 没有他的信息的!但解决办法还是有的,看上图,可以找到一个"Import"按钮,当我们遇到这样的倒霉事时,只有自己去下载并导入根CA认证中心信息了 (其实这样做是不太安全的!),或者期望FireFox的升级会升级这些信息,但这个我是不确定的。

  3.为什么CA认证中心是权威的?

  其实搞清楚这个问题后,你也会真正了解"CA认证中心是如何授权子CA认证中心的?","为什么伪造的数字证书是无效的","为什么数字证书是 一种权威性的电子文档"等等一系列的问题。并且SSL可以说是建立在CA认证中心的权威,公正,可信赖的基础上的,如果CA认证中心的信息可以被伪造的, 那么SSL的一切就完了......

  首先,我们先来看看,在FireFox里记录的CA认证中心的信息到底是什么东西??见上图,单击某项,Export导出....你会看到导出 的东西很面熟,原来就是数字证书!!

  实际上每个CA认证中心/数字证书所有人,他们都有一个数字证书,和属于自己的RSA公钥和密钥,这些是他们的父CA认证中心给他们颁发的,这 里先大概解释一下RSA,RSA是一种非对称加密的算法,它的公钥和密钥是配对的,如果用公钥加密,用私钥解密就可以得到明文;如果用私钥加密,用公钥解 密也可以得到原来的明文,这由RSA特性决定,他效果可以用下图概括:

  

  对于私钥:CA认证中心/数字证书所有人自己保存,不公开。

  对于公钥:CA认证中心/数字证书所有人会把公钥存在他的CA认证中心的数字证书内。

  (1).首先,CA认证中心/数字证书所有人,它在网络上的表现形式只能是一张数字证书!所以我们可以把某张数字证书等价于某个CA认证中心 /数字证书所有人。这样的话,验证数字证书的合法性就可以确定CA认证中心/数字证书所有人是否是合法的!!!

  (2).数字证书使用数字签名作验证!这里简单说明一下数字签名的过程:你从Firefox/IE导出的数字证书包含3个部分:证书内容 (F),加密算法(A),F加密密文(F') (数字证书结构会在第三部分详细介绍),在这里,A不是一个算法,而是两个,所以密文F'是F两次加密后的结果。

  首先,F会被散列算法SHA1计算出hash值h1(称为128bit的摘要),然后h1会被发布这个数字签名的CA认证机构的用私钥进行 RSA加密,注意:是发布这个数字签名的CA认证机 构,如果现在被加密的数字证书是属于二级CA认证机构的,那么用来加密这个证书的私钥是根CA认证机构的私钥!!RAS加密完后,就形成密文F'。

  当你要验证这个数字证书可信/合法性时,你需要找到 你的上一层CA认证中心的数字证书,并且从中获取公钥,把数据证书中的密文F'进行RSA解密,如果得出的值h2和h1比较(h1可以立即用数据证书中的F现场算出来),如果相等,则认为证书是可信的,合法的!由于你是不可能知道上一层CA认证中心的私钥,所以你无法伪造一个可以用上一层CA认证中心公钥解密的数字证书!!

  详细流程图如下:

  

   由于一个数字证书基于上层的数字证书作验证,那上层的数字证书又是否合法呢??这就会出现一直递归上去的现象,事实也是这样的,验证一个证书 是否合法,需要验证到他的最顶层的根证书是否合法!从其他的文章弄来的这幅图很好地表达了这个思想:

   

  这里肯定又有人会问,那么最顶层的CA认证中心如何证明它的合法性呢?.......呵~这就是为什么FireFox要预先把一些最顶层(这里 的"最顶层"和"根"是同一个概念)的CA认证中心的证书加入到权威信任列表中了,因为,最顶层CA认证中心没有办法证明,所以,最顶层的CA认证中心是 总是受信任的!!而事实上,最顶层的CA认证中心在是世界上也是为数不多的。这里大家应该了解为什么我刚才说自己导入根CA证书是不太安全的,因为你无法 验证。

三.数字证书的组成

  可以先看看我从Firefox的证书截图:

  

  1.Certificate(证书):

   (1).Common Name(证书所有人姓名,简称CN,其实就是证书的名字,如第一幅图看到的:ABA.ECOMRoot....)

   (2).Version(版本,现在一般是V3了)

   (3).Issuer(发证机关)

   (4).Validity(有效日期)

   (5).Subject(证书信息,你会发现它和Issuer里面的内容是一样的)

   (6).Subject's Public Key Info(证书所有人公钥,刚才所说的公钥就是这个!)

   (7).Extension(扩展信息)

   (8).Certificate Signature Algorithm(公钥加密算法)、

    以上这几项就是上面所说的证书内容(F)。 

  2.Certificate Signature Algorithm:

    这是描述证书的加密算法,就是上所说的加密算法(A),看它的Fireld Value,一般会写:PKCS #1 SHA-1 With RSA Encryption

  3.Certificate Signature Value:

   这记录的是证书被加密后的结果,相当于上面说讲的F'。

四.数字证书的验证

  要回答数字证书是如何验证的,首先要知道数字证书是要验证些什么东西:>,数字证书的验证,上面已经讲了一些,这做一个总结:

  1.可信性验证/合法性验证:这个刚才已经说的很明白了吧:>

  2.完整性验证:在验证可信性的过程中,h1和h2的比较,其实已经顺便验证其完整性了。

  3.有效性验证:比如验证它的Vilidity值,看是否过期...

 

  先写这么多,其他以后补充!并且可能有些地方写得会比较乱,这个我稍后会改正:>~欢迎拍砖!

 

五.参考资料:

1.http://baike.baidu.com/view/204415.htm

2.http://finance.sina.com.cn/money/roll/20080401/00404692291.shtml

3.http://blog.csdn.net/sfdev/archive/2008/03/12/2174305.aspx

4.http://man.chinaunix.net/develop/rfc/RFC2313.txt

5.http://www.zhlmmc.com/diary/14554

Friday, April 30, 2010

WebService|Using implicit SOAP headers with JAX-WS web services

Using implicit SOAP headers with JAX-WS web services

StrikeIron offers two authentication methods for its for-pay web services, a "SOAP Header" authentication method and a "Non-SOAP Header" one (you can see examples of both in the WSDL section of their U.S. Census Information web service). The non-SOAP header validation method works normally with JAX-WS WSDL-to-Java tools (such as Metro's wsimport and CXF's wsdl2java) because the username and password information is provided as SOAP body request elements and hence parameters will be provided for them in the JAX-WS generated SEI's methods.

However, the SOAP header authentication method relies on implicit SOAP headers. These refer to SOAP headers for requests and responses that are defined in the WSDL binding section instead of the portType section. This is frequently done when the nature of the SOAP header information is metadata only indirectly related to the request and response; in such cases it would be desirable to keep this information separate from the business data referenced in the portType operation. However, implicit headers create a slight problem OOTB with JAX-WS tools, because per the JSR-224 specification WSDL-to-Java code generators only take parameters declared within the portType section into account when generating the SEI method signatures. As a result, necessary SOAP header parameters for making the SOAP request would not be available.

To illustrate this, let's choose one of the Census Information service's operations, say GetAllProfiles_ForZip. Its portType operation refers to two wsdl:messages, one each for request and response:

<wsdl:operation name="GetAllProfiles_ForZip">
<documentation xmlns="http://schemas.xmlsoap.org/wsdl/">
Returns all census information by zip</documentation>
<wsdl:input message="si:GetAllProfiles_ForZipSoapIn" />

<wsdl:output message="si:GetAllProfiles_ForZipSoapOut" />
</wsdl:operation>

<wsdl:message name="GetAllProfiles_ForZipSoapIn">
<wsdl:part name="parameters" element="si:GetAllProfiles_ForZip" />
</wsdl:message>
<wsdl:message name="GetAllProfiles_ForZipSoapOut">
<wsdl:part name="parameters" element="si:GetAllProfiles_ForZipResponse" />
</wsdl:message>

The elements in the request and response messages contain just the business data elements directly related to the operation. It is only within the binding section where the metadata SOAP header elements are defined:

<wsdl:operation name="GetAllProfiles_ForZip">
<soap:operation soapAction="http://www.strikeiron.com/GetAllProfiles_ForZip"
style="document"/>
<wsdl:input>
<soap:body use="literal"/>
...validation checks omitted...
<soap:header message="si:LicenseInfoMessage" part="LicenseInfo"
use="literal"/>

</wsdl:input>
<wsdl:output>
<soap:body use="literal" />
<soap:header message="si:GetAllProfiles_ForZipResponseInfo"
part="ResponseInfo" use="literal"/>
<soap:header message="si:SubscriptionInfoMessage" part="SubscriptionInfo" use="literal"/>

</wsdl:output>
</wsdl:operation>

Since these binding-defined SOAP header declarations are bypassed during wsimport/wsdl2java code generation, the SEI's generated do not supply parameters to allow the SOAP client to provide the authentication information on requests or receive other metadata information on the response:

public com.strikeiron.CensusProfile getAllProfilesForZip(
@WebParam(name = "zip", targetNamespace = "http://www.strikeiron.com")
java.lang.String zip
);

Possible solutions to this issue:

  • Use special wsimport/wsdl2java option settings to bring in implicit headers. Both CXF's wsdl2java and Metro's wsimport tools offer special flags for bringing in implicit SOAP headers when generating the Java artifacts. This is the easiest and probably most reliable solution.

    For Metro's wsimport, use -XadditionalHeaders at the command line or xadditionalHeaders="true" for the ant task or xAdditionalHeaders for Metro's jaxws-maven-plugin.

    For CXF's wsdl2java (command-line or Ant), use the -exsh true setting shown on the wsdl2java Wiki page or extendedSoapHeaders for the Maven cxf-codegen-plugin.

    Using this extension changes the operation signature to the following:

    public com.strikeiron.CensusProfile getAllProfilesForZip(
    @WebParam(name = "zip", targetNamespace = "http://www.strikeiron.com")
    java.lang.String zip,
    @WebParam(name = "LicenseInfo", targetNamespace = "http://ws.strikeiron.com", header = true)
    com.strikeiron.ws.LicenseInfo licenseInfo,
    @WebParam(mode = WebParam.Mode.OUT, name = "ResponseInfo", targetNamespace =
    "http://www.strikeiron.com", header = true)
    javax.xml.ws.Holder responseInfo,
    @WebParam(mode = WebParam.Mode.OUT, name = "SubscriptionInfo", targetNamespace =
    "http://ws.strikeiron.com", header = true)
    javax.xml.ws.Holder subscriptionInfo

    );
  • Modify the WSDL prior to calling the WSDL-to-Java tool, or subsequently alter the generated classes to make the SOAP Headers explicit. This forum topic has an example of the former and blog entry of the latter. This seems tricky and cumbersome to do, however, and unless the flag options above are not working properly for a certain WSDL I wouldn't see any benefit of this over the first option.

  • Create a JAX-WS Handler and use SAAJ to add the SOAP Headers. SAAJ is a DOM-like API used for creation and manipulation of SOAP messages. As shown in Ivasena's blog entry, a class implementing the SOAPHandler interface can be used to modify the outgoing SOAP request by adding the SOAP header information. This can be a nicely viable option if you do not wish to encumber each SEI method call with authentication information, and by placing this logic in a handler it can be shared across multiple web service calls that need the same headers added. See my JAX-WS handler tutorial for more information, and also the RPC/encoded article for examples of working with SAAJ. CXF provides interceptors as an additional option for adding SOAP headers.

  • (Metro only) Use the WSBindingProvider class to add the SOAP headers. As shown in the JAX-WS user's guide, Metro provides a WSBindingProvider that is implemented by proxy or dispatch objects. Methods on this interface allow for convenient adding of SOAP headers.