I missed a key part out of a post I did week ago on automating the generation of service certificates. In order to do this using Bouncy Castle you have to create #Pkcs12 store which is a security wrapper around the private key. It’s worth pointing out that a certificate doesn’t contain a private key. It’s just linked to a private key through a higher level structure. This structure can be a pfx or pkcs#12. The terms can be mutually exclusive for our usage. Anyway, I couldn’t see this code anywhere online so I thought I’d post it to save anyone the trouble of doing this on their own.

// build the key parameter and the certificate entry
var keyEntry = new AsymmetricKeyEntry(privateKey);
var entry = new X509CertificateEntry(certificate);
// build the PKCS#12 store to encapsulate the certificate
var builder = new Pkcs12StoreBuilder();
builder.SetUseDerEncoding(true);
builder.SetCertAlgorithm(PkcsObjectIdentifiers.Sha1WithRsaEncryption);
builder.SetKeyAlgorithm(PkcsObjectIdentifiers.Sha1WithRsaEncryption);
builder.Build();
// create a memorystream to hold the output 
var stream = new MemoryStream(2000);
// create the individual store and set two entries for cert and key
var store = new Pkcs12Store();
store.SetCertificateEntry("Elastacloud Test Certificate", entry);
store.SetKeyEntry("Elastacloud Test Certificate", keyEntry, new[] { entry });
store.Save(stream, userPassword.ToCharArray(), new SecureRandom());

Anyway, once you have this you can use the MemoryStream in .NET with an X509Certificate2.

Hope this helps if anyone was struggling with my former post.