如何在C#中创建X509Certificate2时更改颁发者名称

本文关键字:X509Certificate2 创建 | 更新日期: 2023-09-27 18:25:22

我正在C#.net应用程序中创建X509Certificate2证书。创建证书时,如何设置颁发者名称?当前颁发者名称显示为和使用者名称相同。

请帮忙。

如何在C#中创建X509Certificate2时更改颁发者名称

嗯。

最后,我使用Bouncy Castle dll来创建证书。使用此方法,可以设置颁发者名称。

这是生成x509Certificate并存储到Trusted People存储的完整代码:

 private X509Certificate2 GeneratePFXFile(string certificate,string company,string   email,string state,string locality,string username,string country)
    {
        X509Certificate2 cert = null;
        try
        {
            var kpgen = new RsaKeyPairGenerator();
            kpgen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 2048));
            var kp = kpgen.GenerateKeyPair();
            var gen = new X509V3CertificateGenerator();
            var certName = new X509Name("CN=" + certificate);
            var issuer = new X509Name("C="+country+",O="+company+",OU=LBC Mundial Corp.USA,E="+email+",L="+locality+",ST="+state);
            var serialNo = BigInteger.ProbablePrime(120, new Random());
            gen.SetSerialNumber(serialNo);
            gen.SetSubjectDN(certName);
            gen.SetIssuerDN(issuer);
            gen.SetNotAfter(DateTime.Now.AddYears(50));
            gen.SetNotBefore(DateTime.Now);
            gen.SetSignatureAlgorithm("MD5WithRSA");
            gen.SetPublicKey(kp.Public);
            gen.AddExtension(
                X509Extensions.AuthorityKeyIdentifier.Id,
                false,
                new AuthorityKeyIdentifier(
                    SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public),
                    new GeneralNames(new GeneralName(certName)),
                    serialNo));
            gen.AddExtension(
                X509Extensions.ExtendedKeyUsage.Id,
                false,
                new ExtendedKeyUsage(new ArrayList() { new DerObjectIdentifier("1.3.6.1.5.5.7.3.1") }));
            var newCert = gen.Generate(kp.Private);
            byte[] pfx = DotNetUtilities.ToX509Certificate(newCert).Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pfx, (string)null);
            X509Store store = new X509Store((StoreName)StoreName.TrustedPeople, (StoreLocation)StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadWrite);
            cert = new X509Certificate2(pfx,(string)null, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);
            store.Add(cert);
            store.Close();
        }
        catch (Exception ex)
        {
            ShowError(ex.Message);
            return null;
        }
        return cert;
    }