c# - 如何在 .NET 中使用 RSA key 签署 XML 文件?

标签 c# .net cryptography rsa signature

我正在尝试使用私有(private) RSA 在 C# .NET 3.5 中对 XML 文件进行签名OpenSSL 生成的 key .

我是这样处理的:我从 PEM 转换了 RSA key 使用 chilkat 框架将格式转换为 XML 格式 (www.example-code.com/csharp/cert_usePrivateKeyFromPEM.asp)

有了我的 XML key ,我现在可以使用我更喜欢的 native .NET 函数。所以我使用了 MSDN 中描述的方法.

所以,最后,我的源代码是这样的:

RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider();

//Load the private key from xml file
XmlDocument xmlPrivateKey = new XmlDocument();
xmlPrivateKey.Load("PrivateKey.xml");
rsaProvider.FromXmlString(xmlPrivateKey.InnerXml);

 // Create a SignedXml object.
 SignedXml signedXml = new SignedXml(Doc);

 // 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.
 Doc.DocumentElement.AppendChild(Doc.ImportNode(xmlDigitalSignature, true));

我用这个函数得到的签名 XML 看起来不错,我在文件末尾有 XML 元素,它应该是这样的:

<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
  <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
  <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
  <Reference URI="">
    <Transforms>
      <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
    </Transforms>
    <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
    <DigestValue>qoGPSbe4oR9e2XKN6MzP+7XlXYI=</DigestValue>
  </Reference>
</SignedInfo>
<SignatureValue>iPQ6IET400CXfchWJcP22p2gK6RpEc9mkSgfoA94fL5UM6+AB5+IO6BbjsNt31q6MB8hR6lAIcnjzHzc5SeXvFP8Py2bqHTYJvcSA6KcKCQl1LiDNt12UwWiKpSkus2p0LdAeeZJNy9aDxjC/blUaZEr4uPFt0kGCD7h1NQM2SY=</SignatureValue>

问题是当我尝试在这个 URL 上使用 xmlsec 验证签名时:http://www.aleksey.com/xmlsec/xmldsig-verifier.html .我收到一条消息,告诉我签名无效。

几天来我一直在寻找我的代码中的错误,但我找不到。我开始认为从 PEM 到 XML 文件的转换可能是问题所在,但我不知道如何测试它。此外,我没有找到任何其他方法来转换为 key 或直接在 .NET 中使用 PEM 文件。

有没有人设法在 .NET 中获得有效签名?

最佳答案

是的,我做到了。 我认为问题出在您的引用资料上。 uri 应该指向签名所针对的元素的 id。不管怎样,请检查下面的代码,希望它能为您指明正确的方向。

/克劳斯

/// <summary>
    /// Signs an XmlDocument with an xml signature using the signing certificate given as argument to the method.
    /// </summary>
    /// <param name="doc">The XmlDocument to be signed</param>
    /// <param name="id">The is of the topmost element in the xmldocument</param>
    /// <param name="cert">The certificate used to sign the document</param>
    public static void SignDocument(XmlDocument doc, string id, X509Certificate2 cert)
    {
        SignedXml signedXml = new SignedXml(doc);
        signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
        signedXml.SigningKey = cert.PrivateKey;

        // Retrieve the value of the "ID" attribute on the root assertion element.
        Reference reference = new Reference("#" + id);

        reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
        reference.AddTransform(new XmlDsigExcC14NTransform());

        signedXml.AddReference(reference);

        // Include the public key of the certificate in the assertion.
        signedXml.KeyInfo = new KeyInfo();
        signedXml.KeyInfo.AddClause(new KeyInfoX509Data(cert, X509IncludeOption.WholeChain));

        signedXml.ComputeSignature();
        // Append the computed signature. The signature must be placed as the sibling of the Issuer element.
        XmlNodeList nodes = doc.DocumentElement.GetElementsByTagName("Issuer", Saml20Constants.ASSERTION);
        // doc.DocumentElement.InsertAfter(doc.ImportNode(signedXml.GetXml(), true), nodes[0]);            
        nodes[0].ParentNode.InsertAfter(doc.ImportNode(signedXml.GetXml(), true), nodes[0]);
    }

关于c# - 如何在 .NET 中使用 RSA key 签署 XML 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1825000/

相关文章:

java - 安卓数据库的安全 key

c# - RSS阅读器的组织

c# - 在类之间编写共享枚举的最佳实践是什么

c# - 将枚举添加到组合框

c# - WinForms:检测光标何时进入/离开表单或其控件

javascript - iOS 平台的 React Native 中加密图像并将其保存在 Gallery 中的方法?

c# - 查找在 Visual Studio 或单元测试中未使用 await 的异步用法

.net - 在 WPF 或 winform 中绘制 3D 图形

c# - 在 C# 中使函数非阻塞/异步的简单方法?

c - 在已编译的应用程序中隐藏密码/ key