我需要使用C#创建一个自签名证书(用于本地加密-它不用于保护通信).

我见过一些使用P/InvokeCrypt32.dll的实现,但它们很复杂,而且很难更新参数——如果可能的话,我也希望避免使用P/Invoke.

我不需要跨平台的东西——只在Windows上运行对我来说就足够了.

理想情况下,结果将是一个X509Certificate2对象,我可以使用它插入Windows证书存储或导出到PFX文件.

推荐答案

此实现使用certenroll.dll中的CX509CertificateRequestCertificate COM对象(和friends-MSDN doc)创建自签名证书请求并对其签名.

下面的例子非常直截了当(如果你忽略了这里的一些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.InitializeFrom算法rithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID,
        ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY, 
        算法rithmFlags.算法rithmFlagsNone, "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.Hash算法rithm = 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方法导出结果.

对于完全托管且没有绑定到微软平台的,如果你对Mono的许可没有意见,那么你可以从Mono.Security开始看X509CertificateBuilder.Mono.Security是独立于Mono的,因为它不需要Mono的睡觉来运行,并且可以在任何兼容的.NET环境中使用(例如微软的实现).

.net相关问答推荐

将Visual Studio更新到v17.9.3后,IDE关闭,dotnet.exe命令报告致命错误.内部CLR错误.(0x80131506)

如何从 tshark 的 stderr 捕获实时数据包计数?

无法加载文件或程序集 不支持操作. (来自 HRESULT 的异常:0x80131515)

为什么 .Contains 慢?通过主键获取多个实体的最有效方法?

将 DataRowCollection 转换为 IEnumerable

您是否使用 TestInitialize 或测试类构造函数来准备每个测试?为什么?

比较 C# 中的字符串和对象

ILMerge 最佳实践

泛型方法是如何、何时、何地具体化的?

String 是原始类型吗?

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") 返回上午时间而不是下午时间?

如何对无法加载的 VSTO 插件进行故障排除?

X509Certificate 构造函数异常

ILookup 接口与 IDictionary

.NET 进程间通信的最佳 Select 是什么?

将两个列表映射到 C# 中的字典中

无法加载文件或程序集Antlr3.Runtime (1)或其依赖项之一

C# List<> 按 x 然后 y 排序

在 .Net 中调用 Web 服务时绕过无效的 SSL 证书错误

是否可以判断对象是否已附加到实体框架中的数据上下文?