1

I am working on a project that requires I use AMQP with ssl. This is for communication between a linux based cloud server and a windows machine. I created a local certificate authority, a certificate, and a private key. Since I'm using Azure, this had to be stored there as a pfx file. I used no password to create the pfx.

The cloud service installation script (based on linux bash) is easily able to convert the pfx back into its parts using openssl. I am struggling more with how to use the keys on my local windows machine that is running a service that needs to read the AMQP messages.

Long story short, is there a simple way in c# to get the original private key

-----BEGIN RSA PRIVATE KEY-----
MIIEowI....
-----END RSA PRIVATE KEY-----

out of the X509Certificate2 privatekey property once i've imported the pfx file into the certificate manager?

My code so far:

X509Store certStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
certStore.Open(OpenFlags.ReadOnly);

X509Certificate2 caCert = certStore.Certificates.Find(X509FindType.FindByThumbprint, "3C97BF2632ACAB5E35B48CB94927C4A7D20BBEBA", true)[0];

RSACryptoServiceProvider rsa1 = (RSACryptoServiceProvider)caCert.PrivateKey;

EDIT: The marked as duplicate does not apply. I figured out a solution that works well. I could not find an EXACT example of how to go from certificate store to pem file in windows.

I utilized the utilities found at http://www.bouncycastle.org/csharp/

X509Store certStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
certStore.Open(OpenFlags.ReadOnly);

X509Certificate2 caCert = certStore.Certificates.Find(X509FindType.FindByThumbprint, "3C97BF2632ACAB5E35B48CB94927C4A7D20BBEBA", true)[0];


RSACryptoServiceProvider pkey = (RSACryptoServiceProvider)caCert.PrivateKey;


AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetRsaKeyPair(pkey);
using (TextWriter tw = new StreamWriter("D:\\private.pem"))
{
    PemWriter pw = new PemWriter(tw);
    pw.WriteObject(keyPair.Private);
    tw.Flush();
}
CarComp
  • 1,929
  • 1
  • 21
  • 47

0 Answers0