3

I am trying to generate a trusted self-signed certificate for localhost. This certificate will be used for a Self Hosted Web API inside a Console Application. Due to the requirements of this project, the localhost connection has to be trusted and the application will be installed on clients PC's which means the certificate has to be generated programmatically.

I have managed to get this right in .Net Framework and all seems to work 100%, but once I moved it over to .NetCore I am hitting a wall. I am quite new to .NetCore so my knowledge is very limited.

I am using Bouncy Castle to generate the certificates but for some reason, when I try to assign the private key for the self-signed certificate in .NetCore, I get a "System.PlatformNotSupportedException: 'Operation is not supported on this platform." exception. This exception occur when I try to convert the RsaPrivateCrtKeyParameters to a PrivateKey using "DotNetUtilities.ToRSA(rsaparams)".

I followed the exact answer on this link "Generate self signed certificate on the fly".

Since my knowledge is very limited in .NetCore it would be much appreciated if someone can point me in the right direction.

Ruan
  • 175
  • 1
  • 9

1 Answers1

5

The specific problem is that .NET Core does not support the setter on cert.PrivateKey.

The closest analog is cert.CopyWithPrivateKey, but the code is different. Rather than

cert.PrivateKey = key;
return cert;

you need something more like

return cert.CopyWithPrivateKey(key);

because CopyWithPrivateKey makes a new X509Certificate2 object, leaving the target object unaltered.

FWIW, you can do the entirety of the cert creation without extra dependencies now, as shown in Generate and Sign Certificate Request using pure .net Framework.

bartonjs
  • 30,352
  • 2
  • 71
  • 111
  • That did the trick thank you very much! :) Then only thing now is I get a "ERR_CERT_COMMON_NAME_INVALID" when trying to browse to the self hosted web api. My common name, when generating the Certificates, are set as "CN={My Company Name}" for the root certificate and "CN=127.0.0.1" for the self-signed certificate. Do you know what I might be doing wrong? – Ruan Nov 13 '18 at 06:22
  • 1
    @Ruan Chrome doesn’t use Common Name for matching. You’ll need to build the Subject Alternative Name entry for your child cert (using 127.0.0.1 as an IPAddress entry, not a DNSName entry) – bartonjs Nov 13 '18 at 16:38