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

2 Answers2

5

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
  • 23,232
  • 8
  • 74
  • 98
  • 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
0

Alternative way to "embed" cert without using resources is to add it to .fsproj/.csproj like

  <ItemGroup>
    <Content Include="mycert.pem">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
      <CopyToPublishDirectory>Always</CopyToPublishDirectory>
    </Content>
  </ItemGroup>

and then:

let certPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "mycert.pem")
let clientCert = new X509Certificate2(certPath)

(example in F# but since it's dotnet there is virtually no difference)

suside
  • 609
  • 8
  • 8