使用WS-Security框架对信息进行加密与身份认证

使用WS-Security框架对信息进行加密与身份认证
[1]
处理流程如下:
1、 客户端(WSGetJlogin)发出调用Web服务请求;
2、 客户端Handler(WSClientRequestHandler)截获请求的SOAP消息;
3、 此Handler对截获的SOAP消息进行数字签名(使用client.keystore中的私钥进行数字签名);
    PrivateKey key = (PrivateKey)keyStore.getKey(alias, keypass.toCharArray());
    调用wSSecurity.sign(doc,    sk, ki);//签名。
4、 此Handler对签名后的SOAP消息进行加密(使用client.truststore中的公钥进行RSA算法加密);
    PublicKey pubk = cert.getPublicKey();
    wSSecurity.encrypt(...)
5、 被加密的SOAP消息通过互联网传送到目标Web服务端口;
6、 服务器端Handler(WSServerRequestHandler)截获从客户端发过来的加密后的SOAP消息;
7、 此Handler对加密的SOAP消息进行解密(使用server.keystore中的私钥进行解密);
    PrivateKey prvk2 = (PrivateKey)keyStore.getKey(alias, keypass.toCharArray());
    wSSecurity.decrypt(doc, prvk2, null);
8、 此Handler对SOAP消息进行身份验证(使用server.truststore包含了所信任的身份信息进行身份验证),如果验证不通过,将抛出异常;
    用verifier对象TrustVerifier verifier = new X509TrustVerifier(keyStore);
    调用wSSecurity.verify(doc, verifier, null,null);
9、 此Handler删除被解密后的SOAP消息中与WS-Security相关的元素;
10、 解密后正确的原始SOAP消息被发送到目标Web服务端(如WSjLogin);
11、 目标Web服务对Web服务请求进行处理,然后返回响应的SOAP消息;
12、 服务器端Handler(WSServerResponseHandler)截获响应的SOAP消息;
13、 此Handler对截获的SOAP消息进行数字签名(使用server.keystore作为签名依据);
14、 此Handler对签名后的SOAP消息进行加密(使用server.truststore的公钥进行RSA算法加密);
15、 被加密的SOAP消息通过互联网传送到目客户端;
16、 客户端Handler(WSClientResponseHandler)截获加密的SOAP消息;
17、 此Handler对加密的SOAP消息进行解密(使用clilent.truststore中的私钥);
18、 此Handler对SOAP消息进行身份验证(client.truststore包含了所信任的身份信息),如果验证不
通过,将抛出异常;
19、 此Handler删除被解密后的SOAP消息中与WS-Security相关的元素;
20、 被解密后的SOAP消息发送到目标客户端,客户端输出调用结果。
从上面可以看出,在一个SOAP调用回合中,要对SOAP消息进行四次处理。基本上都是"签名-'加密'-解密'-验证"的过程。
从而确保了数据来源的正确性(只有拥有私钥/公钥的人,才能打开用公钥/私钥加密的文件,从而确保来源的正确性.),以及数据传输的秘密性(加密传递).
3.说明:
进行签名/加密/解密/身份验证:
1)
都要先加载keyStore实例,再进行签名/加密/解密/身份验证:
FileInputStream fileInputStream = new FileInputStream(keystore);
java.security.KeyStore keyStore = java.security.KeyStore.getInstance(storetype);
keyStore.load(fileInputStream, storepass.toCharArray());
2)
在服务端,客户端在进行'签名,加密,解密,身份验证'时,都是:
1.先根据public void invoke(MessageContext messageContext) throws AxisFault {..
获取soapmessage,且转换成doc
SOAPMessage soapMessage =    messageContext.getCurrentMessage();
Document doc = MessageConverter.convertSoapMessageToDocument(soapMessage);
2.签名,加密/解密,身份验证
3.doc-->soapmessage:
soapMessage = MessageConverter.convertDocumentToSOAPMessage(doc);
messageContext.setMessage(soapMessage);
3)
公钥-私钥加密,即是非对称加密.公钥是给大家用于加密的.私钥,是给自己的,要小心保存,用于解密的.确保接受者的身份是正确的.同时,也是数据的正确性(加密传递,别人无法修改)

