在C#代码

时间:2017-11-09 15:37:10

标签: c# x509certificate resx ca

我想将CA证书包含在资源文件(Resources.resx)中,并且一旦读取为字节流,就会提供给X509Certificate构造函数类。 CA证书采用.der格式。我已将.der文件添加到项目的Resources文件夹中。如何在另一个类中访问它并将其传递给X509Certificate构造函数?

我正在关注此链接[http://www.embedded101.com/Blogs/PaoloPatierno/entryid/366/mqtt-over-ssl-tls-with-the-m2mqtt-library-and-the-mosquitto-broker]

底部的c#代码

更新:这是我在客户端做到的方式。

    client = new MqttClient(ddlServerIP.Text, MqttSettings.MQTT_BROKER_DEFAULT_SSL_PORT, true, new X509Certificate(Properties.Resources.ca)
           , new X509Certificate(Properties.Resources.client2), MqttSslProtocols.TLSv1_2);   
        String clientId= Guid.NewGuid().ToString();
        byte code = client.Connect(clientId);

然而在服务器端我得到一个错误:

  

OpenSSL错误:错误:140890C7:SSL例程:SSL3_GET_CLIENT_CERTIFICATE:peer未返回证书

1 个答案:

答案 0 :(得分:0)

如果您将证书嵌入到自己的组合中(通过右键单击该文件并选择Build Action =' Embedded Resource'确保该文件是一个'嵌入式资源)属性),然后您可以按以下步骤操作:

using (Stream cs = Assembly.GetExecutingAssembly().GetManifestResourceStream("MyProj.MyCert.cer"))
{
    Byte[] raw = new Byte[cs.Length];

    for (Int32 i = 0; i < cs.Length; ++i)
        raw[i] = (Byte)cs.ReadByte();

    X509Certificate2 cert = new X509Certificate2();
    cert.Import(raw);

    // Do whatever you need...
}