CSDN博客

img yuzhouhenan

我自己的基于versign实现的wss加密

发表于2008/9/30 10:53:00  415人阅读

 package wss;
import com.verisign.xmlenc.*;
import com.verisign.xmlsig.*;
import javax.crypto.*;
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import java.security.*;
import java.nio.*;
import com.verisign.xpath.*;
import javax.crypto.Cipher;
import java.security.*;
import org.xmltrustcenter.verifier.X509TrustVerifier;
import java.security.cert.X509Certificate;
import org.w3c.dom.Document;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import java.io.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.soap.MimeHeaders;
import javax.xml.transform.stream.StreamResult;
import javax.xml.soap.MessageFactory;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;

public class WSSUtil {
  static String PROVIDER="ISNetworks";//JSSE安全提供者。
//添加JSSE安全提供者,你也可以使用其它安全提供者。只要支持DESede算法。这是程序里动态加载还可以在JDK中静态加载
 static
 {
   java.security.Security.addProvider(new com.isnetworks.provider.jce.ISNetworksProvider());
}
/**
*对XML文档进行数字签名。
*/

  public WSSUtil() {
  }
  public  void encrypt(Document doc, String keystore, String storetype,
                               String storepass, String alias,XPath path){
  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);

    AlgorithmType dataEncryptionAlgoType = AlgorithmType.TRIPLEDES;

   com.verisign.xmlenc.AlgorithmType keyEncryptionAlgoType = com.verisign.xmlenc.AlgorithmType.RSA1_5;
   KeyInfo keyInfo = new KeyInfo();


   com.verisign.xmlenc.Encryptor enc =new com.verisign.xmlenc.Encryptor(doc, key, AlgorithmType.TRIPLEDES, pubk, AlgorithmType.RSA1_5, ki);
   enc.encryptInPlace(path);

  }
  catch (Exception e) {
   System.out.println("Some exception");
   e.printStackTrace();
  }}

public  void decrypt(Document doc, String keystore, String storetype,
                               String storepass, String alias, String keypass){
   try{
     FileInputStream fileInputStream = new FileInputStream(keystore);
     java.security.KeyStore keyStore = java.security.KeyStore.getInstance(storetype);
     keyStore.load(fileInputStream, storepass.toCharArray());
     PrivateKey prvk2 = (PrivateKey)keyStore.getKey(alias, keypass.toCharArray());


   String xpath = "//xenc:EncryptedData";
   String[] ns ={ "xenc", "http://www.w3.org/2001/04/xmlenc#" };
   XPath path = new XPath(xpath, ns);

   com.verisign.xmlenc.Decryptor dec=new com.verisign.xmlenc.Decryptor(doc, prvk2, path);
   dec.decryptInPlace();
   WSSecurityExtn.removeWSSEncryptedKey (doc);
   WSSecurityExtn.removeWSSInfo(doc);
 }
 catch (Exception e) {
  System.out.println("Some exception");
  e.printStackTrace();
 }
}

public  Document readXML(String filename) throws
Exception {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      dbf.setNamespaceAware(true);
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document doc = db.parse(filename);
      return doc;
  }

 public  void writeXML(Document doc, OutputStream os) throws
  Exception {
      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer transformer = tf.newTransformer();
      transformer.transform(new DOMSource(doc), new StreamResult(os));
  }

public  SOAPMessage convertDocumentToSOAPMessage(Document doc)
     throws Exception {
   System.out.println("运行到这里convertDocumentToSOAPMessage");
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    System.out.println("运行到这里1convertDocumentToSOAPMessage");
    DOMSource ds=new  DOMSource(doc);
    System.out.println("运行到这里-1convertDocumentToSOAPMessage");
    transformer.transform(ds, new StreamResult(byteArrayOutputStream));
    System.out.println("运行到这里2convertDocumentToSOAPMessage");
    MimeHeaders header = new MimeHeaders();
    header.addHeader("Content-Type", "text/xml");
    MessageFactory factory = MessageFactory.newInstance();
    System.out.println("运行到这里3convertDocumentToSOAPMessage");
    SOAPMessage soapMsg = factory.createMessage(header,new ByteArrayInputStream(byteArrayOutputStream.toByteArray(),0, byteArrayOutputStream.size()));
    System.out.println("util中的document转为message"+soapMsg.getSOAPPart().getEnvelope());
    return soapMsg;
   }

   /**
    * SOAPMessage转换成Document
    */
   public  Document convertSoapMessageToDocument(SOAPMessage soapMsg)
     throws Exception {
    System.out.println("wssutil"+soapMsg);
    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);
    System.out.print("wssutil"+doc.getDocumentElement().getNodeName());
    return doc;
   }

}


import org.apache.axis.handlers.*;
import org.apache.axis.AxisFault;
import org.apache.axis.MessageContext;
import org.apache.axis.message.*;
import java.io.*;
import java.security.MessageDigest;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPElement;
import wss.*;
import org.w3c.dom.*;
import com.verisign.xpath.*;

public class tttt {
  public tttt() {
  }
  public static void main(String[] args) {
    try{WSSUtil wss=new WSSUtil();
    Document doc=wss.readXML("d://mm.xml");
    SOAPMessage msg=wss.convertDocumentToSOAPMessage(doc);
    XPath path=new XPath("//arg0");
    wss.encrypt(doc,"f:/client.keystore","JKS","changeit","Client",path);
    wss.writeXML(doc,new FileOutputStream("d://mm1.xml"));

    SOAPMessage msg1=wss.convertDocumentToSOAPMessage(doc);
    Document doc1=wss.convertSoapMessageToDocument(msg1);
   // Document doc1=WSSUtil.readXML("d://mm1.xml");
    wss.decrypt(doc1,"f:/client.keystore","JKS","changeit","Client","changeit");
    wss.writeXML(doc1,new FileOutputStream("d://mm2.xml"));

  }catch(Exception e){e.printStackTrace();}

  }

}
0 0

相关博文

我的热门文章

img
取 消
img