Пример #1
0
        // https://stackoverflow.com/questions/13806299/how-to-create-a-self-signed-certificate-using-c
        static void MakeCert()
        {
            using (System.Security.Cryptography.ECDsa ecdsa = System.Security.Cryptography.ECDsa.Create())  // generate asymmetric key pair
            {
                System.Security.Cryptography.X509Certificates.CertificateRequest req =
                    new System.Security.Cryptography.X509Certificates.CertificateRequest("cn=foobar", ecdsa
                                                                                         , System.Security.Cryptography.HashAlgorithmName.SHA512
                                                                                         );

                using (System.Security.Cryptography.X509Certificates.X509Certificate2 cert =
                           req.CreateSelfSigned(System.DateTimeOffset.Now, System.DateTimeOffset.Now.AddYears(5)
                                                ))
                {
                    // Create PFX (PKCS #12) with private key
                    System.IO.File.WriteAllBytes("d:\\mycert.pfx", cert.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pfx));

                    // Create Base 64 encoded CER (public key only)
                    System.IO.File.WriteAllText("d:\\mycert.cer",
                                                "-----BEGIN CERTIFICATE-----\r\n"
                                                + System.Convert.ToBase64String(
                                                    cert.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert)
                                                    , System.Base64FormattingOptions.InsertLineBreaks
                                                    )
                                                + "\r\n-----END CERTIFICATE-----");
                } // End Using cert
            }     // End Using ecdsa
        }         // End Sub MakeCert
Пример #2
0
        /// <summary>
        /// Save a cert for use with encryption
        /// </summary>
        public Task SaveCertificate(string certname, string password, System.Security.Cryptography.X509Certificates.X509Certificate2 certificate)
        {
            var path = Path.Combine(Directory.GetCurrentDirectory(), certname);

            File.WriteAllBytes(path, certificate.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pfx, password));
            return(Task.CompletedTask);
        }
Пример #3
0
        public static void ExportPfx(X509Certificate2 certificate, string outputPfxFile, string password)
        {
            // This password is the one attached to the PFX file. Use 'null' for no password.
            var bytes = certificate.Export(X509ContentType.Pfx, password);

            File.WriteAllBytes(outputPfxFile, bytes);
        }
Пример #4
0
        private static void WriteCertificate(X509Certificate2 certificate, string outputFileName)
        {
            // This password is the one attached to the PFX file. Use 'null' for no password.
            const string password = "******";
            var          bytes    = certificate.Export(X509ContentType.Pfx, password);

            File.WriteAllBytes(outputFileName, bytes);
        }
Пример #5
0
        }     // End Sub Create

        private static void WithMsPfx(byte[] pfxBytes, string fileName, string password)
        {
            System.Security.Cryptography.X509Certificates.X509Certificate2 convertedCertificate =
                new System.Security.Cryptography.X509Certificates.X509Certificate2(pfxBytes,
                                                                                   "", // PW
                                                                                   System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.PersistKeySet | System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable);

            byte[] bytes = convertedCertificate.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pfx, password);
            System.IO.File.WriteAllBytes(fileName, bytes);
        } // End Sub WithMsPfx
Пример #6
0
        public static PkiCertificate From(BclCertificate bclCert)
        {
            var derEncoding = System.Security.Cryptography.X509Certificates.X509ContentType.Cert;
            var der         = bclCert.Export(derEncoding);

            return(new PkiCertificate
            {
                NativeCertificate = new X509CertificateParser().ReadCertificate(der),
            });
        }
Пример #7
0
        public override void ExportArchive(PrivateKey pk, IEnumerable <Crt> certs, ArchiveFormat fmt, Stream target, string password)
        {
            var rsaPk = pk as RsaPrivateKey;

            if (rsaPk == null)
            {
                throw new NotSupportedException("unsupported private key type");
            }

            if (fmt == ArchiveFormat.PKCS12)
            {
                var bcCerts = certs.Select(x =>
                                           new X509CertificateEntry(FromCertPem(x.Pem))).ToArray();
                var bcPk = FromPrivatePem(rsaPk.Pem);

                var pfx = new Pkcs12Store();
                //pfx.SetCertificateEntry(bcCerts[0].Certificate.ToString(), bcCerts[0]);
                //pfx.SetKeyEntry(bcCerts[0].Certificate.ToString(),
                pfx.SetCertificateEntry(string.Empty, bcCerts[0]);
                pfx.SetKeyEntry(string.Empty,
                                new AsymmetricKeyEntry(bcPk.Private), new[] { bcCerts[0] });

                for (int i = 1; i < bcCerts.Length; ++i)
                {
                    //pfx.SetCertificateEntry(bcCerts[i].Certificate.SubjectDN.ToString(),
                    pfx.SetCertificateEntry(i.ToString(), bcCerts[i]);
                }

                // It used to be pretty straight forward to export this...
                //pfx.Save(target, password?.ToCharArray(), new SecureRandom());

                // ...unfortunately, BC won't let us export the Pkcs12 archive
                // without assigning a FriendlyName, so we have to export and
                // then re-import it, clear the FriendlyName, then return that
                // YUCK!
                using (var tmp = new MemoryStream())
                {
                    pfx.Save(tmp, null, new SecureRandom());
                    var c = new System.Security.Cryptography.X509Certificates.X509Certificate2();
                    c.Import(tmp.ToArray(), string.Empty,
                             System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.PersistKeySet |
                             System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable);

                    // Clear the FriendlyName
                    c.FriendlyName = null;
                    var bytes = c.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs12, password);
                    target.Write(bytes, 0, bytes.Length);
                }
            }
            else
            {
                throw new NotSupportedException("unsupported archive format");
            }
        }
