java实现XML的加密和解密

基于xml元素的加密和解密。

//加密函数

public static org.w3c.dom.Element EncryptElement(
   final String strTagNameOfElementToEncrypt,
   final org.w3c.dom.Element elemParent) throws Exception {
  org.apache.xml.security.Init.init();
  
   String strEncryptionAlgorithm = org.apache.xml.security.encryption.XMLCipher.AES_128;
   
   String strEncryptionAlgorithmProvider = null;
  
   String strEncryptionDigestAlgorithm = org.apache.xml.security.utils.Constants.ALGO_ID_DIGEST_SHA1;
  
   String strEncryptionKeyGeneratorAlgorithm = "AES";
  
   String strEncryptionKeyGeneratorAlgorithmProvider = null;
  
   int nEncryptionKeyGeneratorSize = 128;
  
   String strEncryptionKeyWrapAlgorithm = org.apache.xml.security.encryption.XMLCipher.RSA_OAEP;
  
   String strEncryptionKeyWrapAlgorithmProvider = null;
  
  final org.w3c.dom.Element domParent =elemParent;
  final org.w3c.dom.Document domDocument = domParent.getOwnerDocument();
  final org.w3c.dom.NodeList nlToEncrypts = domParent
    .getElementsByTagName(strTagNameOfElementToEncrypt);
  if (null == nlToEncrypts) {
   final String strErrorMessage = "org.w3c.dom.Element.getElementsByTagNameNS unexpectedly returned null";
  // XMLSecurityApacheExtension.log.error(strErrorMessage);
   return null;
  }
    
  if (1 != nlToEncrypts.getLength()) {
   final String strErrorMessage = "org.w3c.dom.Element.getElementsByTagNameNS unexpectedly returned "
     + nlToEncrypts.getLength() + " nodes";
  // XMLSecurityApacheExtension.log.error(strErrorMessage);
   return null;
  }
  final org.w3c.dom.Element domToEncrypt = (org.w3c.dom.Element) nlToEncrypts
    .item(0);
  final org.w3c.dom.Element domTempParent = domDocument
    .createElement("Parent");
  final org.w3c.dom.Element domTempToEncrypt = (org.w3c.dom.Element) domTempParent
    .appendChild(domToEncrypt.cloneNode(true));
  
  String pass="123456";
  FileInputStream in=new FileInputStream("C:\\Users\\mina\\tomcat.keystore");
  KeyStore ks=KeyStore.getInstance("JKS");
  ks.load(in,pass.toCharArray());
  java.security.cert.Certificate cert=ks.getCertificate("tomcat");

  final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DCPoAAk3HmXcUQS/l2ZGJPeL4W6FEJrx4ewwMdN5LnrtqbaBMGJPonDWYqQHv+kPyc0a8djq3C3vFN1MfYIVSMDser7NLqgdqKjNKP00KeuiWoN72c5bgsRl+/S+QuVaZAgLkOVzN4r3RX+jIZe2TJgYzOlCuUC8/PFnFLGcukpIv2aUzGXx8mc7yhboInwbBlleN6xJnDWLwRivA9Tf6WrymH1L6KjPBBIFq9S17dXQyFRGy0BNVHaLEu3jBk8nv0cnrjI2bCBiH9rxnmqrq5VUy0gCHxlnNNKDx7cyf98/BlbtKh43t9gb3goaKUSYWO8mkA6eT6AAIpjCWFP+K8Y3R4T9jhXBfCROTa/fpzKtN9uIMMgV6oKTwnB+ATEhGhkzkSfnymz5H0orYA2gkU8OimcZCQTAtSLkXyiyE8u3O61vR5SEyb2diVIdCkqwK8dQT4NMX2LZwsXULUV7z8fclKlvImC++r1DwBDsVtbwwlE9DxviL9sBtS2MG+oZmYA0YwrIOqOvnjI7avxFV7MzzOWRC+06WNJAnHVlFCdiR1b9Q7kteqDZ0RxzC";

   //org.eclipse.higgins.sts.utilities.CertificateHelper
    //.fromString(strCertificate);

  javax.crypto.KeyGenerator keyGenerator = null;
  if (null == strEncryptionKeyGeneratorAlgorithmProvider)
   keyGenerator = javax.crypto.KeyGenerator.getInstance("AES");
     //.getInstance("strEncryptionKeyGeneratorAlgorithm");
  else
   keyGenerator = javax.crypto.KeyGenerator.getInstance(
     "strEncryptionKeyGeneratorAlgorithm",
     strEncryptionKeyGeneratorAlgorithmProvider);
  keyGenerator.init(nEncryptionKeyGeneratorSize);
  final javax.crypto.SecretKey secretKey = keyGenerator.generateKey();
  final java.security.PublicKey publicKeyRP = certificate.getPublicKey();
  org.apache.xml.security.encryption.XMLCipher keyCipher = null;
  if (null == strEncryptionKeyWrapAlgorithmProvider)
   keyCipher = org.apache.xml.security.encryption.XMLCipher
     .getInstance(strEncryptionKeyWrapAlgorithm);
  else
   keyCipher = org.apache.xml.security.encryption.XMLCipher
     .getProviderInstance(strEncryptionKeyWrapAlgorithm,
       strEncryptionKeyWrapAlgorithmProvider);
  keyCipher.init(org.apache.xml.security.encryption.XMLCipher.WRAP_MODE,
    publicKeyRP);
  final org.apache.xml.security.keys.KeyInfo keyInfoKey = new org.apache.xml.security.keys.KeyInfo(
    domDocument);
  final java.security.MessageDigest mdSha1 = java.security.MessageDigest
    .getInstance("SHA-1");
  final byte[] byteThumbPrint = mdSha1.digest(certificate.getEncoded());
  final org.w3c.dom.Document domParentDocument = domParent
    .getOwnerDocument();
  final org.w3c.dom.Element domSTR = domParentDocument
    .createElementNS(
      "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
      "SecurityTokenReference");
  final org.w3c.dom.Element domKeyIdentifier = domParentDocument
    .createElementNS(
      "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
      "KeyIdentifier");
  domKeyIdentifier
    .setAttribute(
      "ValueType",
      "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#ThumbprintSHA1");
  domKeyIdentifier
    .setAttribute(
      "EncodingType",
      "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary");
  String strThumbprint = org.apache.xml.security.utils.Base64
    .encode(byteThumbPrint);
//  org.eclipse.higgins.sts.utilities.XMLHelper.setTextContent(
//    domKeyIdentifier, strThumbprint);
  domKeyIdentifier.setTextContent(strThumbprint);
  domSTR.appendChild(domKeyIdentifier);
  keyInfoKey.addUnknownElement(domSTR);
  final org.apache.xml.security.encryption.EncryptedKey encryptedKey = keyCipher
    .encryptKey(domDocument, secretKey);
  encryptedKey.setKeyInfo(keyInfoKey);
  final org.apache.xml.security.encryption.EncryptionMethod encryptionMethod = encryptedKey
    .getEncryptionMethod();
  final org.w3c.dom.Element elemDigestMethod = domDocument
    .createElementNS(
      org.apache.xml.security.utils.Constants.SignatureSpecNS,
      "DigestMethod");
  elemDigestMethod
    .setAttribute("Algorithm", strEncryptionDigestAlgorithm);
  encryptionMethod.addEncryptionMethodInformation(elemDigestMethod);
  org.apache.xml.security.encryption.XMLCipher xmlCipher = null;
  if (null == strEncryptionAlgorithmProvider)
   xmlCipher = org.apache.xml.security.encryption.XMLCipher
     .getInstance(strEncryptionAlgorithm);
  else
   xmlCipher = org.apache.xml.security.encryption.XMLCipher
     .getProviderInstance(strEncryptionAlgorithm,
       strEncryptionAlgorithmProvider);
  xmlCipher.init(
    org.apache.xml.security.encryption.XMLCipher.ENCRYPT_MODE,
    secretKey);
  final org.apache.xml.security.encryption.EncryptedData encryptedData = xmlCipher
    .getEncryptedData();
  final org.apache.xml.security.keys.KeyInfo keyInfoEncryption = new org.apache.xml.security.keys.KeyInfo(
    domDocument);
  keyInfoEncryption.add(encryptedKey);
  encryptedData.setKeyInfo(keyInfoEncryption);
  System.out.println("do final, encrypt the Element");
  //xmlCipher.doFinal(domDocument, domTempToEncrypt, false);
  xmlCipher.doFinal(domDocument, domTempToEncrypt,false);
  final org.w3c.dom.NodeList nlEncryptedData = domTempParent
    .getElementsByTagNameNS(
      org.apache.xml.security.utils.EncryptionConstants.EncryptionSpecNS,
      "EncryptedData");
  if (1 != nlEncryptedData.getLength()) {
   throw new Exception("One EncryptedData Not Found!");
  }
  org.w3c.dom.Element domEncryptedData = (org.w3c.dom.Element) nlEncryptedData
    .item(0);
  System.out.println("********************"+domEncryptedData.getNodeType());
//  org.eclipse.higgins.sts.utilities.XMLHelper
//    .stripNewLinesFromElement((org.w3c.dom.Element) nlEncryptedData
//      .item(0));
  domParent.replaceChild(domEncryptedData, domToEncrypt);
  
  
  System.out.println("encrypt:"+domEncryptedData);
//  org.w3c.dom.Element elemResult = null;
//  elemResult.set(domParent);
  return domParent;
  //return domEncryptedData;
 }
 //**************


 

