views:

1771

answers:

2

Backstory: I have a PKCS#12 (p12) certificate with a symmetric cipher (password) that I used OpenSSL to convert to a PEM; opening that as text I see it contains both a BEGIN/END CERTIFICATE section as well as BEGIN/END RSA PRIVATE KEY. The .NET Framework X509Certificate class only supports the "ASN.1 DER" format, so I used OpenSSL to convert the PEM to DER. Unfortunately it appears doing this doesn't include the private key which is what I need for making an SSL connection with SslStream & TcpClient.

X509CertificateCollection certsFromFile = new X509CertificateCollection();
X509Certificate2 cert = new X509Certificate2("my.der.crt");
if (!cert.HasPrivateKey)
    throw new Exception("No private key");
certsFromFile.Add(cert);

TcpClient tcpclient = new TcpClient(hostname, port);
SslStream sslstream = new SslStream(tcpclient.GetStream(), false,
    null, null);
sslstream.AuthenticateAsClient(hostname, certsFromFile,
    SslProtocols.Ssl3, false);
sslstream.Close();
tcpclient.Close();

How do I take this PEM file and make it into a DER while retaining the private key information so I can use it in .NET for signing?

A: 

Certificates and keys are generally stored separately. Cut the PEM file into two files, one with the certificate and one with the key. You can then use the openssl toolkit to convert each file separately into a DER file.

nsayer
+1  A: 

Oops, I'm behind the times! Looks like X509Certificate2 can read PKCS#12 files so there's no need for any conversion.

Neil C. Obremski