Пример #8
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
Пример #9
0
        static void Main(string[] args)
        {
            var tempPath = System.IO.Path.GetTempPath();
            var certOut  = tempPath + "cert.crt";
            var certPass = "******";

            var base64Cert = "base64 encoded string";
            var cert       = new System.Security.Cryptography.X509Certificates.X509Certificate2(Convert.FromBase64String(base64Cert), certPass, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.PersistKeySet);


            if (cert != null)
            {
                var b = new System.IO.BinaryWriter(System.IO.File.Open(certOut, System.IO.FileMode.Create));

                var binCert = cert.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert, certPass);
                b.Write(binCert);
            }
        }
Пример #10
0
        public static void GetPublicKey(string pfxLocation, string password)
        {
            // I'm trying to mimic OpenSSL's capability to extract the Private Key from a PFX Bundle into it's own file.
            // I can get the Public Key OK with the following code:

            // Load your certificate from file
            System.Security.Cryptography.X509Certificates.X509Certificate2 certificate =
                new System.Security.Cryptography.X509Certificates.X509Certificate2(pfxLocation, password
                                                                                   , System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable
                                                                                   | System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.PersistKeySet);
            // Public Key;
            System.Text.StringBuilder publicBuilder = new System.Text.StringBuilder();
            publicBuilder.AppendLine("-----BEGIN CERTIFICATE-----");
            publicBuilder.AppendLine(System.Convert.ToBase64String(certificate.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert)
                                                                   , System.Base64FormattingOptions.InsertLineBreaks));

            publicBuilder.AppendLine("-----END CERTIFICATE-----");
            string foo = publicBuilder.ToString();
        }
Пример #11
0
        } // End Function ReadPrivateKey

        public static void TestSignature()
        {
            System.Console.WriteLine("Attempting to load cert...");
            System.Security.Cryptography.X509Certificates.X509Certificate2 thisCert = null; // LoadCertificate();

            System.Console.WriteLine(thisCert.IssuerName.Name);
            System.Console.WriteLine("Signing the text - Mary had a nuclear bomb");

            byte[] pkcs12Bytes = thisCert.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs12, "dummy");
            Org.BouncyCastle.Pkcs.Pkcs12Store pkcs12 = new Org.BouncyCastle.Pkcs.Pkcs12StoreBuilder().Build();

            pkcs12.Load(new System.IO.MemoryStream(pkcs12Bytes, false), "dummy".ToCharArray());

            Org.BouncyCastle.Crypto.Parameters.ECPrivateKeyParameters privKey = null;
            foreach (string alias in pkcs12.Aliases)
            {
                if (pkcs12.IsKeyEntry(alias))
                {
                    privKey = (Org.BouncyCastle.Crypto.Parameters.ECPrivateKeyParameters)pkcs12.GetKey(alias).Key;
                    break;
                } // End if (pkcs12.IsKeyEntry(alias))
            }     // Next alias

            string signature = SignData("Mary had a nuclear bomb", privKey);

            System.Console.WriteLine("Signature: " + signature);

            System.Console.WriteLine("Verifying Signature");

            Org.BouncyCastle.X509.X509Certificate bcCert = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(thisCert);
            if (VerifySignature((Org.BouncyCastle.Crypto.Parameters.ECPublicKeyParameters)bcCert.GetPublicKey(), signature, "Mary had a nuclear bomb."))
            {
                System.Console.WriteLine("Valid Signature!");
            }
            else
            {
                System.Console.WriteLine("Signature NOT valid!");
            }
        } // End Sub TestSignature
