使用RSA签署Xml文档
我正在使用下面的方法来签署Xml文档:
public static XmlDocument SignDocument(XmlDocument doc)
{
string signatureCanonicalizationMethod = "http://www.w3.org/2001/10/xml-exc-c14n#";
string signatureMethod = @"http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
string digestMethod = @"http://www.w3.org/2001/04/xmlenc#sha256";
string signatureReferenceURI = "#_73e63a41-156d-4fda-a26c-8d79dcade713";
CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), signatureMethod);
var signingCertificate = GetCertificate();
SignedXml signer = new SignedXml(doc);
signer.SigningKey = signingCertificate.PrivateKey;
signer.KeyInfo = new KeyInfo();
signer.KeyInfo.AddClause(new KeyInfoX509Data(signingCertificate));
signer.SignedInfo.CanonicalizationMethod = signatureCanonicalizationMethod;
signer.SignedInfo.SignatureMethod = signatureMethod;
XmlDsigEnvelopedSignatureTransform envelopeTransform = new XmlDsigEnvelopedSignatureTransform();
XmlDsigExcC14NTransform cn14Transform = new XmlDsigExcC14NTransform();
Reference signatureReference = new Reference();
signatureReference.Uri = signatureReferenceURI;
signatureReference.AddTransform(envelopeTransform);
signatureReference.AddTransform(cn14Transform);
signatureReference.DigestMethod = digestMethod;
signer.AddReference(signatureReference);
signer.ComputeSignature();
XmlElement signatureElement = signer.GetXml();
doc.DocumentElement.AppendChild(signer.GetXml());
return doc;
}
private static X509Certificate2 GetCertificate()
{
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
X509Certificate2 card = null;
foreach (X509Certificate2 cert in store.Certificates)
{
if (!cert.HasPrivateKey) continue;
if (cert.Thumbprint.Equals("a_certain_thumb_print", StringComparison.OrdinalIgnoreCase))
{
card = cert;
break;
}
}
store.Close();
return card;
}
尝试使用错误消息指定的无效算法计算签名时,会引发System.Security.Cryptography.CryptographicException类型的异常。 有任何想法吗?
机器:Windows Server 2008 R2
.Net Framework:4.0。
IDE:Visual Studio 2010。
非常感谢这个博客。 它实际上解决了我的问题。 顺便说一下,如果从文件加载证书,它应该是可导出的:X509Certificate2 x509Key = new X509Certificate2(“xxxxx.pfx”,“123”, X509KeyStorageFlags.Exportable );
string signatureMethod = @“http://www.w3.org/2001/04/xmldsig-more#rsa-sha256”;
根据https://msdn.microsoft.com/zh-CN/library/system.security.cryptography.xml.signedinfo.signaturemethod(v = vs.110).aspx,此签名方法未在.NET中实现
@minhj的回复提到了一些博客,但链接不存在。
但是,添加此处提到的类并注册它可以解决问题。 似乎它应该只在每个应用程序域中注册一次。
链接地址: http://www.djcxy.com/p/62937.html上一篇: Signing an Xml Document using RSA
下一篇: InvalidOperationException when creating PerformanceCounter