C# Self-Signed Certificate Creation Guide: Comprehensive Analysis
In various scenarios, especially local encryption, it is necessary to create self-signed certificates. Although it is possible to use Crypt32.dll's P/Invoke implementation, this method can be complex and tedious. This article explores a more direct, P/Invoke-free method using the System.Security.Cryptography.X509Certificates namespace.
In .NET 4.7.2 and later, the CertificateRequest class provides a simplified method of generating self-signed certificates.
Create a self-signed certificate
The following code snippet demonstrates the process of creating a self-signed certificate:
<code class="language-csharp">using System; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; public class CertificateUtil { public static void CreateSelfSignedCertificate() { // 生成非对称密钥对。 ECDsa ecdsa = ECDsa.Create(); // 创建证书请求。 CertificateRequest request = new CertificateRequest("cn=foobar", ecdsa, HashAlgorithmName.SHA256); // 创建自签名证书。 X509Certificate2 certificate = request.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(5)); // 将证书导出为包含私钥的PFX (PKCS #12) 格式。 byte[] pfxBytes = certificate.Export(X509ContentType.Pfx, "P@55w0rd"); File.WriteAllBytes("mycert.pfx", pfxBytes); // 将证书导出为Base64编码的CER格式(仅包含公钥)。 string cerContents = "-----BEGIN CERTIFICATE-----\r\n" + Convert.ToBase64String(certificate.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks) + "\r\n-----END CERTIFICATE-----"; File.WriteAllText("mycert.cer", cerContents); } }</code>
This method uses Elliptic Curve Digital Signature Algorithm (ECDSA) and SHA-256 hashing to generate a self-signed certificate. The certificate is valid for five years and can be exported to PFX (PKCS #12) and CER formats.
Summary
The System.Security.Cryptography.X509Certificates namespace in .NET provides a straightforward mechanism for creating self-signed certificates in C#. This article outlines the process of generating, exporting, and storing certificates, providing a P/Invoke-free, cross-platform solution to your local encryption needs.
The above is the detailed content of How to Easily Create Self-Signed Certificates in C# Without P/Invoke?. For more information, please follow other related articles on the PHP Chinese website!