[2]
详细过程:
(1)
使用ISNetworks安全提供者,ISNetworks实现了RSA加密、解密算法。
当然,你也可以使用其它的安全提供者,并且可以使用不同的加密算法。
ISNetworks相关包ISNetworksProvider.jar。拷贝到:项目根目录\WEB-INF\lib
(2)
Trust Services Integration Kit提供了一个WS-Security实现。
须用到的jar包是ws-security.jar和tsik.jar。
ws-security.jar中包含一个WSSecurity类,我们使用它来对XML进行数字签名和验证,加密与解密。同样
拷贝到:项目根目录\WEB-INF\lib
(3)
创建相关密匙库和信任库(gen-cer-store.bat)。
将以下内容放于bat中,点击即可产生所有的库.如下:
set SERVER_DN="CN=JasonServer, OU=jasonS, O=jasonS, L=shenzhen, S=guangdong, C=CN"
set CLIENT_DN="CN=JasonClient, OU=jasonC, O=jasonC, L=shenzhen, S=guangdong, C=CN"
set KS_PASS=-storepass access
set KEYINFO=-keyalg RSA
echo 生成server.keystore。
keytool -genkey -dname %SERVER_DN% -alias jserver  %KS_PASS%  %KEYINFO% -keystore
server.keystore -keypass access -keysize 1024 -validity 3650
echo 从server.keystore导出数字证书。
keytool -export -file jason_axis.cer -alias jserver -keystore server.keystore %KS_PASS%
echo 将服务器的数字证书导入到客户端信任的truststore中
keytool -import -file jason_axis.cer -alias serverkey -keystore client.truststore %KS_PASS% 
-noprompt
echo 生成client.keystore。
keytool -genkey -dname %CLIENT_DN% -alias jclient  %KS_PASS%  %KEYINFO% -keystore
client.keystore -keypass access -keysize 1024 -validity 3650
echo 从client.keystore导出数字证书。
keytool -export -file jason_axis.cer -alias jclient -keystore client.keystore %KS_PASS%
echo 将客户端的数字证书导出到服务器信任的truststore中。
keytool -import -file jason_axis.cer -alias clientkey -keystore server.truststore %KS_PASS% 
-noprompt
成功创建后,会有产生以下四个文件,其中:
    * client.keystore:客户端自身的身份信息;
    * client.truststore:客户端所信任的身份信息,在此例中也就是包含了服务器的身份信息;
    * server.keystore:服务器自身的身份信息;
    * server.truststore:服务器所信任的身份信息(即客户端身份信息)。
(4)
框架结构
    WSHelper.java //核心类,对SOAP消息签名、加密、解密、身份验证
    MessageConverter.java  //帮助类,Document、SOAP消息互相转换
    WSClientHandler.java  //基类,包含了一些公用方法
    WSClientRequestHandler.java //继承于WSClientHandler.java,调用WSHelper.java对客户端发出
的XML文档进行加密
    WSClientResponseHandler.java //继承于WSClientHandler.java,调用WSHelper.java对服务器端返
回的XML文档进行解密
    WSServerHandler.java //基类,包含了一些公用方法(初始化,从配置文件server-config.wsdd中读
取属性)
    WSServerRequestHandler.java //继承于WSServerHandler.java,调用WSHelper.java对客户端发出
的加密后的XML文档进行解密
    WSServerResponseHandler.java//继承于WSServerHandler.java,调用WSHelper.java对服务器端返
回的XML文档进行加密
具体代码如下:
package com.laoer.bbscs.webservice;

