public static byte[] CreatePfxBytes(
            Org.BouncyCastle.X509.X509Certificate certificate
            , Org.BouncyCastle.Crypto.AsymmetricKeyParameter privateKey
            , string password = "")
        {
            byte[] pfxBytes = null;

            // create certificate entry
            Org.BouncyCastle.Pkcs.X509CertificateEntry certEntry =
                new Org.BouncyCastle.Pkcs.X509CertificateEntry(certificate);

            Org.BouncyCastle.Asn1.X509.X509Name name = new Org.BouncyCastle.Asn1.X509.X509Name(certificate.SubjectDN.ToString());
            string friendlyName = (string)name.GetValueList(Org.BouncyCastle.Asn1.X509.X509Name.O)[0];

            if (System.StringComparer.InvariantCultureIgnoreCase.Equals("Skynet Earth Inc.", friendlyName))
            {
                friendlyName = "Skynet Certification Authority";
            }

            Org.BouncyCastle.Pkcs.Pkcs12StoreBuilder builder = new Org.BouncyCastle.Pkcs.Pkcs12StoreBuilder();
            builder.SetUseDerEncoding(true);


            Org.BouncyCastle.Pkcs.Pkcs12Store store = builder.Build();

            store.SetCertificateEntry(friendlyName, certEntry);

            // create store entry
            store.SetKeyEntry(
                friendlyName
                , new Org.BouncyCastle.Pkcs.AsymmetricKeyEntry(privateKey)
                , new Org.BouncyCastle.Pkcs.X509CertificateEntry[] { certEntry }
                );



            using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
            {
                // Cert is contained in store
                // null: no password, "": an empty passwords
                // note: Linux needs empty password on null...
                store.Save(stream, password == null ? "".ToCharArray() : password.ToCharArray(), new Org.BouncyCastle.Security.SecureRandom());
                // stream.Position = 0;
                pfxBytes = Org.BouncyCastle.Pkcs.Pkcs12Utilities.ConvertToDefiniteLength(stream.ToArray());
            } // End Using stream

            return(pfxBytes);
        } // End Function CreatePfxBytes
Beispiel #2
0
        // DumpPfx(ee25519Cert, subject, caKey25519);
        public static void DumpPfx(
            Org.BouncyCastle.X509.X509Certificate bouncyCert
            , Org.BouncyCastle.Asn1.X509.X509Name subject
            , Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair pair)
        {
            Org.BouncyCastle.Pkcs.Pkcs12Store          store            = new Org.BouncyCastle.Pkcs.Pkcs12Store();
            Org.BouncyCastle.Pkcs.X509CertificateEntry certificateEntry =
                new Org.BouncyCastle.Pkcs.X509CertificateEntry(bouncyCert);

            store.SetCertificateEntry(subject.ToString(), certificateEntry);

            store.SetKeyEntry(subject.ToString(),
                              new Org.BouncyCastle.Pkcs.AsymmetricKeyEntry(pair.Private)
                              , new[] { certificateEntry }
                              );

            Org.BouncyCastle.Security.SecureRandom random =
                new Org.BouncyCastle.Security.SecureRandom(
                    new Org.BouncyCastle.Crypto.Prng.CryptoApiRandomGenerator()
                    );

            using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
            {
                string tempPassword = "******";
                store.Save(stream, tempPassword.ToCharArray(), random);
                using (System.Security.Cryptography.X509Certificates.X509Certificate2 cert =
                           new System.Security.Cryptography.X509Certificates.X509Certificate2(
                               stream.ToArray()
                               , tempPassword
                               , System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.PersistKeySet
                               | System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable)
                       )
                {
                    System.Text.StringBuilder builder = new System.Text.StringBuilder();

                    builder.AppendLine("-----BEGIN CERTIFICATE-----");
                    builder.AppendLine(System.Convert.ToBase64String(
                                           cert.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert)
                                           , System.Base64FormattingOptions.InsertLineBreaks)
                                       );
                    builder.AppendLine("-----END CERTIFICATE-----");

                    // PFX
                    //builder.ToString().Dump("Self-signed Certificate");
                } // End Using cert
            }     // End Using stream
        }         // End Sub DumpPfx
