1

I want to include CA certificate in a resource file (Resources.resx) and, once read as a byte stream is provide to the X509Certificate constructor class. CA certificate is in .der format. I have added the .der file to Resources folder of the project. How can I access it in another class and pass it to X509Certificate constructor?

I was following the c# code given at the bottom in this link [http://www.embedded101.com/Blogs/PaoloPatierno/entryid/366/mqtt-over-ssl-tls-with-the-m2mqtt-library-and-the-mosquitto-broker]

update: This is the way i have did it at client side.

    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);

Yet the at the server side i get an error:

OpenSSL Error: error:140890C7:SSL routines:SSL3_GET_CLIENT_CERTIFICATE:peer did not return a certificate

Spark
  • 33
  • 1
  • 8

1 Answers1

3

If you embed your certificate into the assemblly itself (make sure that the file is an 'Embedded Resource' by right-clicking it and selecting Build Action = 'Embedded Resource' under its Properties), then you can proceed as follows:

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...
}
Tommaso Belluzzo
  • 22,356
  • 7
  • 68
  • 95
  • 1
    You have a slight typo on "new Bbyte[cs.Length]" - should be "new Byte[cs.Length]". Thanks for the code example. – JakeJ Jun 20 '18 at 20:14