public class WSHelper {
   static String PROVIDER= "ISNetworks"; //JSSE安全提供者。
//  添加JSSE安全提供者,你也可以使用其它安全提供者。只要支持DESede算法。这是程序里动态加载还可以在JDK中静态加载
   static
  {
    java.security.Security.addProvider( new com.isnetworks.provider.jce.ISNetworksProvider());
  }
   /**
    *对XML文档进行数字签名。
    */
   public static void sign(Document doc, String keystore, String storetype,
      String storepass, String alias, String keypass) throws Exception {
    FileInputStream fileInputStream = new FileInputStream(keystore);
    java.security.KeyStore keyStore = java.security.KeyStore.getInstance(storetype);
    keyStore.load(fileInputStream, storepass.toCharArray());
    PrivateKey key = (PrivateKey)keyStore.getKey(alias, keypass.toCharArray());
     //从密钥库中直接读取证书,实例化 X.509 证书
    X509Certificate cert = (X509Certificate)keyStore.getCertificate(alias);
    SigningKey sk = SigningKeyFactory.makeSigningKey(key);
    KeyInfo ki = new KeyInfo();
    ki.setCertificate(cert);
    WSSecurity wSSecurity = new WSSecurity(); //ws-security.jar中包含的WSSecurity类
    wSSecurity.sign(doc,    sk, ki); //签名。


  }
   /**
    *对XML文档进行身份验证。
    */
   /*
  对SOAP消息进行验证就是使用keystore的信息生成TrustVerifier对象,然后调用WSSecurity的verify方
  法进行验证。
  */
   public static boolean verify(Document doc, String keystore, String storetype,
      String storepass) throws Exception {
    FileInputStream fileInputStream = new FileInputStream(keystore);
    java.security.KeyStore keyStore = java.security.KeyStore.getInstance(storetype);
    keyStore.load(fileInputStream, storepass.toCharArray());
    TrustVerifier verifier = new X509TrustVerifier(keyStore);
    WSSecurity wSSecurity = new WSSecurity();
    MessageValidity[] resa = wSSecurity.verify(doc, verifier, null, null);
     if (resa.length > 0)
       return resa[0].isValid();
     return false;
  }
   /**
    *对XML文档进行加密。必须有JSSE提供者才能加密。
    */
   public static void encrypt(Document doc, String keystore, String storetype,
      String storepass, String alias) throws Exception {
     try
    {
      FileInputStream fileInputStream = new FileInputStream(keystore);
      java.security.KeyStore keyStore = java.security.KeyStore.getInstance(storetype);
      keyStore.load(fileInputStream, storepass.toCharArray());
      X509Certificate cert = (X509Certificate)keyStore.getCertificate(alias);
      PublicKey pubk = cert.getPublicKey();
      KeyGenerator keyGenerator = KeyGenerator.getInstance( "DESede",PROVIDER);
      keyGenerator.init(168, new SecureRandom());
      SecretKey key = keyGenerator.generateKey();
      KeyInfo ki = new KeyInfo();
      ki.setCertificate(cert);
      WSSecurity wSSecurity = new WSSecurity();
       //加密。
      wSSecurity.encrypt(doc, key, AlgorithmType.TRIPLEDES, pubk, AlgorithmType.RSA1_5, ki);
    }
     catch(Exception e)
    {
      e.printStackTrace();
    }
  }
   /**
    *对文档进行解密。
    */
   public static void decrypt(Document doc, String keystore, String storetype,
      String storepass, String alias, String keypass) throws Exception {
    FileInputStream fileInputStream = new FileInputStream(keystore);
    java.security.KeyStore keyStore = java.security.KeyStore.getInstance(storetype);
    keyStore.load(fileInputStream, storepass.toCharArray());
    System.out.println("");
    System.out.println( "----------------keystore:"+keystore);
    System.out.println( "----------------storetype:"+storetype);
    System.out.println( "----------------keyStore:"+keyStore);
    System.out.println( "----------------alias:"+alias);
    System.out.println( "----------------keypass.toCharArray():"+keypass.toCharArray());
    PrivateKey prvk2 = (PrivateKey)keyStore.getKey(alias, keypass.toCharArray());

    WSSecurity wSSecurity = new WSSecurity();
     //解密。

    wSSecurity.decrypt(doc, prvk2, null);
    WsUtils.removeEncryptedKey(doc); //从 WS-Security    Header中删除 EncryptedKey 元素
  }

   public static void removeWSSElements(Document doc) throws Exception {
    WsUtils.removeWSSElements(doc); // 删除WSS相关的元素。
  }

}
class WsUtils
{

