It appears that the Bouncy Castle C# API has changed and the current answer no longer works. I could not find any answers on SO for how to use it now, so I'll leave this updated example. The trick is to use MiscPemGenerator.
void ConvertPfxToPem(
string pfxPath,
string pfxPassword,
string keyPath)
{
using (Stream stream = File.Open(pfxPath, FileMode.Open))
{
Pkcs12Store pkcs = new Pkcs12Store(stream, pfxPassword.ToCharArray());
foreach (string alias in pkcs.Aliases)
{
if (pkcs.IsKeyEntry(alias) && pkcs.GetKey(alias).Key.IsPrivate)
{
AsymmetricKeyParameter privateKey = pkcs.GetKey(alias).Key;
using (Stream s = new FileStream(keyPath, FileMode.Create))
using (TextWriter textWriter = new StreamWriter(s))
{
var generator = new MiscPemGenerator(privateKey);
PemWriter pemWriter = new PemWriter(textWriter);
pemWriter.WriteObject(generator);
textWriter.Flush();
}
}
}
}
}