我需要使用WS-Security来使用Web服务。我尝试使用XDocument构建xml文件,然后使用x509证书对其进行签名。
我不知道这是否是制作肥皂信封的最佳方法......
var XElemBody = new XElement(soapEnvNS + "Body"
, new XAttribute("Id", "Body")
, new XAttribute(XNamespace.Xmlns + "wsu", wsu)
, new XElement(dgi + "WS_eFactura.EFACRECEPCIONSOBRE"
, new XElement(dgi + "Datain"
, new XElement(dgi + "xmlData"
,"<![CDATA[" + "]]>")
)
));
var soapEnv = new XDocument(new XDeclaration("1.0", "utf-8", null) //<?xml version="1.0"?>
, new XElement(soapEnvNS + "Envelope"
, new XAttribute(XNamespace.Xmlns + "SOAP-ENV", soapEnvNS)
, new XAttribute(XNamespace.Xmlns + "dgi", dgi)
, new XAttribute(XNamespace.Xmlns + "xsd", xsd)
, new XAttribute(XNamespace.Xmlns + "SOAP-ENC", soapEnc)
, new XAttribute(XNamespace.Xmlns + "xsi", xsi)
, new XElement(soapEnvNS + "Header",
new XElement(wsse + "Security"
, new XAttribute(soapEnvNS + "mustUnderstand", 1)
, new XAttribute(XNamespace.Xmlns + "wsse", wsse)
, new XElement(wsse + "BinarySecurityToken"
, new XAttribute(XNamespace.Xmlns + "wsu", wsu)
, new XAttribute("ValueType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3")
, new XAttribute("EncodingType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary")
, new XAttribute("Id", "SecurityToken")
, x509Certificate // I dont know how to generate this element
)
)
)
, XElemBody
));
signSoap(keyStorePass, keyStoreName, ref soapEnv);
结果与我需要做的非常相似,但它不起作用。
然后,使用signSoap函数我尝试签名xml,但我忽略了正确的方法。
XmlDocument xmlDoc = new XmlDocument();
// Format the document to ignore white spaces.
xmlDoc.PreserveWhitespace = false;
xmlDoc = ToXmlDocument(reporte);
var x509 = new X509Certificate2(HostingEnvironment.MapPath("~/keyStore/") + ksName, ksPass, X509KeyStorageFlags.Exportable);
RSACryptoServiceProvider PrivateKeyProvider = (RSACryptoServiceProvider)x509.PrivateKey;
SignedXml xmlFirmado = new SignedXml(xmlDoc);
xmlFirmado.SigningKey = PrivateKeyProvider;
Reference referencia = new Reference("#Body");
xmlFirmado.AddReference(referencia);
// <KeyInfo> -----------------------------------------
KeyInfo keyInfo = new KeyInfo();
var kdata = new KeyInfoX509Data();
// <X509Certificate>
var xcertificate = new X509Certificate(x509);
kdata.AddCertificate(xcertificate);
// <X509IssuerSerial>
var xserial = new X509IssuerSerial();
xserial.IssuerName = x509.IssuerName.Name.ToString();
xserial.SerialNumber = x509.SerialNumber;
kdata.AddIssuerSerial(xserial.IssuerName, xserial.SerialNumber);
keyInfo.AddClause(kdata);
xmlFirmado.KeyInfo = keyInfo;
xmlFirmado.ComputeSignature();
// take a signature in a XmlElement
XmlElement firmaDigitalXML = xmlFirmado.GetXml();
var secur = xmlDoc.FirstChild.FirstChild.FirstChild;
secur.AppendChild(xmlDoc.ImportNode(firmaDigitalXML, true));
reporte = ToXDocument(xmlDoc);
例如,我不知道如何使用命名空间引用body元素id。 我看到id有一个随机字符,例如:
Id="Body-1v-778003-fsd3223-asxv35"
这是如何产生的?
我是C#,网络服务和肥皂的新手,欢迎任何帮助,谢谢!