签署同X509证书XML文档 [英] signing a xml document with x509 certificate
问题描述
每次我试图发送一个签名的XML,Web服务验证拒绝它
Every time I try to send a signed XML, the web service verifier rejects it.
要签我只是适应由微软提供此示例代码的文档:
To sign the document I just adapted this sample code provided by Microsoft:
HTTP: //msdn.microsoft.com/es-es/library/ms229745(v=vs.110).aspx
我的实现:
public static XmlDocument FirmarXML(XmlDocument xmlDoc)
{
try
{
X509Certificate2 myCert = null;
var store = new X509Store(StoreLocation.CurrentUser); //StoreLocation.LocalMachine fails too
store.Open(OpenFlags.ReadOnly);
var certificates = store.Certificates;
foreach (var certificate in certificates)
{
if (certificate.Subject.Contains("xxx"))
{
myCert = certificate;
break;
}
}
if (myCert != null)
{
RSA rsaKey = ((RSA)myCert.PrivateKey);
// Sign the XML document.
SignXml(xmlDoc, rsaKey);
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
return xmlDoc;
}
// Sign an XML file.
// This document cannot be verified unless the verifying
// code has the key with which it was signed.
public static void SignXml(XmlDocument xmlDoc, RSA Key)
{
// Check arguments.
if (xmlDoc == null)
throw new ArgumentException("xmlDoc");
if (Key == null)
throw new ArgumentException("Key");
// Create a SignedXml object.
SignedXml signedXml = new SignedXml(xmlDoc);
// Add the key to the SignedXml document.
signedXml.SigningKey = Key;
// Create a reference to be signed.
Reference reference = new Reference();
reference.Uri = "";
// Add an enveloped transformation to the reference.
XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
reference.AddTransform(env);
// Add the reference to the SignedXml object.
signedXml.AddReference(reference);
// Compute the signature.
signedXml.ComputeSignature();
// Get the XML representation of the signature and save
// it to an XmlElement object.
XmlElement xmlDigitalSignature = signedXml.GetXml();
// Append the element to the XML document.
xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
}
我觉得我用我自己的证书,按照相同的步骤不过预期它不工作的。
I think I am following the same steps using my own certificate, however it doesn't works as expected.
任何建议将受到欢迎。
先谢谢了。
Any suggestion will be welcome. Thanks in advance.
推荐答案
服务器如何知道什么证书文件与签名吗?你似乎不包括已签署的文件中的证书:
How does the server know what certificate the document is signed with? You seem to not to include the cert in the signed document:
KeyInfo keyInfo = new KeyInfo();
KeyInfoX509Data keyInfoData = new KeyInfoX509Data( Key );
keyInfo.AddClause( keyInfoData );
signedXml.KeyInfo = keyInfo;
如果您需要更多的细节,请参考我的博客文章
If you need more details, consult my blog entry
http://www.wiktorzychla.com/2012/12/可互操作的XML-数字签名,c_20.html
这篇关于签署同X509证书XML文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!