gpt4 book ai didi

c# - 使用 x509 证书签署 xml 文档

转载 作者:可可西里 更新时间:2023-11-01 09:04:09 24 4
gpt4 key购买 nike

每次我尝试发送签名的 XML 时,网络服务验证器都会拒绝它。

为了签署文档,我刚刚改编了 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));

}

我想我正在使用我自己的证书执行相同的步骤,但是它没有按预期工作。

欢迎提出任何建议。

最佳答案

服务器如何知道文档是用什么证书签名的?您似乎没有在签名文档中包含证书:

    KeyInfo keyInfo = new KeyInfo();
KeyInfoX509Data keyInfoData = new KeyInfoX509Data( Key );
keyInfo.AddClause( keyInfoData );
signedXml.KeyInfo = keyInfo;

如果您需要更多详细信息,请查阅我的博客文章

http://www.wiktorzychla.com/2012/12/interoperable-xml-digital-signatures-c_20.html

关于c# - 使用 x509 证书签署 xml 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23394654/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com