//解密函数

public static org.w3c.dom.Element DecryptElement
 (final org.w3c.dom.Element elemEncryptedData,
 final PrivateKey privateKey) throws Exception
{
        String strEncryptionAlgorithm = org.apache.xml.security.encryption.XMLCipher.AES_128;
  
     String strEncryptionAlgorithmProvider = null;
  
  String strEncryptionKeyGeneratorAlgorithm = "AES";
    
//  int nEncryptionKeyGeneratorSize = 128;
  
  String strEncryptionKeyWrapAlgorithm = org.apache.xml.security.encryption.XMLCipher.RSA_OAEP;
  
  String strEncryptionKeyWrapAlgorithmProvider = null; 

 //XMLSecurityApacheExtension.log.trace("DecryptElement");
 
 final org.w3c.dom.Element domEncryptedData = elemEncryptedData;
 final org.w3c.dom.NodeList nlEncryptedKey = domEncryptedData.getElementsByTagNameNS
  (org.apache.xml.security.utils.EncryptionConstants.EncryptionSpecNS,
  org.apache.xml.security.utils.EncryptionConstants._TAG_ENCRYPTEDKEY);
 if (null == nlEncryptedKey)
 {
  //XMLSecurityApacheExtension.log.trace("No EncryptedKey found (getElementsByTagName returned null)");
 }
 else if (0 == nlEncryptedKey.getLength())
 {
  //XMLSecurityApacheExtension.log.trace("No EncryptedKey found (0 == getLength())");
 }
 else
 {
  final org.w3c.dom.Document domDocument = domEncryptedData.getOwnerDocument();
  final org.w3c.dom.Element elemEncryptedKey = (org.w3c.dom.Element)nlEncryptedKey.item(0);
  final org.w3c.dom.NodeList nlKeyEncryptionMethod = elemEncryptedKey.getElementsByTagNameNS
   (org.apache.xml.security.utils.EncryptionConstants.EncryptionSpecNS,
   org.apache.xml.security.utils.EncryptionConstants._TAG_ENCRYPTIONMETHOD);
  String strKeyEncryptionMethod = null;
  if (null == nlKeyEncryptionMethod)
  {
   //XMLSecurityApacheExtension.log.trace("No EncryptionMethod found");
   strKeyEncryptionMethod = strEncryptionKeyWrapAlgorithm;
  }
  else if (0 == nlKeyEncryptionMethod.getLength())
  {
   //XMLSecurityApacheExtension.log.trace("No EncryptionMethod found");
   strKeyEncryptionMethod = strEncryptionKeyWrapAlgorithm;
  }
  else
  {
   final org.w3c.dom.Element elemKeyEncryptionMethod = (org.w3c.dom.Element)nlKeyEncryptionMethod.item(0);
   strKeyEncryptionMethod = elemKeyEncryptionMethod.getAttribute(org.apache.xml.security.utils.EncryptionConstants._ATT_ALGORITHM);
  }
  org.apache.xml.security.encryption.XMLCipher keyCipher = null;
  if (null == strEncryptionKeyWrapAlgorithmProvider)
   keyCipher = org.apache.xml.security.encryption.XMLCipher.getInstance
    (strKeyEncryptionMethod);
  else
   keyCipher = org.apache.xml.security.encryption.XMLCipher.getProviderInstance
    (strKeyEncryptionMethod,
    strEncryptionKeyWrapAlgorithmProvider);
  keyCipher.init
   (org.apache.xml.security.encryption.XMLCipher.UNWRAP_MODE,
   privateKey);
  final org.apache.xml.security.encryption.EncryptedKey encryptedKey = keyCipher.loadEncryptedKey
   (domDocument,
   elemEncryptedKey);
  final java.security.Key keySecret = keyCipher.decryptKey
   (encryptedKey,
   strEncryptionKeyWrapAlgorithm);//用私钥去解密出对称密钥
  
  final javax.crypto.SecretKey secretKey = (javax.crypto.SecretKey)keySecret;//对称密钥
  final byte [] encodedSecretKey = secretKey.getEncoded();
  final javax.crypto.spec.SecretKeySpec secretKeySpec = new javax.crypto.spec.SecretKeySpec
   (encodedSecretKey,
   strEncryptionKeyGeneratorAlgorithm);//AES类型的密钥
  org.apache.xml.security.encryption.XMLCipher xmlCipher = null;
  if (null == strEncryptionAlgorithmProvider)
   xmlCipher = org.apache.xml.security.encryption.XMLCipher.getInstance
    (strEncryptionAlgorithm);
  else
   xmlCipher = org.apache.xml.security.encryption.XMLCipher.getProviderInstance
    (strEncryptionAlgorithm,
    strEncryptionAlgorithmProvider);
        xmlCipher.init
         (org.apache.xml.security.encryption.XMLCipher.DECRYPT_MODE,
         secretKeySpec);
  final org.w3c.dom.Document domResultDocument = xmlCipher.doFinal
   (domDocument,
   domEncryptedData,
   false);
//  final org.eclipse.higgins.sts.api.IElement elemResult = new org.eclipse.higgins.sts.common.Element();
//  elemResult.set
//   (domResultDocument.getDocumentElement());
        return domResultDocument.getDocumentElement();
 }
 return null;
 }


 

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
xml加密XML Encryption)是w3c加密xml的标准。这个加密过程包括加密xml文档的元素及其子元素,通过加密xml的初始内容将被替换,但其xml格式仍然被完好的保留。 介绍 我们有3个加密xml的方法 1、仅仅使用对称加密的方法加密xml 这种加密方法只使用一个密钥,也就是说无论是加密xml还是解密xml都使用一个相同的密钥。因为这个密钥不会在被加密xml中保存,所以我们需要在加密解密的过程中加载这个密钥并保护它不被窃取。 2、使用对称加密和非对称加密相结合的方法来加密xml 这种方法需要一个用于加密数据的对称密钥和一个用于保护这个对称密钥的非对称密钥。被加密的对称密钥和被加密的数据一起保存在xml文档中。当用私有非对称密钥解密密钥的时候要用公开非对称密钥对密钥进行加密。 本文就将使用这种方法。想学到其他更多的方法请参看MSDN等到更多的信息。 (译者注:非对称加密算法需要两个密钥:公开密钥(publickey)和私有密钥(privatekey)。公开密钥与私有密钥是一对,如果用公开密钥对数据进行加密,只有用对应的私有密钥才能解密;如果用私有密钥对数据进行加密,那么只有用对应的公开密钥才能解密。因为加密解密使用的是两个不同的密钥,所以这种算法叫作非对称加密算法。) 3、使用X.509加密xml,这种方法是用X.509作为非对称密钥,它由诸如VeriSign之类的第三方提供。 方法 不管xml加密是如何完成的,保存加密数据总是用两种方法之一。 1、加密后所有的元素都被命名为 2、加密后只有数据被替换,而元素名称仍然是可读的,不会发生变化。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值