您可以使用BouncyCastle(假设 C#,因为您提到了 .NET)。
假设localhost.pem
这里包含证书和私钥,这样的东西应该可以工作:
using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.IO;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.Security;
namespace TestApplication
{
class Program
{
static void Main(string[] args)
{
StreamReader sr = File.OpenText("localhost.pem");
IPasswordFinder passwordFinder = new PasswordStore("testtest".ToCharArray());
PemReader pemReader = new PemReader(sr, passwordFinder);
Pkcs12Store store = new Pkcs12StoreBuilder().Build();
X509CertificateEntry[] chain = new X509CertificateEntry[1];
AsymmetricCipherKeyPair privKey = null;
object o;
while ((o = pemReader.ReadObject()) != null)
{
if (o is X509Certificate)
{
chain[0] = new X509CertificateEntry((X509Certificate)o);
}
else if (o is AsymmetricCipherKeyPair)
{
privKey = (AsymmetricCipherKeyPair)o;
}
}
store.SetKeyEntry("test", new AsymmetricKeyEntry(privKey.Private), chain);
FileStream p12file = File.Create("localhost.p12");
store.Save(p12file, "testtest".ToCharArray(), new SecureRandom());
p12file.Close();
}
}
class PasswordStore : IPasswordFinder
{
private char[] password;
public PasswordStore(
char[] password)
{
this.password = password;
}
public char[] GetPassword()
{
return (char[])password.Clone();
}
}
}
IPasswordFinder
如果您想正确处理证书链,您可能需要一些更微妙的东西。有关更高级的功能,您可以在BouncyCastle 示例中找到更多详细信息。