在C#中从文件加载公钥

时间:2013-05-16 14:35:25

标签: c#

我无法加载私钥。 我使用以下命令创建了证书:

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout privateKey.key -out certificate.crt

我创建了输出的GIST:https://gist.github.com/anonymous/5592135

    static void Main(string[] args)
    {
        string location = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
        string certLocation = location + "\\assets\\certificate.crt";
        string privateKeyLocation = location + "\\assets\\privateKey.key";
        string xmlDocLocation = location + "\\assets\\sample.xml";

        XmlDocument Doc = new XmlDocument();
        Doc.Load(xmlDocLocation);

        // read up the certificate
        X509Certificate2 cert = new X509Certificate2(certLocation);
        X509Certificate2 privateKey = new X509Certificate2(privateKeyLocation);

    }

我的证书加载正常,但我无法加载私钥。我得到“找不到请求的对象。”

我更愿意从文件加载私钥和证书而不是使用商店,这可能吗?我是否错误地生成了证书和私钥?最后,我希望将公钥包含在xml文档中,接收方将解析xml数据并验证私钥和公钥匹配。

1 个答案:

答案 0 :(得分:1)

如果您想避免使用证书存储,我建议您将CRT和密钥组合到PFX文件中。这是一个链接,将讨论如何做到这一点(或只是谷歌“openssl创建pfx”)。

https://www.globalsign.com/support/import/apache.php

在您的代码中,请记住X509Certificate2对象(例如您的cert对象)将包含公钥和私钥 - 因此您不需要为私钥使用单独的对象。创建PFX文件时,系统将提示您输入密码。此密码用于加密PFX的私钥部分。当您创建X509Certificate2对象时,您可以为其指定PFX文件的位置以及密码。以下是构造函数:

http://msdn.microsoft.com/en-us/library/ms148420.aspx

我不确定你的最终目标是什么。如果您希望客户端确保XML文件确实来自服务器并且没有被更改,那么您应该考虑使用数字签名。简而言之,发件人使用其私钥签署XML文件的哈希值,接收者使用发件人的公钥验证它。

相关问题