   private static final String WSSE_URI =
     "http://schemas.xmlsoap.org/ws/2002/07/secext";
  private static final String WSSE_PREFIX = "wsse";
  private static final String WSU_URI =
    "http://schemas.xmlsoap.org/ws/2002/07/utility";
  private static final String WSU_PREFIX = "wsu";
  private static final String SOAP_URI = Namespaces.SOAPENV.getUri();
  private static final String SOAP_PREFIX = Namespaces.SOAPENV.getPrefix();
  private static final String XMLSIG_URI = Namespaces.XMLSIG.getUri();
  private static final String XMLSIG_PREFIX = Namespaces.XMLSIG.getPrefix();
  private static final String XMLENC_URI = Namespaces.XMLENC.getUri();
  private static final String XMLENC_PREFIX = Namespaces.XMLENC.getPrefix();
  private static final String SOAP_ENVELOPE = "Envelope";
  private static final String SOAP_HEADER = "Header";
  private static final String SOAP_BODY = "Body";
  private static final String SOAP_FAULT = "Fault";
  private static final boolean USE_WSU_FOR_SECURITY_TOKEN_ID = false;    

  public static void removeEncryptedKey(Document message) throws XmlMessageException {

    DOMWriteCursor domCursor = new DOMWriteCursor(message);
    validate(domCursor);

    // 从 WS-Security Header中删除 EncryptedKey 元素
    if (domCursor.moveToChild(SOAP_URI, SOAP_HEADER)) {
      if (domCursor.moveToChild(WSSE_URI, "Security")) {
        if (domCursor.moveToChild(XMLENC_URI, "EncryptedKey")) {
          domCursor.remove();
        }
      }
    }
  }
  //删除WSS相关的元素。
  public static void removeWSSElements(Document message) throws XmlMessageException {
    DOMWriteCursor domWriteCursor = new DOMWriteCursor(message);

    validate(domWriteCursor);

    // 删除 WS-Security Header元素
    if (domWriteCursor.moveToChild(SOAP_URI, SOAP_HEADER)) {
      if (domWriteCursor.moveToChild(WSSE_URI, "Security")) {
        domWriteCursor.remove();
      }
    }

    // 删除 Timestamp Header 元素
    domWriteCursor.moveToTop();
    if (domWriteCursor.moveToChild(SOAP_URI, SOAP_HEADER)) {
      if (domWriteCursor.moveToChild(WSU_URI, "Timestamp")) {
        domWriteCursor.remove();
      }
    }

    // 从body中删除 wsu:Id 属性
    domWriteCursor.moveToTop();
    if (domWriteCursor.moveToChild(SOAP_URI, SOAP_BODY)) {
      domWriteCursor.setAttribute(WSU_URI, WSU_PREFIX, "Id", null);
    }    

  }
  //检查是否有效
  private static void validate(DOMCursor domCursor) throws XmlMessageException {
    domCursor.moveToTop();
    if (!domCursor.atElement(SOAP_URI, SOAP_ENVELOPE)) {
      throw new XmlMessageException("soap消息丢失或者不正确!");
    }
  }
}
 
/**
*把Document与SOAPMessage进行相互转换
*/
public class MessageConverter
{
   /**
    *把Document转换成SOAPMessage
    */
   public static SOAPMessage convertDocumentToSOAPMessage(Document doc) throws
  TransformerConfigurationException, TransformerException,    SOAPException, IOException
  {
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    transformer.transform( new DOMSource(doc), new StreamResult(byteArrayOutputStream));
    MessageFactory messageFactory = MessageFactory.newInstance();
    MimeHeaders header= new MimeHeaders();
    header.addHeader( "Content-Type", "text/xml");
    SOAPMessage soapMsg = messageFactory.createMessage(header, new ByteArrayInputStream(byteArrayOutputStream.toByteArray(),0,byteArrayOutputStream.size()));

     return soapMsg;
  }
   /**
    *把SOAPMessage转换成Document
    */
   public static Document convertSoapMessageToDocument(SOAPMessage soapMsg) throws
  ParserConfigurationException, SAXException, SOAPException, IOException
  {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    soapMsg.writeTo(byteArrayOutputStream);
    ByteArrayInputStream bais = new ByteArrayInputStream(byteArrayOutputStream.toByteArray(),0,byteArrayOutputStream.size());

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware( true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document doc = documentBuilder.parse(bais);
     return doc;
  }
}
 
package com.ws;

public class WSClientHandler extends BasicHandler{
   protected String keyStoreFile ;
   protected    String keyStoreType = "JKS"; //默认
   protected String keyStorePassword ;
   protected String keyAlias ;
   protected String keyEntryPassword ;
   protected String trustStoreFile ;
   protected String trustStoreType = "JKS"; //默认
   protected String trustStorePassword ;
   protected String certAlias ;

