登录 |  注册 |  繁體中文


利用X.509证书对XML进行加密和签名

分类: 其它 颜色:橙色 默认  字号: 阅读(591) | 评论(0)

XML加密和签名技术应用非常广泛。

ASP.NET 使用XML加密对配置信息进行加密;InfoPath使用XML签名对表单进行签名;Web服务使用XML加密和签名对SOAP消息进行加密和签名;等等。

W3C提供了相应的标准:http://www.w3.org/TR/xmldsig-core。

而X.509是一种非常通用的证书格式,符合ITU-T X.509国际标准。此标准已用于许多网络安全应用程序:IP 安全、SSL、电子商务协议(SET)等等。

利用X.509证书提供的公钥/私钥对可以很方便的对XML进行加密和签名。Geneva框架生成的GenericXmlSecurityToken类型安全令牌就是使用X.509证书对XML进行加密和签名的。

下面是原始的XML:

  <content>
    <public>
      <name>wuhong</name>
     <job>engineer</job>
     </public>
    <private>
       <creditcard>20101220
      <phonenumber>132150
    </private>
  </content>



  • 综述

对XML加密是利用.net的System.Security.Cryptography.Xml.EncryptedXml类。

我们选择对<private>节点进行加密:

  public static void Encrypt(XmlDocument Doc, string targetElementName, string issuer)
        {
     //XML有效性验证
              XmlElement targetElement = Doc.GetElementsByTagName(targetElementName)[0] as XmlElement;
             if (targetElement == null)
            {
                throw new CryptographicException("待加密节点不存在");
            }
 
            //获取加密证书
            X509Certificate2 x = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, issuer);
 
            EncryptedXml eXml = new EncryptedXml();
            //加密
           EncryptedData encryptElement = eXml.Encrypt(targetElement, x);
            //替换加密节点
            EncryptedXml.ReplaceElement(targetElement, encryptElement, false);
        }
    

下面是关键节点加密后的XML:

<EncryptedData>是通过加密XML生成的根元素,并且它包含有关数据的所有信息。

三个子节点<EncryptionMethod>指定用来加密数据的算法;

<KeyInfo>提供有关使用什么密钥来解密数据的信息;

<CipherData>则包含实际的加密信息。

        <?xml version="1.0" encoding="utf-8" standalone="yes"?>
 <!--This is a comment-->
 <content>
  <public>
    <name>wuhong</name>
    <job>engineer</job>
  </public>
  <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element" xmlns="http://www.w3.org/2001/04/xmlenc#">
    <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes256-cbc" />
   <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
     <EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
       <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
       <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
         <X509Data>
           <X509Certificate>MIICBzCCAXCgAwIBAgIQ……</X509Certificate>
         </X509Data>
       </KeyInfo>
       <CipherData>
         <CipherValue>RmzVSAVBW6cl/cmJiEhfjwHLI413aCEI7dkdMIH4poNuc9Ql8IPuDxLdrSo4oXtntlipmRXuj5UK57rTCxu4pln1qFs+Va+2grw+pHklVej1cnZHbM9tdm8IvGcdSQ5NBY5Rg8q3fvNHfqcCrNnTF2oxjNmJQYnaJjU1sRrVkY8=</CipherValue>
       </CipherData>
     </EncryptedKey>
   </KeyInfo>
   <CipherData>
     <CipherValue>mw+YdUH/WQ2JwBgjVujQO6HYITOEqssY7eW+M+seHGG+7iyCbw6e3Hm3MZix/UqzIYqmb6hjwOaHfgXe3Xd8YsP4cmKY/GIXWN51AGnCbHUUHMeztCwEE6iA4rqQPDQrotnyAtssFm0wgHrg4NKW9Q==</CipherValue>
   </CipherData>
 </EncryptedData>
</content> 
    

可以看到,加密是非常简便的。如果利用其他密钥进行加密,则需要根据EncryptedXml类手工处理KeyInfo、EncryptedData等细节内容。

解密也非常简便:

         public static void Decrypt(XmlDocument doc, string issuer)
       {
           //获取加密证书
           X509Certificate2 x = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, issuer);
 
           EncryptedXml exml = new EncryptedXml(doc);
 
           //设置密钥-名称映射,可以随意设置一个名称,我们使用证书私钥解密
           exml.AddKeyNameMapping("rsaKey", x.PrivateKey);
 
          //解密
          //此时会寻找所有,查看节点,解密节点。用解密的结果来替换元素。
          exml.DecryptDocument();
      } 
  
  • XML加密

对XML签名是利用.net的System.Security.Cryptography.Xml.SignedXml类。

利用X.509证书对既定的XML进行签名和验证签名也比较简便。不过签名需要额外两个个步骤:

