private static X509Certificate2 LoadPrivateKey(X509Certificate2 cert, string privateKeyPath)
{
// 读取 PEM 文件内容
var privateKeyPem = File.ReadAllText(privateKeyPath);
// 移除 PEM 文件的头尾
privateKeyPem = privateKeyPem.Replace("-----BEGIN PRIVATE KEY-----", "")
.Replace("-----END PRIVATE KEY-----", "")
.Replace("\n", "")
.Replace("\r", "");
// 将 Base64 编码的字符串转换为字节数组
var privateKeyBytes = Convert.FromBase64String(privateKeyPem);
// 使用 RSA 创建私钥
using var rsa = RSA.Create();
try
{
rsa.ImportRSAPrivateKey(privateKeyBytes, out _);
}
catch (CryptographicException)
{
try
{
rsa.ImportPkcs8PrivateKey(privateKeyBytes, out _);
}
catch (CryptographicException)
{
using var ecdsa = LoadEccPrivateKey(privateKeyBytes);
return cert.CopyWithPrivateKey(ecdsa);
}
}
return cert.CopyWithPrivateKey(rsa);
}
private static ECDsa LoadEccPrivateKey(byte[] privateKeyBytes)
{
// 使用 ECDsa 创建私钥
ECDsa ecdsa = ECDsa.Create();
ecdsa.ImportPkcs8PrivateKey(privateKeyBytes, out _);
return ecdsa;
}
static void filetest()
{
var certificatePath = "fullchain.crt";
var privateKeyPath = "private.pem";
var cert = X509CertificateLoader.LoadCertificateFromFile(certificatePath);
cert = LoadPrivateKey(cert, privateKeyPath);
var pfx_file_data = cert.Export(X509ContentType.Pkcs12, "123456");
//var cert2 = X509CertificateLoader.LoadPkcs12(pfx_file_data , "123456");
}
c#把.crt证书转为.pfx证书
最新推荐文章于 2025-05-26 15:02:28 发布