Beispiel #3
0
        /// <summary>
        /// Request certificate from the ACME server
        /// </summary>
        /// <param name="binding"></param>
        /// <returns></returns>
        public CertificateInfo RequestCertificate(ICsrPlugin csrPlugin, RunLevel runLevel, Renewal renewal, Target target, OrderDetails order)
        {
            // What are we going to get?
            var pfxFileInfo = new FileInfo(PfxFilePath(renewal));

            // Determine/check the common name
            var identifiers     = target.GetHosts(false);
            var commonNameUni   = target.CommonName;
            var commonNameAscii = string.Empty;

            if (!string.IsNullOrWhiteSpace(commonNameUni))
            {
                var idn = new IdnMapping();
                commonNameAscii = idn.GetAscii(commonNameUni);
                if (!identifiers.Contains(commonNameAscii, StringComparer.InvariantCultureIgnoreCase))
                {
                    _log.Warning($"Common name {commonNameUni} provided is invalid.");
                    commonNameAscii = identifiers.First();
                    commonNameUni   = idn.GetUnicode(commonNameAscii);
                }
            }

            // Determine the friendly name
            var friendlyName = renewal.FriendlyName;

            if (string.IsNullOrEmpty(friendlyName))
            {
                friendlyName = target.FriendlyName;
            }
            if (string.IsNullOrEmpty(friendlyName))
            {
                friendlyName = commonNameUni;
            }

            // Try using cached certificate first to avoid rate limiting during
            // (initial?) deployment troubleshooting. Real certificate requests
            // will only be done once per day maximum unless the --force parameter
            // is used.
            var cache = CachedInfo(renewal);

            if (cache != null &&
                cache.CacheFile.LastWriteTime > DateTime.Now.AddDays(Settings.Default.CertificateCacheDays * -1) &&
                cache.Match(target))
            {
                if (runLevel.HasFlag(RunLevel.IgnoreCache))
                {
                    _log.Warning("Cached certificate available but not used with --{switch}. Use 'Renew specific' or " +
                                 "'Renew all' in the main menu to run unscheduled renewals without hitting rate limits.",
                                 nameof(MainArguments.Force).ToLower());
                }
                else
                {
                    _log.Warning("Using cached certificate for {friendlyName}. To force issue of a new certificate within " +
                                 "24 hours, delete the .pfx file from the CertificatePath or run with the --{switch} switch. " +
                                 "Be ware that you might run into rate limits doing so.",
                                 friendlyName,
                                 nameof(MainArguments.Force).ToLower());
                    return(cache);
                }
            }

            var csr      = csrPlugin.GenerateCsr(commonNameAscii, identifiers);
            var csrBytes = csr.CreateSigningRequest();

            order = _client.SubmitCsr(order, csrBytes);
            File.WriteAllText(GetPath(renewal, "-csr.pem"), _pemService.GetPem("CERTIFICATE REQUEST", csrBytes));

            _log.Information("Requesting certificate {friendlyName}", friendlyName);
            var rawCertificate = _client.GetCertificate(order);

            if (rawCertificate == null)
            {
                throw new Exception($"Unable to get certificate");
            }

            var certificate       = new X509Certificate2(rawCertificate);
            var certificateExport = certificate.Export(X509ContentType.Cert);
            var crtPem            = _pemService.GetPem("CERTIFICATE", certificateExport);

            // Get issuer certificate
            var issuerCertificate       = new X509Certificate2(rawCertificate.Skip(certificateExport.Length).ToArray());
            var issuerCertificateExport = issuerCertificate.Export(X509ContentType.Cert);
            var issuerPem = _pemService.GetPem("CERTIFICATE", issuerCertificateExport);

            // Build pfx archive
            var pfx                = new bc.Pkcs.Pkcs12Store();
            var bcCertificate      = _pemService.ParsePem <bc.X509.X509Certificate>(crtPem);
            var bcCertificateEntry = new bc.Pkcs.X509CertificateEntry(bcCertificate);
            var bcCertificateAlias = bcCertificate.SubjectDN.ToString();
            var bcPrivateKeyEntry  = new bc.Pkcs.AsymmetricKeyEntry(csrPlugin.GetPrivateKey());

            pfx.SetCertificateEntry(bcCertificateAlias, bcCertificateEntry);
            pfx.SetKeyEntry(bcCertificateAlias, bcPrivateKeyEntry, new[] { bcCertificateEntry });

            var bcIssuer      = _pemService.ParsePem <bc.X509.X509Certificate>(issuerPem);
            var bcIssuerEntry = new bc.Pkcs.X509CertificateEntry(bcIssuer);
            var bcIssuerAlias = bcIssuer.SubjectDN.ToString();

            pfx.SetCertificateEntry(bcIssuerAlias, bcIssuerEntry);

            var pfxStream = new MemoryStream();

            pfx.Save(pfxStream, null, new bc.Security.SecureRandom());
            pfxStream.Position = 0;
            using (var pfxStreamReader = new BinaryReader(pfxStream))
            {
                var tempPfx = new X509Certificate2(
                    pfxStreamReader.ReadBytes((int)pfxStream.Length),
                    (string)null,
                    X509KeyStorageFlags.MachineKeySet |
                    X509KeyStorageFlags.PersistKeySet |
                    X509KeyStorageFlags.Exportable);
                if (csrPlugin.CanConvert())
                {
                    try
                    {
                        var converted = csrPlugin.Convert(tempPfx.PrivateKey);
                        if (converted != null)
                        {
                            tempPfx.PrivateKey = converted;
                        }
                    }
                    catch
                    {
                        _log.Warning("Private key conversion error.");
                    }
                }

                tempPfx.FriendlyName = $"{friendlyName} {DateTime.Now.ToUserString()}";
                File.WriteAllBytes(pfxFileInfo.FullName, tempPfx.Export(X509ContentType.Pfx, renewal.PfxPassword?.Value));
                pfxFileInfo.Refresh();
            }

            // Update LastFriendlyName so that the user sees
            // the most recently issued friendlyName in
            // the WACS GUI
            renewal.LastFriendlyName = friendlyName;

            // Recreate X509Certificate2 with correct flags for Store/Install
            return(new CertificateInfo()
            {
                Certificate = ReadForUse(pfxFileInfo, renewal.PfxPassword?.Value),
                CacheFile = pfxFileInfo,
                CacheFilePassword = renewal.PfxPassword?.Value
            });
        }