Пример #12
0
 private static void WriteCertificate(X509Certificate2 certificate, string outputFileName)
 {
     // This password is the one attached to the PFX file. Use 'null' for no password.
     const string password = "******";
     var bytes = certificate.Export(X509ContentType.Pfx, password);
     File.WriteAllBytes(outputFileName, bytes);
 }
        public static byte[] GenerateRootCertificate(string subjectName, string password, out string pemValue)
        {

            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random = new SecureRandom(randomGenerator);

            var kpgen = new RsaKeyPairGenerator();
            kpgen.Init(new KeyGenerationParameters(random, 2048)); //new SecureRandom(new CryptoApiRandomGenerator()), 2048));
            var subjectKeyPair = kpgen.GenerateKeyPair();

            var gen = new X509V3CertificateGenerator();

            var certName = new X509Name("CN=" + subjectName);
            BigInteger serialNo = BigInteger.ValueOf(4); //BigInteger.ProbablePrime(120, random);
            gen.SetSerialNumber(serialNo);

            gen.SetSubjectDN(certName);
            gen.SetIssuerDN(certName);

            gen.SetNotAfter(DateTime.Now.AddYears(100));
            gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0)));
            gen.SetSignatureAlgorithm("SHA256WithRSA"); //("MD5WithRSA");
            gen.SetPublicKey(subjectKeyPair.Public);

            //gen.AddExtension(
            //    X509Extensions.SubjectKeyIdentifier,
            //    false,
            //    new SubjectKeyIdentifierStructure(kp.Public)
            //    );

            //gen.AddExtension(
            //    X509Extensions.AuthorityKeyIdentifier.Id,
            //    false,
            //    new AuthorityKeyIdentifier(
            //        SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public),
            //        new GeneralNames(new GeneralName(certName)),
            //        serialNo));

            var certificate = gen.Generate(subjectKeyPair.Private, random);

            var privateKeyPem = new StringBuilder();
            var privateKeyPemWriter = new PemWriter(new StringWriter(privateKeyPem));

            privateKeyPemWriter.WriteObject(certificate);
            privateKeyPemWriter.WriteObject(subjectKeyPair.Private);
            privateKeyPemWriter.Writer.Flush();
            pemValue = privateKeyPem.ToString();
            System.IO.File.WriteAllText(@"C:\_rootCa.pem", pemValue);

            //var certBytes = DotNetUtilities.ToX509Certificate(certificate).Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs12, password);

            //var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());

            //RSA rsaPriv = DotNetUtilities.ToRSA(subjectKeyPair.Private as RsaPrivateCrtKeyParameters);

            //
            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);
            var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());
            var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded());
            if (seq.Count != 9)
            {
                throw new PemException("malformed sequence in RSA private key");
            }

            var rsa = new RsaPrivateKeyStructure(seq);
            RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            //-------------

            //RsaPrivateCrtKeyParameters rsaparams = (RsaPrivateCrtKeyParameters)subjectKeyPair.Private;
            RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(rsaparams);
            CspParameters cspParameters = new CspParameters();
            cspParameters.KeyContainerName = Guid.NewGuid().ToString(); // "MyKeyContainer";
            RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(2048, cspParameters);
            rsaKey.ImportParameters(rsaParameters);

            // ------------

            x509.PrivateKey = rsaKey; // DotNetUtilities.ToRSA(rsaparams);
            //


            var x509Bytes = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert, password);
            System.IO.File.WriteAllBytes(@"C:\_rootCa.cer", x509Bytes);

            var x509Bytes2 = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pfx, password);
            System.IO.File.WriteAllBytes(@"C:\_rootCa.pfx", x509Bytes2);

            return x509Bytes;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <remarks>Based on <see cref="http://www.fkollmann.de/v2/post/Creating-certificates-using-BouncyCastle.aspx"/></remarks>
        /// <param name="subjectName"></param>
        /// <returns></returns>
        public static byte[] GenerateCertificate(string subjectName, byte[] issuingCertificate, string issuingCertificatePassword, out string password)
        {

            AsymmetricKeyParameter caPrivateKey;
            var caCert = ReadCertificateFromBytes(issuingCertificate, issuingCertificatePassword, out caPrivateKey);

            var caAuth = new AuthorityKeyIdentifierStructure(caCert);
            var authKeyId = new AuthorityKeyIdentifier(caAuth.GetKeyIdentifier());

            // ---------------------------

            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random = new SecureRandom(randomGenerator);

            var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-()#$%^&@+=!";
            var rnd = new Random();
            var result = new string(
                Enumerable.Repeat(chars, 15)
                          .Select(s => s[rnd.Next(s.Length)])
                          .ToArray());
            password = result;

            var gen = new X509V3CertificateGenerator();
            var certName = new X509Name("CN=" + subjectName);
            var serialNo = BigInteger.ProbablePrime(120, random);
            gen.SetSerialNumber(serialNo);
            gen.SetSubjectDN(certName);
            gen.SetIssuerDN(caCert.IssuerDN);

            // gen.SetIssuerUniqueID(caCert.IssuerUniqueID.GetBytes())

            gen.SetNotAfter(DateTime.Now.AddYears(100));
            gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0)));
            gen.SetSignatureAlgorithm("SHA256WithRSA"); //("MD5WithRSA");

            var kpgen = new RsaKeyPairGenerator();
            kpgen.Init(new KeyGenerationParameters(random, 2048)); // new SecureRandom(new CryptoApiRandomGenerator()), 2048));
            var subjectKeyPair = kpgen.GenerateKeyPair();
            gen.SetPublicKey(subjectKeyPair.Public);

            //gen.AddExtension(
            //   X509Extensions.AuthorityKeyIdentifier,
            //   false,
            //   authKeyId);

            //gen.AddExtension(
            //    X509Extensions.SubjectKeyIdentifier,
            //    false,
            //    new SubjectKeyIdentifierStructure(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 KeyPurposeID[] { KeyPurposeID.IdKPClientAuth, KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPCodeSigning }));

            //1.3.6.1.5.5.7.3.1 = server authentication
            //1.3.6.1.5.5.7.3.2 = client authentication
            //1.3.6.1.5.5.7.3.3 = code signing

            var certificate = gen.Generate(caPrivateKey);

            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);

            // merge into X509Certificate2
            var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());
            var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded());
            if (seq.Count != 9)
            {
                throw new PemException("malformed sequence in RSA private key");
            }

            var rsa = new RsaPrivateKeyStructure(seq);
            RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            //-------------

            //RsaPrivateCrtKeyParameters rsaparams = (RsaPrivateCrtKeyParameters)subjectKeyPair.Private;
            RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(rsaparams);
            CspParameters cspParameters = new CspParameters();
            cspParameters.KeyContainerName = Guid.NewGuid().ToString(); // "MyKeyContainer";
            RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(2048, cspParameters);
            rsaKey.ImportParameters(rsaParameters);

            // ------------

            x509.PrivateKey = rsaKey; // DotNetUtilities.ToRSA(rsaparams);


            //var certBytes = DotNetUtilities.ToX509Certificate(certificate).Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pfx, password);

            //var x5092 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certBytes, password);
            //var rsaPriv = DotNetUtilities.ToRSA(subjectKeyPair.Private as RsaPrivateCrtKeyParameters);
            //x509.PrivateKey = rsaPriv;

            var x509Bytes = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert);
            System.IO.File.WriteAllBytes(@"C:\mycertx509x.cer", x509Bytes);

            var x509Bytes2 = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs12, password);

            System.IO.File.WriteAllBytes(@"C:\mycertx509x.pfx", x509Bytes2);
            System.IO.File.WriteAllText(@"C:\mycertx509x_pass.txt", password);

            //Utility.AddCertToStore(x509, System.Security.Cryptography.X509Certificates.StoreName.My, System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine);

            return x509Bytes2;
        }
