MasstransferExporter/MasstransferCommon/Utils/CertUtil.cs

29 lines
928 B
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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);
}
}