Beispiel #4
0
        // System.Security.Cryptography.X509Certificates.X509Certificate2.Import (string fileName);

        // https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.x509certificates.x509certificate2.import?view=netframework-4.7.2
        // https://gist.github.com/yutopio/a217a4af63cf6bcf0a530c14c074cf8f
        // https://gist.githubusercontent.com/yutopio/a217a4af63cf6bcf0a530c14c074cf8f/raw/42b2f8cb27f6d22b7e22d65da5bbd0f1ce9b2fff/cert.cs
        // https://stackoverflow.com/questions/44755155/store-pkcs12-container-pfx-with-bouncycastle
        // https://github.com/Worlaf/RSADemo/blob/328692e28e48db92340d55563480c8724d916384/RSADemo_WinForms/frmRsaDemo.cs
        public static void Create(
            string fileName
            , Org.BouncyCastle.X509.X509Certificate certificate
            , Org.BouncyCastle.Crypto.AsymmetricKeyParameter privateKey
            , string password = "")
        {
            // create certificate entry
            Org.BouncyCastle.Pkcs.X509CertificateEntry certEntry =
                new Org.BouncyCastle.Pkcs.X509CertificateEntry(certificate);

            Org.BouncyCastle.Asn1.X509.X509Name name = new Org.BouncyCastle.Asn1.X509.X509Name(certificate.SubjectDN.ToString());
            string friendlyName = name
                                  .GetValueList(Org.BouncyCastle.Asn1.X509.X509Name.O)
                                  .OfType <string>()
                                  .FirstOrDefault();

            if (System.StringComparer.InvariantCultureIgnoreCase.Equals("Skynet Earth Inc.", friendlyName))
            {
                friendlyName = "Skynet Certification Authority";
            }

            // get bytes of private key.
            Org.BouncyCastle.Asn1.Pkcs.PrivateKeyInfo keyInfo = Org.BouncyCastle.Pkcs.PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);
            //byte[] keyBytes = keyInfo.ToAsn1Object().GetEncoded();

            Org.BouncyCastle.Pkcs.Pkcs12StoreBuilder builder = new Org.BouncyCastle.Pkcs.Pkcs12StoreBuilder();
            builder.SetUseDerEncoding(true);



            Org.BouncyCastle.Pkcs.Pkcs12Store store = builder.Build();

            store.SetCertificateEntry(friendlyName, certEntry);

            // create store entry
            store.SetKeyEntry(
                //keyFriendlyName
                friendlyName
                , new Org.BouncyCastle.Pkcs.AsymmetricKeyEntry(privateKey)
                , new Org.BouncyCastle.Pkcs.X509CertificateEntry[] { certEntry }
                );


            byte[] pfxBytes = null;

            using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
            {
                // Cert is contained in store
                // null: no password, "": an empty passwords
                // note: Linux needs empty password on null...
                store.Save(stream, password == null ? "".ToCharArray() : password.ToCharArray(), new Org.BouncyCastle.Security.SecureRandom());
                // stream.Position = 0;
                pfxBytes = stream.ToArray();
            } // End Using stream