Пример #15
0
        public static void GenerateRootCertificate(string subjectName, long serialNumber, DateTime expireOn, bool isCertificateAuthority, out string thumbprint, out string pemPrivateKey, out string pemPublicCert, out byte[] publicCert, out byte[] pkcs12Data, out string password)
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            var kpgen = new RsaKeyPairGenerator();

            kpgen.Init(new KeyGenerationParameters(random, 2048)); //new SecureRandom(new CryptoApiRandomGenerator()), 2048));
            var subjectKeyPair = kpgen.GenerateKeyPair();

            var gen = new X509V3CertificateGenerator();

            var certName = new X509Name("CN=" + subjectName);

            BigInteger serialNo;

            if (serialNumber == 0)
            {
                serialNo = BigInteger.ProbablePrime(120, random);
            }
            else
            {
                serialNo = BigInteger.ValueOf(serialNumber);
            }

            gen.SetSerialNumber(serialNo);
            gen.SetSubjectDN(certName);
            gen.SetIssuerDN(certName);

            gen.SetNotAfter(expireOn);
            gen.SetNotBefore(DateTime.Now.Date);
            gen.SetSignatureAlgorithm("SHA256WithRSA"); //("MD5WithRSA");
            gen.SetPublicKey(subjectKeyPair.Public);


            gen.AddExtension(
                X509Extensions.BasicConstraints.Id,
                true,
                new BasicConstraints(isCertificateAuthority));

            var certificate = gen.Generate(subjectKeyPair.Private, random);

            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);
            var            x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());
            var            seq  = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded());

            if (seq.Count != 9)
            {
                throw new PemException("Malformed sequence in RSA private key.");
            }

            var rsa = new RsaPrivateKeyStructure(seq);
            RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(rsaparams);
            CspParameters cspParameters = new CspParameters();

            cspParameters.KeyContainerName = Guid.NewGuid().ToString(); // "MyKeyContainer";
            RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(2048, cspParameters);

            rsaKey.ImportParameters(rsaParameters);

            x509.PrivateKey = rsaKey; // DotNetUtilities.ToRSA(rsaparams);

            // Generating Random Numbers
            var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-()#$%^&@+=!";
            var rnd   = new Random();

            password = new string(
                Enumerable.Repeat(chars, 15)
                .Select(s => s[rnd.Next(s.Length)])
                .ToArray());
            thumbprint = x509.Thumbprint.ToLower();
            publicCert = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert);

            var privateKeyPem       = new StringBuilder();
            var privateKeyPemWriter = new PemWriter(new StringWriter(privateKeyPem));

            privateKeyPemWriter.WriteObject(certificate);
            privateKeyPemWriter.WriteObject(subjectKeyPair.Private);
            privateKeyPemWriter.Writer.Flush();
            pemPrivateKey = privateKeyPem.ToString();

            var publicKeyPem       = new StringBuilder();
            var utf8WithoutBom     = new System.Text.UTF8Encoding(false);
            var publicKeyPemWriter = new PemWriter(new StringWriterWithEncoding(publicKeyPem, utf8WithoutBom));

            publicKeyPemWriter.WriteObject(certificate);
            publicKeyPemWriter.Writer.Flush();
            pemPublicCert = publicKeyPem.ToString();
            pemPublicCert = pemPublicCert.Replace(Environment.NewLine, "\n"); //only use newline and not returns

            pkcs12Data = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pfx, password);
        }
