MasstransferExporter/MasstransferCommon/Utils/CertUtil.cs

29 lines
928 B
C#
Raw Normal View History

2024-07-03 06:24:17 +00:00
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace MasstransferCommon.Utils;
public class CertUtil
{
public static void ConvertCertToPfx(string certPath, string keyPath, string pfxPath, string password)
{
// 加载证书文件(.cer 或 .crt
var cert = new X509Certificate2(certPath);
// 加载私钥文件(.key
var keyContent = File.ReadAllText(keyPath);
// 从PEM格式的私钥中提取RSA密钥
var privateKey = RSA.Create();
privateKey.ImportFromPem(keyContent.ToCharArray());
// 创建带有私钥的X509Certificate2对象
var certWithPrivateKey = cert.CopyWithPrivateKey(privateKey);
// 导出为PFX格式
var pfxData = certWithPrivateKey.Export(X509ContentType.Pfx, password);
// 保存PFX文件
File.WriteAllBytes(pfxPath, pfxData);
}
}