#if WITH_MS_PFX
            WithMsPfx(pfxBytes, fileName, password);
#else
            byte[] result = Org.BouncyCastle.Pkcs.Pkcs12Utilities.ConvertToDefiniteLength(pfxBytes);
            // this.StoreCertificate(System.Convert.ToBase64String(result));

            using (System.IO.BinaryWriter writer = new System.IO.BinaryWriter(System.IO.File.Open(fileName, System.IO.FileMode.Create)))
            {
                writer.Write(result);
            } // End Using writer
#endif
        }     // End Sub Create
Beispiel #5
0
        /// <summary>
        /// Request certificate from the ACME server
        /// </summary>
        /// <param name="binding"></param>
        /// <returns></returns>
        public CertificateInfo RequestCertificate(ICsrPlugin csrPlugin, Renewal renewal, Target target, OrderDetails order)
        {
            // What are we going to get?
            var pfxFileInfo = new FileInfo(PfxFilePath(renewal));

            // Determine/check the common name
            var identifiers = target.GetHosts(false);
            var commonName  = target.CommonName;

            if (!string.IsNullOrWhiteSpace(commonName))
            {
                var idn = new IdnMapping();
                commonName = idn.GetAscii(commonName);
                if (!identifiers.Contains(commonName, StringComparer.InvariantCultureIgnoreCase))
                {
                    _log.Warning($"Common name {commonName} provided is invalid.");
                    commonName = identifiers.First();
                }
            }

            // Try using cached certificate first to avoid rate limiting during
            // (initial?) deployment troubleshooting. Real certificate requests
            // will only be done once per day maximum.
            if (pfxFileInfo.Exists && pfxFileInfo.LastWriteTime > DateTime.Now.AddDays(-1))
            {
                try
                {
                    var cached = new CertificateInfo()
                    {
                        Certificate = ReadForUse(pfxFileInfo, renewal.PfxPassword),
                        PfxFile     = pfxFileInfo
                    };
                    var idn = new IdnMapping();
                    if (cached.SubjectName == commonName &&
                        cached.HostNames.Count == identifiers.Count() &&
                        cached.HostNames.All(h => identifiers.Contains(idn.GetAscii(h))))
                    {
                        if (_options.Force)
                        {
                            _log.Warning("Cached certificate available but not used with --{switch}. Use 'Renew specific' or 'Renew all' in the main menu to run unscheduled renewals without hitting rate limits.", nameof(MainArguments.Force).ToLower());
                        }
                        else
                        {
                            _log.Warning("Using cached certificate for {friendlyName}. To force issue of a new certificate within 24 hours, delete the .pfx file from the CertificatePath or run with the --{switch} switch. Be ware that you might run into rate limits doing so.", renewal.FriendlyName, nameof(MainArguments.Force).ToLower());
                            return(cached);
                        }
                    }
                }
                catch
                {
                    // File corrupt or invalid password?
                    _log.Warning("Unable to read from certificate cache");
                }
            }

            var csr      = csrPlugin.GenerateCsr(commonName, identifiers);
            var csrBytes = csr.CreateSigningRequest();

            order = _client.SubmitCsr(order, csrBytes);

            if (Settings.Default.SavePrivateKeyPem)
            {
                File.WriteAllText(GetPath(renewal, "-key.pem"), GetPem(csrPlugin.GeneratePrivateKey()));
            }
            File.WriteAllText(GetPath(renewal, "-csr.pem"), GetPem("CERTIFICATE REQUEST", csrBytes));

            _log.Information("Requesting certificate {friendlyName}", renewal.FriendlyName);
            var rawCertificate = _client.GetCertificate(order);

            if (rawCertificate == null)
            {
                throw new Exception($"Unable to get certificate");
            }

            var certificate       = new X509Certificate2(rawCertificate);
            var certificateExport = certificate.Export(X509ContentType.Cert);

            var crtDerFile = GetPath(renewal, $"-crt.der");
            var crtPemFile = GetPath(renewal, $"-crt.pem");
            var crtPem     = GetPem("CERTIFICATE", certificateExport);

            _log.Information("Saving certificate to {crtDerFile}", _certificatePath);
            File.WriteAllBytes(crtDerFile, certificateExport);
            File.WriteAllText(crtPemFile, crtPem);

            // Get issuer certificate and save in DER and PEM formats
            var chain = new X509Chain();

            chain.Build(certificate);
            X509Certificate2 issuerCertificate = chain.ChainElements[1].Certificate;
            var issuerCertificateExport        = issuerCertificate.Export(X509ContentType.Cert);
            var issuerPem = GetPem("CERTIFICATE", issuerCertificateExport);

            File.WriteAllBytes(GetPath(renewal, "-crt.der", "ca-"), issuerCertificateExport);
            File.WriteAllText(GetPath(renewal, "-crt.pem", "ca-"), issuerPem);

            // Generate combined files
            File.WriteAllText(GetPath(renewal, "-chain.pem", "ca-"), crtPem + issuerPem);

            // Build pfx archive
            var pfx                = new bc.Pkcs.Pkcs12Store();
            var bcCertificate      = ParsePem <bc.X509.X509Certificate>(crtPem);
            var bcCertificateEntry = new bc.Pkcs.X509CertificateEntry(bcCertificate);
            var bcCertificateAlias = bcCertificate.SubjectDN.ToString();
            var bcPrivateKeyEntry  = new bc.Pkcs.AsymmetricKeyEntry(csrPlugin.GeneratePrivateKey());

            pfx.SetCertificateEntry(bcCertificateAlias, bcCertificateEntry);
            pfx.SetKeyEntry(bcCertificateAlias, bcPrivateKeyEntry, new[] { bcCertificateEntry });

            var bcIssuer      = ParsePem <bc.X509.X509Certificate>(issuerPem);
            var bcIssuerEntry = new bc.Pkcs.X509CertificateEntry(bcIssuer);
            var bcIssuerAlias = bcIssuer.SubjectDN.ToString();

            pfx.SetCertificateEntry(bcIssuerAlias, bcIssuerEntry);

            using (var pfxStream = new MemoryStream())
            {
                pfx.Save(pfxStream, null, new bc.Security.SecureRandom());
                pfxStream.Position = 0;
                using (var pfxStreamReader = new BinaryReader(pfxStream))
                {
                    var tempPfx = new X509Certificate2(
                        pfxStreamReader.ReadBytes((int)pfxStream.Length),
                        (string)null,
                        X509KeyStorageFlags.MachineKeySet |
                        X509KeyStorageFlags.PersistKeySet |
                        X509KeyStorageFlags.Exportable);
                    if (csrPlugin.CanConvert())
                    {
                        try
                        {
                            var converted = csrPlugin.Convert(tempPfx.PrivateKey);
                            if (converted != null)
                            {
                                tempPfx.PrivateKey = converted;
                            }
                        }
                        catch
                        {
                            _log.Warning("Private key conversion error.");
                        }
                    }

                    tempPfx.FriendlyName = FriendlyName(renewal);
                    File.WriteAllBytes(pfxFileInfo.FullName, tempPfx.Export(X509ContentType.Pfx, renewal.PfxPassword));
                    pfxFileInfo.Refresh();
                }
            }

            // Recreate X509Certificate2 with correct flags for Store/Install
            return(new CertificateInfo()
            {
                Certificate = ReadForUse(pfxFileInfo, renewal.PfxPassword),
                PfxFile = pfxFileInfo
            });
        }
        /// <summary>
        /// Exports the specified stream and password to a pkcs12 encrypted file.
        /// </summary>
        /// <remarks>
        /// Exports the specified stream and password to a pkcs12 encrypted file.
        /// </remarks>
        /// <param name="stream">The output stream.</param>
        /// <param name="password">The password to use to lock the private keys.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <para><paramref name="stream"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="password"/> is <c>null</c>.</para>
        /// </exception>
        /// <exception cref="System.IO.IOException">
        /// An error occurred while writing to the stream.
        /// </exception>
        public void Export(System.IO.Stream stream, string password)
        {
            if (stream == null)
            {
                throw new System.ArgumentNullException(nameof(stream));
            }

            if (password == null)
            {
                throw new System.ArgumentNullException(nameof(password));
            }

            Org.BouncyCastle.Pkcs.Pkcs12Store store = new Org.BouncyCastle.Pkcs.Pkcs12Store();
            foreach (Org.BouncyCastle.X509.X509Certificate certificate in certs)
            {
                if (keys.ContainsKey(certificate))
                {
                    continue;
                }

                string alias = GetCommonName(certificate);

                if (alias == null)
                {
                    continue;
                }

                Org.BouncyCastle.Pkcs.X509CertificateEntry entry =
                    new Org.BouncyCastle.Pkcs.X509CertificateEntry(certificate);

                store.SetCertificateEntry(alias, entry);
            }

            foreach (
                System.Collections.Generic.KeyValuePair <
                    Org.BouncyCastle.X509.X509Certificate,
                    Org.BouncyCastle.Crypto.AsymmetricKeyParameter
                    > kvp in keys)
            {
                string alias = GetCommonName(kvp.Key);

                if (alias == null)
                {
                    continue;
                }

                Org.BouncyCastle.Pkcs.AsymmetricKeyEntry entry =
                    new Org.BouncyCastle.Pkcs.AsymmetricKeyEntry(kvp.Value);

                Org.BouncyCastle.Pkcs.X509CertificateEntry cert =
                    new Org.BouncyCastle.Pkcs.X509CertificateEntry(kvp.Key);

                System.Collections.Generic.List <Org.BouncyCastle.Pkcs.X509CertificateEntry> chain =
                    new System.Collections.Generic.List <Org.BouncyCastle.Pkcs.X509CertificateEntry>();

                chain.Add(cert);

                store.SetKeyEntry(alias, entry, chain.ToArray());
            }

            store.Save(stream, password.ToCharArray(), new Org.BouncyCastle.Security.SecureRandom());
        }
