在C#中,签署与X.509证书的XML和检查签名 [英] In C#, sign an xml with a x.509 certificate and check the signature

查看:257
本文介绍了在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);

在假的部分说,只导出公众一块,不要导出私钥件。 (DOC的<一个href=\"http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsa.toxmlstring.aspx\">RSA.ToXmlString)

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

And then in the verifying application, use

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

而VerifyXml调用 CheckSignature()。它看起来是这样的:

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和检查签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