一是提供一个引用<Reference>来说明签名是包封式的;

二是提供签名证书的信息<KeyInfo>给验证签名使用。

          public static void Sign(XmlDocument Doc, string issuer)
        {
            SignedXml signedXml = new SignedXml(Doc);
 
            //获取签名证书
             X509Certificate2 x = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, issuer);
            signedXml.SigningKey = x.PrivateKey;
 
            //引用
           //指定了在哈希运算之前应当如何对将要签名的数据进行处理。
           //URI属性标识要签名的数据,而Transforms元素指定如何处理数据。
            Reference reference = new Reference();
           reference.Uri = ""; //空字符串,它指定对整个文档进行签名并且包含签名,需要特别注意的是文档中如果已经存在节点,在签名前将先被移除。
           XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();  //使用包封式签名转换
           reference.AddTransform(env);
           signedXml.AddReference(reference);
 
           //向签名的接收方提供签名证书的信息,在验证签名的同时可以验证签名证书
           KeyInfoX509Data keyInfoX509 = new KeyInfoX509Data(x, X509IncludeOption.EndCertOnly);
           signedXml.KeyInfo.AddClause(keyInfoX509);
 
           //签名
           signedXml.ComputeSignature();
 
           //将签名加入XML中
           XmlElement xmlDigitalSignature = signedXml.GetXml();
           Doc.DocumentElement.AppendChild(Doc.ImportNode(xmlDigitalSignature, true));
       }
    

下面是对整个文档进行签名后的XML:

<SignedInfo>元素的子元素包含有关所签名的内容以及签名方式的所有信息。签名算法实际上应用于该元素及其所有子元素以生成签名。

三个子节点<CanonicalizationMethod>指定了用于SignedInfo元素以便将XML规范化的规范化(C14N)算法。

<SignatureMethod>指定了该签名的签名算法。

<Reference>指定了将要签名的数据以及在哈希运算之前应当如何对该数据进行处理。<URI>属性标识要签名的数据,而<Transforms>元素指定在进行哈希运算之前如何处理数据。每个<Reference>元素都可以具有零个或更多个为它指定的转换。按照转换在<Transforms>元素下面出现的顺序,使用<DigestMethod>元素所指定的哈希算法对经过转换的数据进行哈希运算,在<DigestValue>元素中存储产生的哈希值。

<SignatureValue>包含通过签名SignedInfo元素及其所有子元素而计算得到的签名值。

<KeyInfo>存储密钥名称、密钥值、密钥检索方法或证书信息。

         <?xml version="1.0" encoding="utf-8" standalone="yes"?>
 <!--This is a comment-->
 <content>
  <public>
    <name>wuhong</name>
    <job>engineer</job>
  </public>
  <private>
    <creditcard>20101220</creditcard>
   <phonenumber>132150</phonenumber>
 </private>
 <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
   <SignedInfo>
     <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
     <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
     <Reference URI="">
       <Transforms>
         <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
       </Transforms>
       <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
       <DigestValue>4EId0mV0lU5UJ/TMa65XQFZVn9I=</DigestValue>
     </Reference>
   </SignedInfo>
   <SignatureValue>rw84o7X+F1kcennlhx7lTV15T2CuBzZGbusbi1bP+v8fBihe6EcArpvJCXkoEryzvYsr+nNngnrzSV3kYJ9K44KENVPeZfs9wTcs5aw8BUaNMtdiJLla1UeXEsz2MQj2dujTVfvTdG8qCqZVdWnSJYqyp27rnQlsj0CIzElv6EU=</SignatureValue>
   <KeyInfo>
     <X509Data>
       <X509Certificate>MIICBzCCAXCgAwIBAgIQ……</X509Certificate>
     </X509Data>
   </KeyInfo>
 </Signature>
  </content>
    

验证签名是比较简单的,代码如下:

          public static Boolean VerifySign(XmlDocument Doc, string issuer)
        {
            //XML有效性验证
            XmlNodeList nodeList = Doc.GetElementsByTagName("Signature");
            if (nodeList.Count <= 0)
            {
                throw new CryptographicException("缺失signature节点");
            }
            if (nodeList.Count >= 2)
           {
               throw new CryptographicException("signature节点多于一个");
           }
 
           SignedXml signedXml = new SignedXml(Doc);
 
           signedXml.LoadXml((XmlElement)nodeList[0]);
 
           //获取证书
           X509Certificate2 x = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, issuer);
 
           //验证签名以及证书,verifySignatureOnly设置为flase则不验证证书
           return signedXml.CheckSignature(x, true);
       }
        

转自 https://www.cnblogs.com/wuhong/archive/2010/12/20/1911526.html




姓 名: *
邮 箱:
内 容: *
验证码: 点击刷新 *   

回到顶部