gpt4 book ai didi

openssl - 使用 OpenSSL 以编程方式将 .PEM 证书转换为 .PFX

转载 作者:行者123 更新时间:2023-12-03 16:30:26 26 4
gpt4 key购买 nike

我有一个 .PEM file我想转换为 PKCS12 文件 (PFX),并且我知道我可以使用以下 openssl 轻松完成此操作命令:

Create a PKCS#12 file:

openssl pkcs12 -export -in file.pem -out file.p12 -name "My Certificate"


这很棒,但我想使用 OpenSSL 以编程方式执行此操作调用。不幸的是,OpenSSL 的文档并不理想。

我已经研究过使用其他库来做到这一点:

使用 .NET:我可以从 PEM 文件创建 X509Certificate2 对象,但这只会获取第一个证书并忽略 PEM 文件中的任何中间 CA。

使用 Mentalis.org安全库:我可以从 PEM 文件创建证书对象,但我在文档中看到以下内容:

Remarks This implementation only reads certificates from PEM files. It does not read the private key from the certificate file, if one is present.



所以,这对我没有帮助。我也需要那个私钥。

我基本上需要重新创建 OpenSSL 命令行工具操作以实现 PEM>PFX,但在代码中。

有没有更简单的方法来做到这一点?

最佳答案

您可以使用 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 examples 中找到更多详细信息。 .

关于openssl - 使用 OpenSSL 以编程方式将 .PEM 证书转换为 .PFX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3097642/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com