我需要使用 C# 创建一个自签名证书(用于本地加密 - 它不用于保护通信)。
我见过一些使用 P/Invoke 的实现与 Crypt32.dll ,但它们很复杂并且很难更新参数 - 我也想尽可能避免 P/Invoke。
我不需要跨平台的东西 - 只在 Windows 上运行对我来说就足够了。
理想情况下,结果将是一个 X509Certificate2 对象,我可以使用它插入 Windows 证书存储或导出到 PFX文件。
最佳答案
从 .NET 4.7.2 开始,您可以使用 System.Security.Cryptography.X509Certificates.CertificateRequest 创建自签名证书.
例如:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
public class CertificateUtil
{
static void MakeCert()
{
var ecdsa = ECDsa.Create(); // generate asymmetric key pair
var req = new CertificateRequest("cn=foobar", ecdsa, HashAlgorithmName.SHA256);
var cert = req.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(5));
// Create PFX (PKCS #12) with private key
File.WriteAllBytes("c:\\temp\\mycert.pfx", cert.Export(X509ContentType.Pfx, "P@55w0rd"));
// Create Base 64 encoded CER (public key only)
File.WriteAllText("c:\\temp\\mycert.cer",
"-----BEGIN CERTIFICATE-----\r\n"
+ Convert.ToBase64String(cert.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks)
+ "\r\n-----END CERTIFICATE-----");
}
}
关于c# - 如何使用 C# 创建自签名证书?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13806299/