在 C# 中,使用 x.509 证书对 xml 进行签名并检查签名

In C#, sign an xml with a x.509 certificate and check the signature(在 C# 中,使用 x.509 证书对 xml 进行签名并检查签名)

本文介绍了在 C# 中,使用 x.509 证书对 xml 进行签名并检查签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 x.509 证书对 XML 文件进行签名,我可以使用私钥对文档进行签名,然后使用 CheckSignature 方法(它具有接收证书作为参数的重载)来验证签名.

I'm trying to sign an XML file using a x.509 certificate, I can use the private key to sign the document and then use the CheckSignature method (it has an overload that receives a certificate as parameter) to verify the signature.

问题是验证签名的用户必须拥有证书,我担心的是,如果用户拥有证书,那么他可以访问私钥,据我所知,这是私有的,应该只可用给签名的用户.

The problem is that the user who validates the signature must have the certificate, my concern is, if the user has the certificate then he has access to the private key, and as I understand, this is private and should be available only to the user who signs.

我错过了什么?

感谢您的帮助.

推荐答案

在 .NET 中,如果你从 .pfx 文件中获取 X509 证书,如下所示:

In .NET, If you get your X509 cert from a .pfx file, like this:

 X509Certificate2 certificate = new X509Certificate2(certFile, pfxPassword);
 RSACryptoServiceProvider rsaCsp = (RSACryptoServiceProvider) certificate.PrivateKey;   

然后你可以像这样导出公钥部分:

Then you can export the public key portion like so:

 rsaCsp.ToXmlString(false);

假"部分说,只导出公开片,不导出私人片.(RSA.ToXmlString 的文档)

The "false" part says, only export the public piece, don't export the private piece. (doc for RSA.ToXmlString)

然后在验证应用程序中,使用

And then in the verifying application, use

 RSACryptoServiceProvider csp = new RSACryptoServiceProvider();
 csp.FromXmlString(PublicKeyXml);
 bool isValid = VerifyXml(xmlDoc, rsa2);

VerifyXml 调用 CheckSignature().它看起来像这样:

And the VerifyXml calls CheckSignature(). It looks something like this:

private Boolean VerifyXml(XmlDocument Doc, RSA Key)
{
    // Create a new SignedXml object and pass it
    // the XML document class.
    var signedXml = new System.Security.Cryptography.Xml.SignedXml(Doc);

    // Find the "Signature" node and create a new XmlNodeList object.
    XmlNodeList nodeList = Doc.GetElementsByTagName("Signature");

    // Throw an exception if no signature was found.
    if (nodeList.Count <= 0)
    {
        throw new CryptographicException("Verification failed: No Signature was found in the document.");
    }

    // Though it is possible to have multiple signatures on 
    // an XML document, this app only supports one signature for
    // the entire XML document.  Throw an exception 
    // if more than one signature was found.
    if (nodeList.Count >= 2)
    {
        throw new CryptographicException("Verification failed: More that one signature was found for the document.");
    }

    // Load the first <signature> node.  
    signedXml.LoadXml((XmlElement)nodeList[0]);

    // Check the signature and return the result.
    return signedXml.CheckSignature(Key);
}

这篇关于在 C# 中,使用 x.509 证书对 xml 进行签名并检查签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 C# 中,使用 x.509 证书对 xml 进行签名并检查签名

基础教程推荐