Пример #16
0
 public CertHackStore(System.Security.Cryptography.X509Certificates.X509Certificate2 cert)
 {
     this.m_isNotWindows = !System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows);
     this.m_certificate  = cert;
     this.m_bkcs12Bytes  = cert.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs12);
 } // End Constructor
        public static void GenerateRootCertificate(string subjectName, long serialNumber, DateTime expireOn, bool isCertificateAuthority, out string thumbprint, out string pemPrivateKey, out string pemPublicCert, out byte[] publicCert, out byte[] pkcs12Data, out string password)
        {

            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random = new SecureRandom(randomGenerator);

            var kpgen = new RsaKeyPairGenerator();
            kpgen.Init(new KeyGenerationParameters(random, 2048)); //new SecureRandom(new CryptoApiRandomGenerator()), 2048));
            var subjectKeyPair = kpgen.GenerateKeyPair();

            var gen = new X509V3CertificateGenerator();

            var certName = new X509Name("CN=" + subjectName);

            BigInteger serialNo;
            if (serialNumber == 0)
            {
                serialNo = BigInteger.ProbablePrime(120, random);
            }
            else
            {
                serialNo = BigInteger.ValueOf(serialNumber);
            }

            gen.SetSerialNumber(serialNo);
            gen.SetSubjectDN(certName);
            gen.SetIssuerDN(certName);

            gen.SetNotAfter(expireOn);
            gen.SetNotBefore(DateTime.Now.Date);
            gen.SetSignatureAlgorithm("SHA256WithRSA"); //("MD5WithRSA");
            gen.SetPublicKey(subjectKeyPair.Public);


            gen.AddExtension(
                X509Extensions.BasicConstraints.Id,
                true,
                new BasicConstraints(isCertificateAuthority));


            //// NOT WORKING... NOT PASSING CERTIFICATE ISSUING ALLOWED
            //if (isCertificateAuthority)
            //{
            //    gen.AddExtension(
            //         X509Extensions.BasicConstraints.,
            //         true,
            //         new BasicConstraints(isCertificateAuthority));
            //}



            var certificate = gen.Generate(subjectKeyPair.Private, random);

            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);
            var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());
            var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded());
            if (seq.Count != 9)
            {
                throw new PemException("Malformed sequence in RSA private key.");
            }

            var rsa = new RsaPrivateKeyStructure(seq);
            RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(rsaparams);
            CspParameters cspParameters = new CspParameters();
            cspParameters.KeyContainerName = Guid.NewGuid().ToString(); // "MyKeyContainer";
            RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(2048, cspParameters);
            rsaKey.ImportParameters(rsaParameters);

            x509.PrivateKey = rsaKey; // DotNetUtilities.ToRSA(rsaparams);

            // Generating Random Numbers
            var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-()#$%^&@+=!";
            var rnd = new Random();

            password = new string(
                Enumerable.Repeat(chars, 32)
                          .Select(s => s[rnd.Next(s.Length)])
                          .ToArray());
            thumbprint = x509.Thumbprint.ToLower();
            publicCert = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert);

            var privateKeyPem = new StringBuilder();
            var privateKeyPemWriter = new PemWriter(new StringWriter(privateKeyPem));
            privateKeyPemWriter.WriteObject(certificate);
            privateKeyPemWriter.WriteObject(subjectKeyPair.Private);
            privateKeyPemWriter.Writer.Flush();
            pemPrivateKey = privateKeyPem.ToString();

            var publicKeyPem = new StringBuilder();
            var utf8WithoutBom = new System.Text.UTF8Encoding(false);
            var publicKeyPemWriter = new PemWriter(new StringWriterWithEncoding(publicKeyPem, utf8WithoutBom));
            publicKeyPemWriter.WriteObject(certificate);
            publicKeyPemWriter.Writer.Flush();
            pemPublicCert = publicKeyPem.ToString();
            pemPublicCert = pemPublicCert.Replace(Environment.NewLine, "\n"); //only use newline and not returns

            pkcs12Data = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pfx, password);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <remarks>Based on <see cref="http://www.fkollmann.de/v2/post/Creating-certificates-using-BouncyCastle.aspx"/></remarks>
        /// <param name="subjectName"></param>
        /// <returns></returns>
        public static void z_dep_GenerateCertificate(string subjectName, long serialNumber, DateTime expireOn, System.Security.Cryptography.X509Certificates.X509Certificate2 issuingCertificate, out string thumbprint, out string pemPrivateKey, out string pemPublicCert, out byte[] publicCert, out byte[] pkcs12Data, out string password)
        {

            AsymmetricKeyParameter caPrivateKey;
            var caCert = ReadCertificateFromX509Certificate2(issuingCertificate, out caPrivateKey);

            //var caAuth = new AuthorityKeyIdentifierStructure(caCert);
            //var authKeyId = new AuthorityKeyIdentifier(caAuth.GetKeyIdentifier());

            // ---------------------------

            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random = new SecureRandom(randomGenerator);

            var gen = new X509V3CertificateGenerator();

            // var certName = new X509Name("CN=" + subjectName);

            var list = new Dictionary<string, string>();
            AddItems(list, "CN", subjectName);
            AddItems(list, "O", "CompliaShield");
            AddItems(list, "OU", "CompliaShield");
            //var simpleCertName = GetItemString(list);
            //var certNameLight = new X509Name(simpleCertName);

            list.Add("L", "Boulder");
            list.Add("ST", "Colorado");
            list.Add("C", "US");
            var subjectFull = GetItemString(list);
            var certName = new X509Name(subjectFull);


            BigInteger serialNo;
            if (serialNumber == 0)
            {
                serialNo = BigInteger.ProbablePrime(120, random);
            }
            else
            {
                serialNo = BigInteger.ValueOf(serialNumber);
            }
            gen.SetSerialNumber(serialNo);
            gen.SetSubjectDN(certName);

            gen.SetIssuerDN(caCert.IssuerDN);

            var issuerPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(caCert.GetPublicKey());
            var issuerGeneralNames = new GeneralNames(new GeneralName(caCert.IssuerDN));
            var issuerSerialNumber = caCert.SerialNumber;

            var authorityKeyIdentifier = new AuthorityKeyIdentifier(issuerPublicKeyInfo, issuerGeneralNames, issuerSerialNumber);
            gen.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, true, authorityKeyIdentifier);

            // gen.SetIssuerUniqueID(caCert.IssuerUniqueID.GetBytes())

            gen.SetNotAfter(expireOn);
            gen.SetNotBefore(DateTime.Now.AddHours(-2));
            gen.SetSignatureAlgorithm("SHA256WithRSA"); //("MD5WithRSA");

            var kpgen = new RsaKeyPairGenerator();
            kpgen.Init(new KeyGenerationParameters(random, 2048)); // new SecureRandom(new CryptoApiRandomGenerator()), 2048));
            var subjectKeyPair = kpgen.GenerateKeyPair();
            gen.SetPublicKey(subjectKeyPair.Public);

            gen.AddExtension(
                X509Extensions.ExtendedKeyUsage.Id,
                false,
                new ExtendedKeyUsage(new KeyPurposeID[] { KeyPurposeID.IdKPClientAuth, KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPCodeSigning }));

            //1.3.6.1.5.5.7.3.1 = server authentication
            //1.3.6.1.5.5.7.3.2 = client authentication
            //1.3.6.1.5.5.7.3.3 = code signing

            var certificate = gen.Generate(caPrivateKey);

            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);

            // merge into X509Certificate2
            var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());
            var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded());
            if (seq.Count != 9)
            {
                throw new PemException("Malformed sequence in RSA private key.");
            }

            var rsa = new RsaPrivateKeyStructure(seq);
            RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            //-------------

            //RsaPrivateCrtKeyParameters rsaparams = (RsaPrivateCrtKeyParameters)subjectKeyPair.Private;
            RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(rsaparams);
            CspParameters cspParameters = new CspParameters();
            cspParameters.KeyContainerName = Guid.NewGuid().ToString(); // "MyKeyContainer";
            RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(2048, cspParameters);
            rsaKey.ImportParameters(rsaParameters);

            // ------------

            x509.PrivateKey = rsaKey; // DotNetUtilities.ToRSA(rsaparams);

            // Generating Random Numbers
            var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-()#$%^&@+=!{}[]*.,";
            var rnd = new Random();

            password = new string(
                Enumerable.Repeat(chars, 32)
                          .Select(s => s[rnd.Next(s.Length)])
                          .ToArray());
            thumbprint = x509.Thumbprint.ToLower();
            publicCert = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert);

            var privateKeyPem = new StringBuilder();
            var privateKeyPemWriter = new PemWriter(new StringWriter(privateKeyPem));
            privateKeyPemWriter.WriteObject(certificate);
            privateKeyPemWriter.WriteObject(subjectKeyPair.Private);
            privateKeyPemWriter.Writer.Flush();
            pemPrivateKey = privateKeyPem.ToString();

            var publicKeyPem = new StringBuilder();
            var utf8WithoutBom = new System.Text.UTF8Encoding(false);
            var publicKeyPemWriter = new PemWriter(new StringWriterWithEncoding(publicKeyPem, utf8WithoutBom));
            publicKeyPemWriter.WriteObject(certificate);
            publicKeyPemWriter.Writer.Flush();
            pemPublicCert = publicKeyPem.ToString();
            pemPublicCert = pemPublicCert.Replace(Environment.NewLine, "\n"); //only use newline and not returns

            pkcs12Data = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pfx, password);

        }
