我尝试在 ASP.NET Web 服务中唱歌和加密 SOAP 消息。
//I have Crypt class, which input parameters is Stream:
public class CryptUtility
{
public virtual Stream EncryptAndSingXml (Stream inputStream)
{
XmlTextReader reader = new XmlTextReader(inputStream);
XmlDocument doc = new XmlDocument();
doc.Load(reader);
// in this place I encrypt and sign SOAP message
foreach (string xPathQuery in soapElement)
{
XmlNodeList nodesToEncrypt = doc.SelectNodes(xPathQuery, nsMan);
foreach (XmlNode nodeToEncrypt in nodesToEncrypt)
{
// method EncryptString crypt only string from XmlNode
nodeToEncrypt.InnerXml = EncryptString();
}
}
// !!!
// I THINK HERE IS A PROBLEM
//
//it return plain stream, no encrypt stream
MemoryStream retStream = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(retStream, Encoding.UTF8);
doc.Save(retStream);
return retStream;
}
}
我在 Soap 扩展类中使用了 CryptUtility 对象:
public class SoapMsg : SoapExtension
{
private CryptUtility cryptUtil; //this object crypt and sing SOAP message
// ...
//this method copy stream
private void CopyStream(Stream from, Stream to)
{
TextReader reader = new StreamReader(from);
TextWriter writer = new StreamWriter(to);
writer.Write(reader.ReadToEnd());
writer.Flush();
}
//this method sing and encrypt SOAP message, I call this method in stage AfterSerialize
private void CryptMessage()
{
newStream.Position = 0;
Stream retStream = cryptUtil.EncryptAndSingXml(newStream);
retStream.Position = 0;
CopyStream(retStream, oldStream);
}
public override void ProcessMessage(SoapMessage message)
{
switch (message.Stage)
{
case SoapMessageStage.BeforeSerialize:
break;
case SoapMessageStage.AfterSerialize:
{
// call the crypt and sing method
CryptMessage();
//save the SOAP message, the message is not encrypt
Log(message, "AfterSerialize");
}
break;
case SoapMessageStage.BeforeDeserialize:
break;
case SoapMessageStage.AfterDeserialize:
break;
default:
throw new ArgumentException("error.");
}
}
// ...
}
问题是,当我在 AfterDeserialize 中记录 SOAP 消息时,XML 是纯文本,但它应该是加密的 有人可以帮我吗,哪里有问题,或者我能做些什么不好?
因为首先我在 SoapMsg 类中使用方法 EncryptAndSingXml 作为 void,它工作正常!!! 像这样的东西:
public class SoapMsg : SoapExtension
{
//...
public void EncryptAndSingXml()
{...}
//...
public override void ProcessMessage(SoapMessage message)
{
switch (message.Stage)
{
//...
case SoapMessageStage.AfterSerialize:
EncryptAndSingXml();
break;
//...
}
// ...
}
但是,当我将类 CryptUtility 和方法 EncryptAndSingXml() 设为虚拟时,它不起作用。:( 有人可以帮助我吗?