日期:2012-09-17  浏览次数:20454 次

加密对外发送的报文

这里我简单描述下如何创建一个可以返回个被加密的XML文档的Web服务。第一步先用using指示符来添加必要的命名空间,如下:

using System.Web.Services;

using Microsoft.Web.Services;

using Microsoft.Web.Services.Security;

using System.Security.Cryptography;

using System.Security.Cryptography.Xml;

using System.Xml;

GetXmlDocument方法使用了的.NET框架实现的三元DES算法,采用128位密钥和64位初始化向量(IV),能够生成对称密钥。这个密钥还将拥有一个名字,并被添加到应答报文的SoapContext元素上,之后被SecurityOutputFilter使用于加密简单的XML文档,这个方法最后将返回给客户端。更多关于.NET框架的加密技术,请看.NET框架开发者指南上的Cryptography Overview一文。

//返回由三元DES对称算法加密后的数据

[WebMethod (Description="返回一个由对称加密算法机密后的敏感XML文档", EnableSession=false)]



public XmlDocument GetXmlDocument()

{

//创建一个用于返回的简单的XML文档

XmlDocument myDoc = new XmlDocument();

myDoc.InnerXml =

"<EncryptedResponse>这里是敏感数据.</EncryptedResponse>";



//得到对外发送的回应报文的SoapContext

SoapContext myContext = HttpSoapContext.ResponseContext;



//创建一个用于加密的对称密钥,由于密钥是对称的,这些相同的数据必须存在有需求的客户端上。



//定义共享的16字节数组,用来表示128位密钥

byte[] keyBytes = {48, 218, 89, 25, 222, 209, 227, 51, 50, 168, 146,

188, 250, 166, 5, 206};



//定义共享的8字节(64位)数组,也就是初始化向量(IV)

byte[] ivBytes = {16, 143, 111, 77, 233, 137, 12, 72};



//创建三元DES算法的新实例

SymmetricAlgorithm mySymAlg = new TripleDESCryptoServiceProvider();



//设置好密钥和IV

mySymAlg.Key = keyBytes;

mySymAlg.IV = ivBytes;





//创建一个新的WSE对称加密密钥

EncryptionKey myKey = new SymmetricEncryptionKey(mySymAlg);





//给他取个名字J

KeyInfoName myKeyName = new KeyInfoName();

myKeyName.Value = "http://example.com/symmetrictestkey";

myKey.KeyInfo.AddClause(myKeyName);





//使用对称密钥来创建一个新的EncryptedData元素

EncryptedData myEncData = new EncryptedData(myKey);





//将EncryptedData元素添加到SOAP回应上,告诉过滤器用指定的密钥来加密信息正文



myContext.Security.Elements.Add(myEncData);



return myDoc;

}

基于前面的方法,WSE管道产生了下面有相应的安全头信息,密文和密钥信息的回应报文:

<?xml version="1.0" encoding="utf-8"?>

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<soap:Header>

<wsu:Timestamp

xmlns:wsu="http://schemas.xmlsoap.org/ws/2002/07/utility">

<wsu:Created>2003-02-11T02:07:23Z</wsu:Created>

<wsu:Expires>2003-02-11T02:12:23Z</wsu:Expires>

</wsu:Timestamp>

<wsse:Security soap:mustUnderstand="1"

xmlns:wsse="http://schemas.xmlsoap.org/ws/2002/07/secext">

<xenc:ReferenceList

xmlns:xenc="http://www.w3.org/2001/04/xmlenc#">

<xenc:DataReference URI=

"#EncryptedContent-f50076e3-5aea-435e-8493-5d7860191411" />

</xenc:ReferenceList>

</wsse:Security>

</soap:Header>

<soap:Body xmlns:wsu="http://schemas.xmlsoap.org/ws/2002/07/utility"

wsu:Id="Id-d2f22e02-a052-4dcb-8fbc-8591a45b8a9f">

<xenc:EncryptedData

Id="EncryptedContent-f50076e3-5aea-435e-8493-5d7860191411"

Type="http://www.w3.org/2001/04/xmlenc#Content"

xmlns:xenc="http://www.w3.org/2001/04/xmlenc#">

<xenc:EncryptionMethod