我需要使用C#创建自签名证书(用于本地加密-不用于保护通信)。
我看到了一些使用P/Invoke和Crypt32.dll的实现,但它们很复杂,更新参数很难-如果可能的话,我也想避免P/Invoke。
我不需要跨平台的东西-只在Windows上运行就足够了。
理想情况下,结果应该是一个X509Certificate2对象,我可以将其插入到Windows证书存储中或导出到PFX文件中。
我需要使用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-----");
}
}
这个实现使用CX509CertificateRequestCertificate
COM对象(以及相关的内容 - MSDN文档)从certenroll.dll
创建自签名证书请求并对其进行签名。
下面的示例很简单(如果您忽略此处发生的COM部分),代码中有一些确实是可选的部分(如EKU),但仍然很有用且易于适应您的用途。
public static X509Certificate2 CreateSelfSignedCertificate(string subjectName)
{
// create DN for subject and issuer
var dn = new CX500DistinguishedName();
dn.Encode("CN=" + subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE);
// create a new private key for the certificate
CX509PrivateKey privateKey = new CX509PrivateKey();
privateKey.ProviderName = "Microsoft Base Cryptographic Provider v1.0";
privateKey.MachineContext = true;
privateKey.Length = 2048;
privateKey.KeySpec = X509KeySpec.XCN_AT_SIGNATURE; // use is not limited
privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG;
privateKey.Create();
// Use the stronger SHA512 hashing algorithm
var hashobj = new CObjectId();
hashobj.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID,
ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY,
AlgorithmFlags.AlgorithmFlagsNone, "SHA512");
// add extended key usage if you want - look at MSDN for a list of possible OIDs
var oid = new CObjectId();
oid.InitializeFromValue("1.3.6.1.5.5.7.3.1"); // SSL server
var oidlist = new CObjectIds();
oidlist.Add(oid);
var eku = new CX509ExtensionEnhancedKeyUsage();
eku.InitializeEncode(oidlist);
// Create the self signing request
var cert = new CX509CertificateRequestCertificate();
cert.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, "");
cert.Subject = dn;
cert.Issuer = dn; // the issuer and the subject are the same
cert.NotBefore = DateTime.Now;
// this cert expires immediately. Change to whatever makes sense for you
cert.NotAfter = DateTime.Now;
cert.X509Extensions.Add((CX509Extension)eku); // add the EKU
cert.HashAlgorithm = hashobj; // Specify the hashing algorithm
cert.Encode(); // encode the certificate
// Do the final enrollment process
var enroll = new CX509Enrollment();
enroll.InitializeFromRequest(cert); // load the certificate
enroll.CertificateFriendlyName = subjectName; // Optional: add a friendly name
string csr = enroll.CreateRequest(); // Output the request in base64
// and install it back as the response
enroll.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate,
csr, EncodingType.XCN_CRYPT_STRING_BASE64, ""); // no password
// output a base64 encoded PKCS#12 so we can import it back to the .Net security classes
var base64encoded = enroll.CreatePFX("", // no password, this is for internal consumption
PFXExportOptions.PFXExportChainWithRoot);
// instantiate the target class with the PKCS#12 data (and the empty password)
return new System.Security.Cryptography.X509Certificates.X509Certificate2(
System.Convert.FromBase64String(base64encoded), "",
// mark the private key as exportable (this is usually what you want to do)
System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable
);
}
使用X509Store
可以将结果添加到证书存储中,或者使用X509Certificate2
方法进行导出。
对于完全托管且未绑定到Microsoft平台的情况,并且如果您同意Mono的许可证,则可以查看Mono.Security中的X509CertificateBuilder。Mono.Security是独立于Mono的,它不需要其他Mono组件即可运行,并且可以在任何兼容的.NET环境(例如Microsoft的实现)中使用。
certenroll.dll
一起使用,该文件应该已经包含在您的操作系统中(我认为 Windows 6.0 及以上版本都有)。 - Guss另一个选择是使用来自CodePlex的CLR Security扩展库,该库实现了一个帮助函数来生成自签名的X.509证书:
X509Certificate2 cert = CngKey.CreateSelfSignedCertificate(subjectName);
您还可以查看该函数的实现(在CngKeyExtensionMethods.cs
中)以了解如何在托管代码中明确创建自签名证书。
如果有人需要帮助,我需要生成一个PEM格式的测试证书(因此需要crt和key文件),使用来自Duncan Smart的答案,我得到了以下结果...
public static void MakeCert(string certFilename, string keyFilename)
{
const string CRT_HEADER = "-----BEGIN CERTIFICATE-----\n";
const string CRT_FOOTER = "\n-----END CERTIFICATE-----";
const string KEY_HEADER = "-----BEGIN RSA PRIVATE KEY-----\n";
const string KEY_FOOTER = "\n-----END RSA PRIVATE KEY-----";
using var rsa = RSA.Create();
var certRequest = new CertificateRequest("cn=test", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
// We're just going to create a temporary certificate, that won't be valid for long
var certificate = certRequest.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddDays(1));
// export the private key
var privateKey = Convert.ToBase64String(rsa.ExportRSAPrivateKey(), Base64FormattingOptions.InsertLineBreaks);
File.WriteAllText(keyFilename, KEY_HEADER + privateKey + KEY_FOOTER);
// Export the certificate
var exportData = certificate.Export(X509ContentType.Cert);
var crt = Convert.ToBase64String(exportData, Base64FormattingOptions.InsertLineBreaks);
File.WriteAllText(certFilename, CRT_HEADER + crt + CRT_FOOTER);
}
Null
的问题。 - undefined您可以使用免费的PluralSight.Crypto库来简化编程式创建自签名X.509证书:
using (CryptContext ctx = new CryptContext())
{
ctx.Open();
X509Certificate2 cert = ctx.CreateSelfSignedCertificate(
new SelfSignedCertProperties
{
IsPrivateKeyExportable = true,
KeyBitLength = 4096,
Name = new X500DistinguishedName("cn=localhost"),
ValidFrom = DateTime.Today.AddDays(-1),
ValidTo = DateTime.Today.AddYears(1),
});
X509Certificate2UI.DisplayCertificate(cert);
}
Pluralsight.Crypto需要.NET 3.5或更高版本。
// This code was written by Keith Brown, and may be freely used.
- Andrzej Gis这是一个控制台应用程序,它会询问用户主机名、过期天数和密码。
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
Console.Write("Enter hostname: ");
string hostname = Console.ReadLine();
Console.Write("Enter days until expiration: ");
int days = int.Parse(Console.ReadLine());
Console.Write("Enter password, enter to skip: ");
string password = Console.ReadLine();
// Generate a new RSA key pair
RSA rsa = RSA.Create();
// Create a certificate request with the specified subject and key pair
CertificateRequest request = new CertificateRequest(
$"CN={hostname}",
rsa,
HashAlgorithmName.SHA256,
RSASignaturePadding.Pkcs1);
// Create a self-signed certificate from the certificate request
X509Certificate2 certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(days));
// Export the certificate to a file with password
byte[] certBytes = string.IsNullOrEmpty(password)
? certificate.Export(X509ContentType.Pfx)
: certificate.Export(X509ContentType.Pfx, password);
File.WriteAllBytes($"{hostname}.pfx", certBytes);
Console.WriteLine($"Certificate for {hostname} created successfully and will expire on {certificate.NotAfter}.");
Console.WriteLine($"Path: {Path.Combine(AppContext.BaseDirectory, hostname)}.pfx");
Console.ReadKey();
基于在此处找到的代码,通过添加SubjectAlternativeNames来扩展0909EMs answer:了解C#中自签名证书
public static void MakeCert(string certFilename, string keyFilename)
{
const string CRT_HEADER = "-----BEGIN CERTIFICATE-----\n";
const string CRT_FOOTER = "\n-----END CERTIFICATE-----";
const string KEY_HEADER = "-----BEGIN RSA PRIVATE KEY-----\n";
const string KEY_FOOTER = "\n-----END RSA PRIVATE KEY-----";
using var rsa = RSA.Create();
var certRequest = new CertificateRequest("cn=test", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
// Adding SubjectAlternativeNames (SAN)
var subjectAlternativeNames = new SubjectAlternativeNameBuilder();
subjectAlternativeNames .AddDnsName("test");
certRequest.CertificateExtensions.Add(subjectAlternativeNames.Build());
// We're just going to create a temporary certificate, that won't be valid for long
var certificate = certRequest.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddDays(1));
// export the private key
var privateKey = Convert.ToBase64String(rsa.ExportRSAPrivateKey(), Base64FormattingOptions.InsertLineBreaks);
File.WriteAllText(keyFilename, KEY_HEADER + privateKey + KEY_FOOTER);
// Export the certificate
var exportData = certificate.Export(X509ContentType.Cert);
var crt = Convert.ToBase64String(exportData, Base64FormattingOptions.InsertLineBreaks);
File.WriteAllText(certFilename, CRT_HEADER + crt + CRT_FOOTER);
}
关于使用X509KeyUsageExtension
定义密钥的用法,请查看此处https://dev59.com/XlYM5IYBdhLWcg3w7jc1#48210587
这是关于如何创建证书的Powershell版本。您可以通过执行命令来使用它。 请查看https://technet.microsoft.com/itpro/powershell/windows/pkiclient/new-selfsignedcertificate
编辑:忘记说了,在创建证书之后,您可以使用Windows的“管理计算机证书”程序将证书导出为.CER或其他类型。