Пример #19
0
        public static X509Certificate2 IssueCertificate(
            string basename,
            string password,
            DistinguishedName dn,
            CertificateType certtype,
            DateTime notBefore,
            DateTime notAfter)
        {
            var certificateGenerator = new X509V3CertificateGenerator();
            var privateOutputPath    = "";
            var publicOutputPath     = "";

            /* Prepare output directories  */
            if (certtype == CertificateType.AuthorityCertificate)
            {
                privateOutputPath = AuthorityPrivateCertificatesPath;
                publicOutputPath  = AuthorityPublicCertificatesPath;
            }
            else if (certtype == CertificateType.ServerCertificate)
            {
                privateOutputPath = ServerPrivateCertificatesPath;
                publicOutputPath  = ServerPublicCertificatesPath;
            }
            else
            {
                privateOutputPath = UserPrivateCertificatesPath;
                publicOutputPath  = UserPublicCertificatesPath;
            }

            /* Certificate Asymmetric Keys */
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom             random          = new SecureRandom(randomGenerator);

            KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, 2048);
            RsaKeyPairGenerator     keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);

            AsymmetricCipherKeyPair subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            /* Certificate Serial Number */
            BigInteger serialNumber =
                BigIntegers.CreateRandomInRange(
                    BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            /* Certificate Date Constrains */
            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            /* Certificate Issuer and Subject DN */
            string issuerName = IssuerDN.ToString();

            if (certtype == CertificateType.AuthorityCertificate)
            {
                /* A Certification Authority is a self signed certificate */
                issuerName = dn.ToString();
            }

            certificateGenerator.SetSubjectDN(new X509Name(dn.ToString()));
            certificateGenerator.SetIssuerDN(new X509Name(issuerName));

            /* Certificate Alternative Names */
            if (dn.AlternativeNames != null && dn.AlternativeNames.Any())
            {
                var subjectAlternativeNamesExtension =
                    new DerSequence(
                        dn.AlternativeNames.Select(name => new GeneralName(GeneralName.DnsName, name))
                        .ToArray <Asn1Encodable> ());

                certificateGenerator.AddExtension(
                    X509Extensions.SubjectAlternativeName.Id, false, subjectAlternativeNamesExtension);
            }

            /* Certificate Keys Usage  */
            var keyUsageFlags = KeyUsage.KeyCertSign | KeyUsage.KeyEncipherment |
                                KeyUsage.DataEncipherment | KeyUsage.DigitalSignature;

            if (certtype == CertificateType.AuthorityCertificate || certtype == CertificateType.ServerCertificate)
            {
                keyUsageFlags |= KeyUsage.CrlSign | KeyUsage.NonRepudiation;
            }

            certificateGenerator.AddExtension(
                X509Extensions.KeyUsage.Id, false, new KeyUsage(keyUsageFlags));

            /* Certificate Extended Key Usages */
            if (certtype != CertificateType.AuthorityCertificate)
            {
                KeyPurposeID[] extendedUsages = null;

                if (certtype == CertificateType.ServerCertificate)
                {
                    extendedUsages = new KeyPurposeID[] {
                        KeyPurposeID.IdKPServerAuth,
                    };
                }
                else
                {
                    extendedUsages = new KeyPurposeID[] {
                        KeyPurposeID.IdKPClientAuth,
                        KeyPurposeID.IdKPEmailProtection,
                    };
                }

                certificateGenerator.AddExtension(
                    X509Extensions.ExtendedKeyUsage.Id, false, new ExtendedKeyUsage(extendedUsages));
            }

            /* Certificate Authority Key Identifier */
            /* A Certification Authority is a self signed certificate */
            AsymmetricCipherKeyPair issuerKeyPair = subjectKeyPair;;

            if (certtype != CertificateType.AuthorityCertificate)
            {
                issuerKeyPair = DotNetUtilities.GetKeyPair(IssuerCertificate.PrivateKey);
            }

            var issuerPKIFactory = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerKeyPair.Public);
            var generalNames     = new GeneralNames(
                new GeneralName(new X509Name(issuerName)));

            /* A Certification Authority is a self signed certificate */
            BigInteger issuerSerialNumber = serialNumber;

            if (certtype != CertificateType.AuthorityCertificate)
            {
                issuerSerialNumber = new BigInteger(IssuerCertificate.GetSerialNumber());
            }

            var authorityKIExtension =
                new AuthorityKeyIdentifier(
                    issuerPKIFactory, generalNames, issuerSerialNumber);

            certificateGenerator.AddExtension(
                X509Extensions.AuthorityKeyIdentifier.Id, false, authorityKIExtension);

            /* Certificate Subject Key Identifier */
            var subjectPKIFactory  = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public);
            var subjectKIExtension = new SubjectKeyIdentifier(subjectPKIFactory);

            certificateGenerator.AddExtension(
                X509Extensions.SubjectKeyIdentifier.Id, false, subjectKIExtension);

            /* Certificate Basic constrains */
            bool isCertificateAuthority = false;

            if (certtype == CertificateType.AuthorityCertificate)
            {
                isCertificateAuthority = true;
            }

            var basicConstrains = new BasicConstraints(isCertificateAuthority);

            certificateGenerator.AddExtension(
                X509Extensions.BasicConstraints.Id, true, basicConstrains);

            /* Generate BouncyCastle Certificate */
            ISignatureFactory signatureFactory = new Asn1SignatureFactory(
                "SHA512WITHRSA",
                issuerKeyPair.Private,
                random
                );

            /* Generate P12 Certificate Store and write to disk*/
            var store = new Pkcs12Store();

            var certificate      = certificateGenerator.Generate(signatureFactory);
            var certificateEntry = new X509CertificateEntry(certificate);
            var stream           = new MemoryStream();

            store.SetCertificateEntry(dn.ToString(), certificateEntry);
            store.SetKeyEntry(dn.ToString(), new AsymmetricKeyEntry(subjectKeyPair.Private), new [] { certificateEntry });
            store.Save(stream, password.ToCharArray(), random);

            File.WriteAllBytes(privateOutputPath + basename + ".p12", stream.ToArray());

            /* Convert to Microsoft X509Certificate2 and write to disk pfx and der files */
            var convertedCertificate =
                new X509Certificate2(stream.ToArray(),
                                     password,
                                     X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

            File.WriteAllBytes(privateOutputPath + basename + ".pfx", convertedCertificate.Export(X509ContentType.Pfx, password));
            File.WriteAllBytes(publicOutputPath + basename + ".crt", convertedCertificate.Export(X509ContentType.Cert, password));

            return(convertedCertificate);
        }
