我需要从 .CER 和 .KEY 文件创建证书。我在 .NET 5 中有一段工作代码,但该代码需要转换为 .NET Framework 4.8。那么 .NET Framework 4.8 中不存在方法
CreateFromPemFile
,所以我需要其他方法。我已经尝试过像 BouncyCastle 这样的库,但不知何故我不断遇到异常。我什至尝试过 ChatGPT,但还没有成功。
static public X509Certificate2 CreateCertificate(string certificatePath, string keyPath)
{
return new X509Certificate2(
X509Certificate2.CreateFromPemFile(certificatePath, keyPath)
.Export(X509ContentType.Pfx));
}
也许显而易见,也许需要:
cer 文件开头为:-----BEGIN CERTIFICATE-----
密钥文件开头为:-----BEGIN PRIVATE KEY-----
经过大量阅读、尝试和询问 chatGPT,我使用 BouncyCastle 提出了以下解决方案。这对我有用。也许对其他人有帮助:
using System.IO;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Pkcs;
namespace Turien.Relations.TestConsole
{
using X509Certificate2 = System.Security.Cryptography.X509Certificates.X509Certificate2;
static class CertificateUtilities
{
static public X509Certificate2 CreateCertificate(string certificatePath, string keyPath)
{
var certParser = new Org.BouncyCastle.X509.X509CertificateParser();
var cert = certParser.ReadCertificate(File.ReadAllBytes(certificatePath));
AsymmetricCipherKeyPair keyPair;
using (var reader = new StreamReader(keyPath))
{
var pemReader = new PemReader(reader);
var rsaParams = (RsaPrivateCrtKeyParameters)pemReader.ReadObject();
var rsaPubParams = new RsaKeyParameters(false, rsaParams.Modulus, rsaParams.PublicExponent);
keyPair = new AsymmetricCipherKeyPair(rsaPubParams, rsaParams);
}
var store = new Pkcs12Store();
var certEntry = new X509CertificateEntry(cert);
store.SetCertificateEntry(cert.SubjectDN.ToString(), certEntry);
store.SetKeyEntry(cert.SubjectDN.ToString(), new AsymmetricKeyEntry(keyPair.Private), new[] { certEntry });
using (var stream = new MemoryStream())
{
store.Save(stream, null, new Org.BouncyCastle.Security.SecureRandom());
return new X509Certificate2(stream.ToArray());
}
}
}
}
这是.NET框架中证书和密钥文件的正确解决方案。