I'm working on some code that currently uses OpenSSL.net to create a public/private key pair for a Certificate Signing Request. The request is equipped with the public key and sent to a CA which returns a signed certificate. Then the previously created private key is added to the certificate:
myCert.PrivateKey = CryptoKey.FromPrivateKey(rsa.PrivateKeyAsPEM, null);
The problem is I need a .net X509Certificate because the rest of the software uses SslStream and other .net classes for TLS.
I was able to create a certificate from the CA's response, but I did not find a way to add the private key to it. I also tried creating an OpenSSL certificate from the CA's response, exporting that as DER or PEM and creating the .net certificate from that, but it always ignores the private key.
Any ideas on how I could solve this problem?
I've created a small helper NuGet package to create a X509 certificate based on public key and private (rsa) key.
// Generate with: openssl req -x509 -sha256 -nodes -days 365 -newkey rsa:2048 -keyout private.key -out certificate_pub.crt
string certificateText = File.ReadAllText("certificate_pub.crt");
string privateKeyText = File.ReadAllText("private.key");
ICertificateProvider provider = new CertificateFromFileProvider(certificateText, privateKeyText);
X509Certificate2 certificate = provider.Certificate;
// Example: use the PrivateKey from the certificate above for signing a JWT token using Jose.Jwt:
string token = Jose.JWT.Encode(payload, certificate.PrivateKey, JwsAlgorithm.RS256);
See NuGet and Github-project for functionality and code-examples based on opensslkey.
I guess maybe you are missing some conceptual ideas here?
A Certificate is not supposed to contain a Private Key. The Private Key is always private, a certificate is what that binds your public key to your distinguished name. In other words a Certificate is a document that is signed by an authority that confirms that a particular Public Key, that you share with the world, belongs to you and no one else. Therefore it never can contain the Private Key, because you share your certificate with the world!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With