   public void setInitialization(String keyStoreFile,String keyStoreType,String keyStorePassword,
      String keyAlias,String keyEntryPassword,String trustStoreFile,
      String trustStoreType,String trustStorePassword,String certAlias){
     this.keyStoreFile=keyStoreFile;
     this.keyStoreType=keyStoreType;
     this.keyStorePassword=keyStorePassword;
     this.keyAlias=keyAlias;
     this.keyEntryPassword=keyEntryPassword;
     this.trustStoreFile=trustStoreFile;
     this.trustStoreType=trustStoreType;
     this.trustStorePassword=trustStorePassword;
     this.certAlias=certAlias;
  }
   public void setInitialization(String keyStoreFile,String keyStorePassword,
      String keyAlias,String keyEntryPassword,String trustStoreFile,
      String trustStorePassword,String certAlias){
     this.keyStoreFile=keyStoreFile;
     this.keyStorePassword=keyStorePassword;
     this.keyAlias=keyAlias;
     this.keyEntryPassword=keyEntryPassword;
     this.trustStoreFile=trustStoreFile;
     this.trustStorePassword=trustStorePassword;
     this.certAlias=certAlias;
  }
   public void invoke(MessageContext messageContext) throws AxisFault { //在这个方法里对XML文档进行处理
     //do nothing now!
  }
   public void onFault(MessageContext msgContext) {
    System.out.println( "处理错误,这里忽略!");
  }
}
 
package com.ws;

public class WSClientRequestHandler extends WSClientHandler{
   public void invoke(MessageContext messageContext) throws AxisFault {
     try {
      System.out.println( "-------------------------WSClientRequestHandler开始工作------------------");
      SOAPMessage soapMessage = messageContext.getMessage();
      Document doc = MessageConverter.convertSoapMessageToDocument (soapMessage); //soapMessage转换为Document
      WSHelper.sign(doc, keyStoreFile, keyStoreType,keyStorePassword,    keyAlias, keyEntryPassword); //数字签名
      WSHelper.encrypt(doc, trustStoreFile, trustStoreType,    trustStorePassword, certAlias); //加密
      soapMessage = MessageConverter.convertDocumentToSOAPMessage(doc);    
//      处理后的Document再转换回soapMessage
      messageContext.setMessage(soapMessage);
    } catch (Exception e){
      System.err.println( "在处理响应时发生以下错误�? " + e);
      e.printStackTrace();    }
  }
}    
 
package com.ws;

public class WSClientResponseHandler extends WSClientHandler{
   public void invoke(MessageContext messageContext) throws AxisFault {
     try {
      System.out.println( "-------------------------WSClientResponseHandler开始工作------------------");
      SOAPMessage soapMessage =    messageContext.getCurrentMessage();
      Document doc = MessageConverter.convertSoapMessageToDocument(soapMessage);

      WSHelper.decrypt(doc, keyStoreFile, keyStoreType,
          keyStorePassword, keyAlias, keyEntryPassword); //解密

          WSHelper.verify (doc, trustStoreFile, trustStoreType, trustStorePassword); //验证
          WSHelper.removeWSSElements(doc);
          soapMessage = MessageConverter.convertDocumentToSOAPMessage(doc);
          messageContext.setMessage(soapMessage);
    } catch (Exception e){
      e.printStackTrace();
      System.err.println( "在处理响应时发生以下错误�? " + e);
    }

  }
}        
 
package com.laoer.bbscs.webservice;

public class WSServerHandler extends BasicHandler{
   protected String keyStoreFile ;
   protected    String keyStoreType = "JKS"; //默认
   protected String keyStorePassword ;
   protected String keyAlias ;
   protected String keyEntryPassword ;
   protected String trustStoreFile ;
   protected String trustStoreType = "JKS"; //默认
   protected String trustStorePassword ;
   protected String certAlias ;

