C# 使用x509证书签署xml文档
每次我尝试发送签名的XML时,web服务验证器都会拒绝它 为了签署文档,我刚刚修改了Microsoft提供的示例代码: 我的实施:C# 使用x509证书签署xml文档,c#,xml,xml-signature,x509,C#,Xml,Xml Signature,X509,每次我尝试发送签名的XML时,web服务验证器都会拒绝它 为了签署文档,我刚刚修改了Microsoft提供的示例代码: 我的实施: public static XmlDocument FirmarXML(XmlDocument xmlDoc) { try { X509Certificate2 myCert = null; var store = new X509Store(StoreLocation
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));
}
我想我正在使用我自己的证书遵循相同的步骤,但是它没有按照预期工作
欢迎提供任何建议。服务器如何知道文档的签名证书?您似乎没有在签名文档中包含证书:
KeyInfo keyInfo = new KeyInfo();
KeyInfoX509Data keyInfoData = new KeyInfoX509Data( Key );
keyInfo.AddClause( keyInfoData );
signedXml.KeyInfo = keyInfo;
如果您需要更多详细信息,请查阅我的博客
这篇文章已经很久没有发表了。我也遇到了同样的问题,数字签名无法验证 谁有同样的问题。在我的例子中,区别在于XmlDocument.PreserveWhitespace选项 当
PreserveWhitespace=true
时,文档在检查公钥时无效preservewitspace=false
使签名的XML有效
我猜在将签名的XML保存到文件并将其发送到服务器时。文档中插入了一些空格或特殊字符,使其无效。您好,Wiktor,您的博客非常有趣,我使用了您展示的示例进行测试。不幸的是,我仍然有相同的问题,签名被拒绝。我将在下面发布更多信息。只是想知道,这种方式是不是在有效负载中公开私钥,还是在有效负载中以某种方式对私钥进行了加密?@Jami:这种方式没有私钥,只有公钥(证书)。如果要使用PreserveWhitespace=true将xml中的空格保留为原始格式,然后,在验证xml的服务器代码中,在加载xml时也必须将PreserveWhitespace设置为true。