Beispiel #7
0
        private void button1_Click(object sender, EventArgs e)
        {
            string signatureAlgorithm = algtxt.Text;
            var    rsaGenerator       = new RsaKeyPairGenerator();
            var    randomGenerator    = new CryptoApiRandomGenerator();
            var    secureRandom       = new SecureRandom(randomGenerator);
            var    keyParameters      = new KeyGenerationParameters(secureRandom, 1024);

            rsaGenerator.Init(keyParameters);
            var keyPair    = rsaGenerator.GenerateKeyPair();
            var attributes = new System.Collections.Hashtable();

            attributes[X509Name.E]  = emailtxt.Text;  //设置dn信息的邮箱地址
            attributes[X509Name.CN] = towhomtxt.Text; //设置证书的用户,也就是颁发给谁
            attributes[X509Name.O]  = Issuertxt.Text; //设置证书的办法者
            attributes[X509Name.C]  = "Zh";           //证书的语言
            var ordering = new System.Collections.ArrayList();

            ordering.Add(X509Name.E);
            ordering.Add(X509Name.CN);
            ordering.Add(X509Name.O);
            ordering.Add(X509Name.C);
            var generater = new X509V3CertificateGenerator();

            //设置证书序列化号
            generater.SetSerialNumber(BigInteger.ProbablePrime(120, new Random()));
            //设置颁发者dn信息
            generater.SetIssuerDN(new X509Name(ordering, attributes));
            //设置证书生效时间
            generater.SetNotBefore(DateTime.Today.Subtract(new TimeSpan(1, 0, 0, 0)));
            //设置证书失效时间
            generater.SetNotAfter(DateTime.Today.AddDays(365));
            //设置接受者dn信息
            generater.SetSubjectDN(new X509Name(ordering, attributes));
            //设置证书的公钥
            generater.SetPublicKey(keyPair.Public);
            //设置证书的加密算法
            generater.SetSignatureAlgorithm(signatureAlgorithm);
            generater.AddExtension(X509Extensions.BasicConstraints,
                                   true,
                                   new BasicConstraints(false));
            generater.AddExtension(X509Extensions.AuthorityKeyIdentifier,
                                   true,
                                   new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public)));
            // Key usage: Client authentication
            generater.AddExtension(X509Extensions.ExtendedKeyUsage.Id,
                                   false,
                                   new ExtendedKeyUsage(new System.Collections.ArrayList()
            {
                new DerObjectIdentifier("1.3.6.1.5.5.7.3.2")
            }));

            Castle = generater.Generate(keyPair.Private);
            var    store        = new Org.BouncyCastle.Pkcs.Pkcs12Store();
            string friendlyname = Castle.SubjectDN.ToString();
            var    ccentry      = new Org.BouncyCastle.Pkcs.X509CertificateEntry(Castle);

            store.SetCertificateEntry(friendlyname, ccentry);
            store.SetKeyEntry(friendlyname, new Org.BouncyCastle.Pkcs.AsymmetricKeyEntry(keyPair.Private), new[] { ccentry });

            certificate.Text = "-----BEGIN CERTIFICATE-----\r\n" + Convert.ToBase64String(Castle.GetEncoded()) + "\r\n-----END CERTIFICATE-----";

            string password = pswtxt.Text;

            Castlekey = keyPair.Private;
            var stream = new MemoryStream();

            store.Save(stream, password.ToCharArray(), secureRandom);
            nametxt.Text = Castle.IssuerDN.ToString();
            TextWriter textWriter = new StringWriter();
            PemWriter  pemWriter  = new PemWriter(textWriter);

            pemWriter.WriteObject(Castle.GetPublicKey());
            pemWriter.Writer.Flush();
            pubtxt.Text = textWriter.ToString();
            SaveFileDialog output = new SaveFileDialog();

            output.Filter           = "pfx file|*.pfx";
            output.RestoreDirectory = true;
            output.InitialDirectory = Environment.CurrentDirectory;
            output.FilterIndex      = 1;
            if (output.ShowDialog() == DialogResult.OK)
            {
                File.WriteAllBytes(output.FileName, stream.ToArray());
            }
            else
            {
                MessageBox.Show("pfx证书不导出!");
            }
            output.Filter = "cer file|*.cer";
            if (output.ShowDialog() == DialogResult.OK)
            {
                File.WriteAllText(output.FileName, certificate.Text);
            }
            else
            {
                MessageBox.Show("cer证书没导出!");
            }
        }