Home >Backend Development >C++ >How Can I Easily Generate Self-Signed Certificates in C#?

How Can I Easily Generate Self-Signed Certificates in C#?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-13 07:13:42564browse

How Can I Easily Generate Self-Signed Certificates in C#?

Easily generate self-signed certificates in C#

Developers often need to create self-signed certificates for various purposes, such as local encryption without securing communications. In C#, this task can be accomplished using the direct method introduced in .NET 4.7.2.

Using the System.Security.Cryptography.X509Certificates.CertificateRequest class you can easily create self-signed certificates. The following code snippet demonstrates how:

<code class="language-csharp">using System;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

public class CertificateUtil
{
    static void MakeCert()
    {
        var ecdsa = ECDsa.Create(); // 生成非对称密钥对
        var req = new CertificateRequest("cn=foobar", ecdsa, HashAlgorithmName.SHA256);
        var cert = req.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(5));

        // 创建包含私钥的PFX (PKCS #12) 文件
        File.WriteAllBytes("c:\temp\mycert.pfx", cert.Export(X509ContentType.Pfx, "P@55w0rd"));

        // 创建Base64编码的CER (仅包含公钥) 文件
        File.WriteAllText("c:\temp\mycert.cer",
            "-----BEGIN CERTIFICATE-----\r\n"
            + Convert.ToBase64String(cert.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks)
            + "\r\n-----END CERTIFICATE-----");
    }
}</code>

This code uses ECDSa to generate an asymmetric key pair and creates a CertificateRequest object. Subsequently, it calls the CreateSelfSigned method to generate a self-signed certificate. Certificates can be exported to a PFX file containing the private key or to a Base64-encoded CER file containing only the public key.

With this simplified approach, developers can avoid the complexity of P/Invoke and conveniently create self-signed certificates in C#.

The above is the detailed content of How Can I Easily Generate Self-Signed Certificates in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn