Home >Backend Development >C++ >How Can I Generate a Self-Signed Certificate Using C#?

How Can I Generate a Self-Signed Certificate Using C#?

DDD
DDDOriginal
2025-01-13 07:35:42839browse

How Can I Generate a Self-Signed Certificate Using C#?

C# Self-Signed Certificate Generation Guide

There are many ways to generate a self-signed certificate, but one easy to implement in C# is to utilize the System.Security.Cryptography.X509Certificates.CertificateRequest class, which is available in .NET Framework 4.7.2 Available in and later versions. Self-signed certificates can be used for local encryption without the need to secure communications.

Code implementation:

The following sample code demonstrates how to generate a self-signed certificate using the above class:

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

public class CertificateUtil
{
    public static void GenerateCertificate()
    {
        // 生成非对称密钥对
        var ecdsa = ECDsa.Create();

        // 使用指定的主题和密钥创建证书请求
        var req = new CertificateRequest("cn=foobar", ecdsa, HashAlgorithmName.SHA256);

        // 生成自签名证书,设置有效期
        var cert = req.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(5));

        // 以PFX格式导出证书(包含私钥)
        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 generates a self-signed certificate named "foobar" using the Elliptic Curve Digital Signature Algorithm (ECDSA) and the SHA-256 hashing algorithm. Certificates are valid for five years and can be exported in PFX (PKCS #12) format (contains the private key) and CER (Base64 encoded) format (contains only the public key).

The above is the detailed content of How Can I Generate a Self-Signed Certificate Using 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