Пример #20
0
        /// <summary>
        ///
        /// </summary>
        /// <remarks>Based on <see cref="http://www.fkollmann.de/v2/post/Creating-certificates-using-BouncyCastle.aspx"/></remarks>
        /// <param name="subjectName"></param>
        /// <returns></returns>
        public static void GenerateCertificate(string subjectName, long serialNumber, DateTime expireOn, System.Security.Cryptography.X509Certificates.X509Certificate2 issuingCertificate, out string thumbprint, out string pemPrivateKey, out string pemPublicCert, out byte[] publicCert, out byte[] pkcs12Data, out string password)
        {
            AsymmetricKeyParameter caPrivateKey;
            var caCert = ReadCertificateFromX509Certificate2(issuingCertificate, out caPrivateKey);

            var caAuth    = new AuthorityKeyIdentifierStructure(caCert);
            var authKeyId = new AuthorityKeyIdentifier(caAuth.GetKeyIdentifier());

            // ---------------------------

            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            var gen = new X509V3CertificateGenerator();

            // var certName = new X509Name("CN=" + subjectName);

            var list = new Dictionary <string, string>();

            AddItems(list, "CN", subjectName);
            AddItems(list, "O", "JFM Concepts, LLC");
            AddItems(list, "OU", "VDP Web");
            //var simpleCertName = GetItemString(list);
            //var certNameLight = new X509Name(simpleCertName);

            list.Add("L", "Boulder");
            list.Add("ST", "Colorado");
            list.Add("C", "US");
            var subjectFull = GetItemString(list);
            var certName    = new X509Name(subjectFull);


            BigInteger serialNo;

            if (serialNumber == 0)
            {
                serialNo = BigInteger.ProbablePrime(120, random);
            }
            else
            {
                serialNo = BigInteger.ValueOf(serialNumber);
            }
            gen.SetSerialNumber(serialNo);
            gen.SetSubjectDN(certName);

            gen.SetIssuerDN(caCert.IssuerDN);

            var issuerPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(caCert.GetPublicKey());
            var issuerGeneralNames  = new GeneralNames(new GeneralName(caCert.IssuerDN));
            var issuerSerialNumber  = caCert.SerialNumber;

            var authorityKeyIdentifier = new AuthorityKeyIdentifier(issuerPublicKeyInfo, issuerGeneralNames, issuerSerialNumber);

            gen.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, true, authorityKeyIdentifier);

            // gen.SetIssuerUniqueID(caCert.IssuerUniqueID.GetBytes())

            gen.SetNotAfter(expireOn);
            gen.SetNotBefore(DateTime.Now.AddHours(-2));
            gen.SetSignatureAlgorithm("SHA256WithRSA"); //("MD5WithRSA");

            var kpgen = new RsaKeyPairGenerator();

            kpgen.Init(new KeyGenerationParameters(random, 2048)); // new SecureRandom(new CryptoApiRandomGenerator()), 2048));
            var subjectKeyPair = kpgen.GenerateKeyPair();

            gen.SetPublicKey(subjectKeyPair.Public);

            gen.AddExtension(
                X509Extensions.ExtendedKeyUsage.Id,
                false,
                new ExtendedKeyUsage(new KeyPurposeID[] { KeyPurposeID.IdKPClientAuth, KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPCodeSigning }));

            //1.3.6.1.5.5.7.3.1 = server authentication
            //1.3.6.1.5.5.7.3.2 = client authentication
            //1.3.6.1.5.5.7.3.3 = code signing

            var certificate = gen.Generate(caPrivateKey);

            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);

            // merge into X509Certificate2
            var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());
            var seq  = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded());

            if (seq.Count != 9)
            {
                throw new PemException("Malformed sequence in RSA private key.");
            }

            var rsa = new RsaPrivateKeyStructure(seq);
            RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            //-------------

            //RsaPrivateCrtKeyParameters rsaparams = (RsaPrivateCrtKeyParameters)subjectKeyPair.Private;
            RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(rsaparams);
            CspParameters cspParameters = new CspParameters();

            cspParameters.KeyContainerName = Guid.NewGuid().ToString(); // "MyKeyContainer";
            RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(2048, cspParameters);

            rsaKey.ImportParameters(rsaParameters);

            // ------------

            x509.PrivateKey = rsaKey; // DotNetUtilities.ToRSA(rsaparams);

            // Generating Random Numbers
            var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-()#$%^&@+=!";
            var rnd   = new Random();

            password = new string(
                Enumerable.Repeat(chars, 15)
                .Select(s => s[rnd.Next(s.Length)])
                .ToArray());
            thumbprint = x509.Thumbprint.ToLower();
            publicCert = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert);

            var privateKeyPem       = new StringBuilder();
            var privateKeyPemWriter = new PemWriter(new StringWriter(privateKeyPem));

            privateKeyPemWriter.WriteObject(certificate);
            privateKeyPemWriter.WriteObject(subjectKeyPair.Private);
            privateKeyPemWriter.Writer.Flush();
            pemPrivateKey = privateKeyPem.ToString();

            var publicKeyPem       = new StringBuilder();
            var utf8WithoutBom     = new System.Text.UTF8Encoding(false);
            var publicKeyPemWriter = new PemWriter(new StringWriterWithEncoding(publicKeyPem, utf8WithoutBom));

            publicKeyPemWriter.WriteObject(certificate);
            publicKeyPemWriter.Writer.Flush();
            pemPublicCert = publicKeyPem.ToString();
            pemPublicCert = pemPublicCert.Replace(Environment.NewLine, "\n"); //only use newline and not returns

            pkcs12Data = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pfx, password);
        }