   public void invoke(MessageContext messageContext) throws AxisFault {
     //do nothing now!
  }
   public void onFault(MessageContext msgContext) {
    System.out.println( "处理错误,这里忽略!");
  }
   public void init() { //初始化,从配置文件server-config.wsdd中读取属性
    keyStoreFile = (String)getOption( "keyStoreFile");
     if(( keyStoreFile== null) )
      System.err.println( "Please keyStoreFile configured for the Handler!");
    trustStoreFile = (String)getOption( "trustStoreFile");
     if((    trustStoreFile== null) )
      System.err.println( "Please trustStoreFile configured for the Handler!");
    keyStorePassword = (String)getOption( "keyStorePassword");
     if(( keyStorePassword== null) )
      System.err.println( "Please keyStorePassword configured for the Handler!");
    keyAlias = (String)getOption( "keyAlias");
     if(( keyAlias== null) )
      System.err.println( "Please keyAlias configured for the Handler!");
    keyEntryPassword = (String)getOption( "keyEntryPassword");
     if(( keyEntryPassword== null) )
      System.err.println( "Please keyEntryPassword configured for the Handler!");
    trustStorePassword = (String)getOption( "trustStorePassword");
     if(( trustStorePassword== null) )
      System.err.println( "Please trustStorePassword configured for the Handler!");
    certAlias = (String)getOption( "certAlias");
     if ((certAlias== null))
      System.err.println( "Please certAlias configured for the Handler!");
     if ((getOption( "keyStoreType")) != null)
      keyStoreType = (String)getOption( "keyStoreType");
     if ((getOption( "trustStoreType")) != null)
      trustStoreType = (String)getOption( "trustStoreType");
  }
}        
 
package com.laoer.bbscs.webservice;

public class WSServerRequestHandler extends WSServerHandler{
   public void invoke(MessageContext messageContext) throws AxisFault {
     try {
      System.out.println( "-------------------------WSServerRequestHandler开始工作------------------");
      SOAPMessage msg = messageContext.getCurrentMessage();
      Document doc = MessageConverter.convertSoapMessageToDocument(msg);
      System.out.println( "接收的原始消息:");
      msg.writeTo(System.out);
      WSHelper.decrypt(doc, keyStoreFile, keyStoreType,
          keyStorePassword, keyAlias, keyEntryPassword); //解密

          WSHelper.verify (doc, trustStoreFile, trustStoreType, trustStorePassword); //验证
          WSHelper.removeWSSElements(doc);
          msg = MessageConverter.convertDocumentToSOAPMessage(doc);
          System.out.println( "怀原后的原始消息:");
          msg.writeTo(System.out);
          messageContext.setMessage(msg);
    } catch (Exception e){
      e.printStackTrace();
      System.err.println( "在处理响应时发生以下错误: " + e);
    }

  }
}
 
package com.laoer.bbscs.webservice;

public class WSServerResponseHandler extends WSServerHandler{
   public void invoke(MessageContext messageContext) throws AxisFault {
     try {
System.out.println( "-------------------------WSServerResponseHandler开始工作------------------");
      SOAPMessage soapMessage = messageContext.getMessage();
      System.out.println( "返回的原始消息:");
      soapMessage.writeTo(System.out);
      Document doc = MessageConverter.convertSoapMessageToDocument(soapMessage);

      WSHelper.sign(doc, keyStoreFile, keyStoreType,
          keyStorePassword, keyAlias, keyEntryPassword); //数字签名
      WSHelper.encrypt(doc, trustStoreFile, trustStoreType, //加密
          trustStorePassword, certAlias);

      soapMessage = MessageConverter.convertDocumentToSOAPMessage(doc);
      System.out.println( "返回的加密后的消息:");
      soapMessage.writeTo(System.out);
      messageContext.setMessage(soapMessage);
    } catch (Exception e){
      System.err.println( "在处理响应时发生以下错误: " + e);
      e.printStackTrace();
    }

  }
}
 
<!-- WS-Security -->    
  <service name= "WSjLogin" provider= "java:RPC">
    <requestFlow> 
            
