2009-07-30 157 views
6

我一直试图让.NET中的XMLDSIG支持行为正常,更具体地说是SignedXml类。我正在实施第三方服务,他们刚刚开始要求所有邮件都必须进行数字签名...SignedXml生成无效签名

我的问题是,我似乎无法生成有效的签名。第三方服务和我找到的在线签名验证程序都将该签名报告为无效。验证服务(http://www.aleksey.com/xmlsec/xmldsig-verifier.html)报告摘要和数据之间不匹配,至今我一直无法弄清楚我做错了什么。

下面是相关的代码 - 希望有人能够发现我的错误;

public static XDocument SignDocument(XDocument originalDocument, X509Certificate2 certificate) 
{ 
    var document = new XmlDocument(); 
    document.LoadXml(originalDocument.ToString(SaveOptions.DisableFormatting)); 
    if (document.DocumentElement == null) 
     throw new InvalidOperationException("Invalid XML document; no root element found."); 

    var signedDocument = new SignedXml(document); 
    Reference signatureReference = GetSignatureReference(); 
    KeyInfo certificateKeyInfo = GetCertificateKeyInfo(certificate); 
    var dataObject = new DataObject("", "text/xml", "utf-8", document.DocumentElement); 

    signedDocument.AddReference(signatureReference); 
    signedDocument.AddObject(dataObject); 
    signedDocument.SigningKey = certificate.PrivateKey; 
    signedDocument.KeyInfo = certificateKeyInfo; 
    signedDocument.ComputeSignature(); 

    return XDocument.Parse(signedDocument.GetXml().OuterXml, LoadOptions.PreserveWhitespace); 
} 


private static Reference GetSignatureReference() 
{ 
    var signatureReference = new Reference(""); 
    signatureReference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); 

    return signatureReference; 
} 


private static KeyInfo GetCertificateKeyInfo(X509Certificate certificate) 
{ 
    var certificateKeyInfo = new KeyInfo(); 
    certificateKeyInfo.AddClause(new KeyInfoX509Data(certificate)); 

    return certificateKeyInfo; 
} 

回答

12

如果有人有兴趣,我解决了这个问题,我的博客上写了一篇关于它: http://thomasjo.com/blog/2009/08/04/xmldsig-in-the-net-framework.html

+1

伟大的工作! 我认为你的文章会帮助我很多!我需要使用“笼罩”类型,并且存在的文档太可怕了...... – 2009-09-22 11:26:28

+1

非常感谢您的文章! – 2012-10-16 11:55:23

+1

正确的网址是http://thomasjo.com/blog/2009/08/04/xmldsig-in-the-net-framework.html – Giorgi 2014-06-28 10:18:07