      <handler type= "java:com.laoer.bbscs.webservice.WSServerRequestHandler">
                            <parameter name= "keyStoreFile" value= "D:\tomcat_bbs\webapps\BBSCS_8_0_3\WEB-INF\wsKeyStores\server.keystore"/>
                            <parameter name= "trustStoreFile" value= "D:\tomcat_bbs\webapps\BBSCS_8_0_3\WEB-INF\wsKeyStores\server.truststore"/>
                            <parameter name= "keyStorePassword" value= "access"/>
                            <parameter name= "keyAlias" value= "jserver"/>
                            <parameter name= "keyEntryPassword" value= "access"/>
                            <parameter name= "trustStorePassword" value= "access"/>
                            <parameter name= "certAlias" value= "clientkey"/>
                     </handler>
    </requestFlow>
    
    <responseFlow>
                     <handler type= "java:com.laoer.bbscs.webservice.WSServerResponseHandler">
                            <parameter name= "keyStoreFile" value= "D:\tomcat_bbs\webapps\BBSCS_8_0_3\WEB-INF\wsKeyStores\server.keystore"/>
                            <parameter name= "trustStoreFile"    value= "D:\tomcat_bbs\webapps\BBSCS_8_0_3\WEB-INF\wsKeyStores\server.truststore"/>
                            <parameter name= "keyStorePassword" value= "access"/>
                            <parameter name= "keyAlias" value= "jserver"/>
                            <parameter name= "keyEntryPassword" value= "access"/>
                            <parameter name= "trustStorePassword" value= "access"/>
                            <parameter name= "certAlias" value= "clientkey"/>
                     </handler>
                </responseFlow>
                
    <parameter name= "allowedMethods" value= "*" />
    <parameter name= "className" value= "com.laoer.bbscs.webservice.WSjLogin" /> 
     
  </service>
 
package com.laoer.bbscs.webservice;
public class WSjLogin extends ServletEndpointSupport{
    
   private JLogin jlogin;
   protected void onInit() throws ServiceException {    
//    在Spring容器中获取Bean的实例    
    jlogin = (JLogin) getApplicationContext().getBean( "JLogin");    
  }    

   public String getMessage(String name) throws RemoteException {    
     return "登录者"+name+ "的密码是:"+jlogin.ForWS(name);    
  }    
}
 
package com.ws;
public class WSGetJlogin {

   public static void main(String[] args)    
  {
    String endpoint= "http://127.0.0.1:8080/BBSCS_8_0_3/services/WSjLogin";
    try {
      Service service=new Service();
        
      String keyStorePath="D:/tomcat_bbs/webapps/BBSCS_8_0_3/WEB-INF/wsKeyStores/client.keystore";
      String trustStorePath="D:/tomcat_bbs/webapps/BBSCS_8_0_3/WEB-INF/wsKeyStores/client.truststore";
////注意新加的HANDLER
      WSClientHandler handler=new WSClientRequestHandler();
                        handler.setInitialization(keyStorePath,"access","jclient","access",trustStorePath,"access","serverkey");//初始化 
                        WSClientHandler handlee=new WSClientResponseHandler();
                        handlee.setInitialization(keyStorePath,"access","jclient","access",trustStorePath,"access","serverkey");//初始化 
        
      Call call=(Call)service.createCall();
        
      call.setClientHandlers(handler, handlee);//���Handler
        
      call.setTargetEndpointAddress(endpoint);
      call.setOperationName("getMessage");
      call.getMessageContext().setUsername("jason");
      call.getMessageContext().setPassword("1234");
      String bbscsPassword=(String)call.invoke(new Object[]{"shenzhenchufa"});
      System.out.println(bbscsPassword);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

使用ws-security,安全性会比较高,但同时,也比较耗系统的资源.对比安全性要求不高的,可以用Filter,Handler等轻量级的安全认证.

你可能感兴趣的:(框架,加密,认证,信息,ws-security)