public static X509Certificate2 IssueCert(string pathToPfxFile, string password, string commonName, out AsymmetricCipherKeyPair certificateSubjectKeyPair)
        {
            var issuerCertificate = new X509Certificate2(pathToPfxFile, password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

            if (!issuerCertificate.HasPrivateKey)
            {
                throw new InvalidOperationException("The authority's .pfx file does not have a private key.");
            }

            var keyUsages         = KeyUsage.DataEncipherment | KeyUsage.KeyEncipherment | KeyUsage.DigitalSignature;
            var extendedKeyUsages = new List <KeyPurposeID>(new[] { KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPClientAuth });

            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            certificateSubjectKeyPair = GenerateRsaKeyPair(random, 2048);
            var subjectSerialNumber    = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
            var subjectDn              = $"C=US,ST=NY,L=New York,STREET=123 Main St,[email protected],O=Sample Certs,OU=MegaCorp,CN={commonName}";
            var bcIssuerCertificate    = DotNetUtilities.FromX509Certificate(issuerCertificate);
            var issuerDn               = bcIssuerCertificate.SubjectDN.ToString();
            var issuerKeyPair          = DotNetUtilities.GetKeyPair(issuerCertificate.PrivateKey);
            var signatureAlgorithmName = bcIssuerCertificate.SigAlgOid;

            var certificate = GenerateCertificate(random, subjectDn, certificateSubjectKeyPair, subjectSerialNumber,
                                                  GetAllSan(), issuerDn, issuerKeyPair, keyUsages, extendedKeyUsages, 30, signatureAlgorithmName);

            var convertedCertificate = ConvertCertificate(certificate, certificateSubjectKeyPair, random);

            convertedCertificate.FriendlyName = commonName;
            return(convertedCertificate);
        }
Пример #2
0
        /// <summary>
        /// https://stackoverflow.com/questions/22230745/generate-a-self-signed-certificate-on-the-fly
        /// </summary>
        /// <param name="subjectName"></param>
        /// <param name="subjectKeyPair"></param>
        /// <param name="resultKeyPair"></param>
        /// <returns></returns>
        public static X509Certificate2 GenerateCaCertificate(
            string subjectName,
            out AsymmetricCipherKeyPair resultKeyPair,
            AsymmetricCipherKeyPair subjectKeyPair = null)
        {
            const int keyStrength = 2048;

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

            // The Certificate Generator
            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();

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

            certificateGenerator.SetSerialNumber(serialNumber);

            // Signature Algorithm
            const string signatureAlgorithm = "SHA256WithRSA";

            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);

            // Issuer and Subject Name
            X509Name subjectDn = new X509Name(subjectName);
            X509Name issuerDn  = subjectDn;

            certificateGenerator.SetIssuerDN(issuerDn);
            certificateGenerator.SetSubjectDN(subjectDn);

            // Valid For
            DateTime notBefore = DateTime.UtcNow.Date;
            DateTime notAfter  = notBefore.AddYears(100);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Generate a key pair if none was provided
            if (subjectKeyPair == null)
            {
                KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
                RsaKeyPairGenerator     keyPairGenerator        = new RsaKeyPairGenerator();
                keyPairGenerator.Init(keyGenerationParameters);
                subjectKeyPair = keyPairGenerator.GenerateKeyPair();
            }

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Generating the Certificate
            AsymmetricCipherKeyPair issuerKeyPair = subjectKeyPair;

            // Selfsign certificate
            Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(issuerKeyPair.Private, random);
            X509Certificate2 x509 = new X509Certificate2(certificate.GetEncoded(), string.Empty, X509KeyStorageFlags.EphemeralKeySet);

            resultKeyPair = issuerKeyPair;

            return(x509);
        }
Пример #3
0
        /// <summary>
        /// Creates a new X509 certificate and returns its data in PEM format
        /// </summary>
        public string GenerateNewCertificatePEM()
        {
            var randomGenerator      = new CryptoApiRandomGenerator();
            var random               = new SecureRandom(randomGenerator);
            var certificateGenerator = new X509V3CertificateGenerator();
            var serialNumber         = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);
            certificateGenerator.SetSignatureAlgorithm("SHA256WithRSA");
            var subjectDN = new X509Name("cn=Unknown");
            var issuerDN  = subjectDN;

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);
            certificateGenerator.SetNotBefore(DateTime.UtcNow.Date.AddYears(-10));
            certificateGenerator.SetNotAfter(DateTime.UtcNow.Date.AddYears(50));
            var keyGenerationParameters = new KeyGenerationParameters(random, 2048);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            X509Certificate cert = certificateGenerator.Generate(subjectKeyPair.Private);

            using (var writer = new StringWriter())
            {
                var pemWriter = new OpenSsl.PemWriter(writer);

                pemWriter.WriteObject(new PemObject("CERTIFICATE", cert.GetEncoded()));
                pemWriter.WriteObject(subjectKeyPair.Private);
                return(writer.ToString());
            }
        }
Пример #4
0
        /// <summary>
        /// Windows TLS needs the Alias public + private key in a PFX file
        /// </summary>
        /// <param name="certFile"></param>
        /// <param name="keyFile"></param>
        internal static void MakePFXFile(string certFile, string keyFile, string outputPfxFile, string password)
        {
            CryptoApiRandomGenerator rg = new CryptoApiRandomGenerator();
            var rng = new SecureRandom(rg);
            // get the cert
            var parser = new X509CertificateParser();
            var cert   = parser.ReadCertificate(File.ReadAllBytes(certFile));

            // get the key
            Org.BouncyCastle.OpenSsl.PemReader pemReader =
                new Org.BouncyCastle.OpenSsl.PemReader(new StringReader(File.ReadAllText(keyFile)));
            AsymmetricCipherKeyPair kp = pemReader.ReadObject() as AsymmetricCipherKeyPair;


            // Put the key and cert in an PKCS12 store so that the WIndows TLS stack can use it
            var    store            = new Pkcs12Store();
            string friendlyName     = cert.SubjectDN.ToString();
            var    certificateEntry = new X509CertificateEntry(cert);

            store.SetCertificateEntry(friendlyName, certificateEntry);
            store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(kp.Private), new[] { certificateEntry });

            var stream = new MemoryStream();
            var pwd    = password == null ? null : password.ToCharArray();

            store.Save(stream, pwd, rng);
            File.WriteAllBytes(outputPfxFile, stream.ToArray());
            return;
        }
        private static Org.BouncyCastle.Security.SecureRandom GetSecureRandom()
        {
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new Org.BouncyCastle.Security.SecureRandom(randomGenerator);

            return(random);
        }
Пример #6
0
        public static (CertPrivateKey, BcCertificate) GenerateRsaSelfSignedCertificate(string subjectName,
                                                                                       string issuerName,
                                                                                       AsymmetricKeyParameter issuerPrivKey, int keyStrength = 2048)
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

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

            certificateGenerator.SetSerialNumber(serialNumber);

            // Signature Algorithm
            const string signatureAlgorithm = "SHA256WithRSA";

#pragma warning disable CS0618 // Type or member is obsolete
            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);
#pragma warning restore CS0618 // Type or member is obsolete

            // Issuer and Subject Name
            var subjectDN = new X509Name(subjectName);
            var issuerDN  = new X509Name(issuerName);
            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Valid For
            var notBefore = DateTime.UtcNow.AddMonths(-1).Date;
            var notAfter  = DateTime.UtcNow.AddMonths(1).Date;

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            AsymmetricCipherKeyPair subjectKeyPair;
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();
            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Generating the Certificate
            var issuerKeyPair = subjectKeyPair;

            // selfsign certificate
#pragma warning disable CS0618 // Type or member is obsolete
            var certificate = certificateGenerator.Generate(issuerPrivKey, random);
#pragma warning restore CS0618 // Type or member is obsolete

            var key = new CertPrivateKey
            {
                KeyPair = subjectKeyPair,
            };
            return(key, certificate);
        }
Пример #7
0
        public X509Certificate2 Build()
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            certificateGenerator.SetIssuerDN(new X509Name(_issuerName ?? _subjectName));
            certificateGenerator.SetSubjectDN(new X509Name(_subjectName));

            // Authority Key Identifier
            if (_issuer != null)
            {
                var authorityKeyIdentifier = new AuthorityKeyIdentifierStructure(
                    DotNetUtilities.FromX509Certificate(_issuer));
                certificateGenerator.AddExtension(
                    X509Extensions.AuthorityKeyIdentifier.Id, false, authorityKeyIdentifier);
            }

            // Basic Constraints - certificate is allowed to be used as intermediate.
            certificateGenerator.AddExtension(
                X509Extensions.BasicConstraints.Id, true, new BasicConstraints(_intermediate));

            // Valid For
            certificateGenerator.SetNotBefore(_notBefore ?? DateTime.UtcNow.Date);
            certificateGenerator.SetNotAfter(_notAfter ?? DateTime.UtcNow.Date.AddYears(2));

            // Subject Public Key
            var keyGenerationParameters = new KeyGenerationParameters(random, _keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);

            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();
            var issuerKeyPair  = _issuerPrivateKey == null
                ? subjectKeyPair
                : DotNetUtilities.GetKeyPair(_issuerPrivateKey);

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Signature Algorithm
            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerKeyPair.Private, random);

            // selfsign certificate
            var certificate = certificateGenerator.Generate(signatureFactory);

            // Merge into X509Certificate2
            return(new X509Certificate2(certificate.GetEncoded())
            {
                PrivateKey = ConvertToRsaPrivateKey(subjectKeyPair)
            });
        }
Пример #8
0
        public static X509Certificate2 GenerateSelfSignedCert()
        {
            var randomGenerator      = new CryptoApiRandomGenerator();
            var random               = new SecureRandom(randomGenerator);
            var certificateGenerator = new X509V3CertificateGenerator();
            var serialNumber         =
                BigIntegers.CreateRandomInRange(
                    BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);
            const string signatureAlgorithm = "SHA1WithRSA";

            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);
            var subjectDN = new X509Name("CN=simpletorrent");
            var issuerDN  = subjectDN;

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);
            var notBefore = DateTime.UtcNow.Date.AddHours(-24);
            var notAfter  = notBefore.AddYears(1000);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);
            const int strength = 4096;
            var       keyGenerationParameters = new KeyGenerationParameters(random, strength);

            var keyPairGenerator = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

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

            var    store            = new Pkcs12Store();
            string friendlyName     = certificate.SubjectDN.ToString();
            var    certificateEntry = new X509CertificateEntry(certificate);

            store.SetCertificateEntry(friendlyName, certificateEntry);

            store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(subjectKeyPair.Private), new[] { certificateEntry });

            string password = "******";

            var stream = new MemoryStream();

            store.Save(stream, password.ToCharArray(), random);

            //mono bug #1660 fix -> convert to definite-length encoding
            byte[] pfx = Pkcs12Utilities.ConvertToDefiniteLength(stream.ToArray(), password.ToCharArray());

            var convertedCertificate =
                new X509Certificate2(
                    pfx, password,
                    X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

            return(convertedCertificate);
        }
Пример #9
0
        private static SecureRandom GenerateRandom()
        {
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            return(random);
        }
Пример #10
0
        public AsymmetricCipherKeyPair GenerateRsaKeyPair(int rsaKeySize = 2048)
        {
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            return(GenerateRsaKeyPair(random, rsaKeySize));
        }
Пример #11
0
        internal ComposedCertificate Generate(Type type, String subjectName, String issuerName, AsymmetricKeyParameter parentPrivate)
        {
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            var generator = new X509V3CertificateGenerator();

            setSerialNumber(generator, random);
            setSubjectAndIssuer(generator, subjectName, issuerName);
            setValidity(generator);

            if (type == Type.Root)
            {
                setCA(generator);
            }

            var keyPair = setPublicKey(generator, random);

            var x509 = signAndMerge(generator, random, parentPrivate ?? keyPair.Private);

            if (type == Type.SSL)
            {
                setPrivateKey(x509, keyPair);
            }

            return(new ComposedCertificate(x509, keyPair.Private));
        }
Пример #12
0
        public void VerifyRandomness()
        {
            CryptoApiRandomGenerator instance = new CryptoApiRandomGenerator(true);

            Byte[] randomBytes = new Byte[32];

            Stopwatch stopwatch  = Stopwatch.StartNew();
            Int32     iterations = 2000;

            for (Int32 index = 0; index < iterations; index++)
            {
                instance.NextBytes(randomBytes);
                String output         = BitConverter.ToString(randomBytes);
                String outputAsBase64 = Convert.ToBase64String(randomBytes);

                Debug.WriteLine(output + " - " + outputAsBase64);

                //System.IO.File.AppendAllText(@"C:\Data\out.txt", output + " - " + outputAsBase64 + Environment.NewLine);

                if (index % (iterations / 10) == 0)
                {
                    Debug.WriteLine($"{index}/{iterations}");
                }
            }

            stopwatch.Stop();

            Double perSecond   = (Double)iterations / (Double)stopwatch.Elapsed.TotalSeconds;
            Double averageTime = (Double)stopwatch.Elapsed.TotalSeconds / (Double)iterations;

            Debug.WriteLine($"Elapsed: {stopwatch.Elapsed.ToString()} for {iterations.ToString()} iterations. ({perSecond:N1} iterations/second | Avg Time: {averageTime:N4})");

            Debugger.Break();
        }
Пример #13
0
        /// <summary>
        /// Creates a CA certificate.
        /// </summary>
        /// <param name="name">The name that should appear on the certificate in the subject field.</param>
        /// <param name="issuer">If it's an intermediate CA, you should provide here the Root CA certificate. Otherwise, pass null.</param>
        /// <returns>A CA certificate chain with a private key of the requested certificate.</returns>
        public static CertificateChainWithPrivateKey CreateCACertificate(
            string name = "Concerto",
            CertificateChainWithPrivateKey?issuer = null)
        {
            var randomGenerator = new CryptoApiRandomGenerator();
            var secureRandom    = new SecureRandom(randomGenerator);

            // key
            var keyPair = GenerateRsaKeyPair(secureRandom, 3072);

            var certificateGenerator = new X509V3CertificateGenerator();

            // serial number
            certificateGenerator.SetSerialNumber(GenerateRandomSerialNumber(secureRandom));

            // set subject
            var subjectName = new X509Name($"O={name} CA,OU={UserName}@{MachineName},CN={name} {UserName}@{MachineName}");

            certificateGenerator.SetSubjectDN(subjectName);

            certificateGenerator.SetNotAfter(DateTime.UtcNow.AddYears(10));
            certificateGenerator.SetNotBefore(DateTime.UtcNow);

            certificateGenerator.SetPublicKey(keyPair.Public);

            // issuer information
            if (issuer != null)
            {
                certificateGenerator.SetIssuerDN(issuer.PrimaryCertificate.SubjectDN);
                certificateGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false,
                                                  new AuthorityKeyIdentifier(
                                                      SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuer.PrimaryCertificate.GetPublicKey())));
            }
            else
            {
                certificateGenerator.SetIssuerDN(subjectName);
            }

            // SKID
            certificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false,
                                              new SubjectKeyIdentifierStructure(keyPair.Public));

            // CA constrains, we allow one intermediate certificate if root
            certificateGenerator.AddExtension(X509Extensions.BasicConstraints.Id, true,
                                              new BasicConstraints(issuer == null ? 1 : 0));

            // usage
            certificateGenerator.AddExtension(X509Extensions.KeyUsage, true,
                                              new KeyUsage(KeyUsage.KeyCertSign | KeyUsage.CrlSign));

            var signatureFactory = new Asn1SignatureFactory("SHA256WithRSA",
                                                            issuer != null ? issuer.PrivateKey : keyPair.Private, secureRandom);

            var certificate = certificateGenerator.Generate(signatureFactory);

            return(new CertificateChainWithPrivateKey(
                       BuildCertificateChain(certificate, issuer?.Certificates ?? Array.Empty <X509Certificate>()),
                       keyPair.Private));
        }
Пример #14
0
        public static X509Certificate2 GenerateCACertificate(string subjectName, ref AsymmetricKeyParameter CaPrivateKey)
        {
            const int keyStrength = 2048;

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

            // The Certificate Generator
            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();

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

            certificateGenerator.SetSerialNumber(serialNumber);

            // Signature Algorithm
            //const string signatureAlgorithm = "SHA256WithRSA";
            //certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);

            // Issuer and Subject Name
            X509Name subjectDN = new X509Name(subjectName);
            X509Name issuerDN  = subjectDN;

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Valid For
            DateTime notBefore = DateTime.UtcNow.Date;
            DateTime notAfter  = notBefore.AddYears(2);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            AsymmetricCipherKeyPair subjectKeyPair;
            KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            RsaKeyPairGenerator     keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Generating the Certificate
            AsymmetricCipherKeyPair issuerKeyPair = subjectKeyPair;

            // selfsign certificate
            //Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(issuerKeyPair.Private, random);
            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerKeyPair.Private, random);

            Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(signatureFactory);
            X509Certificate2 x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());

            CaPrivateKey = issuerKeyPair.Private;

            return(x509);
            //return issuerKeyPair.Private;
        }
Пример #15
0
        /// <summary>
        /// Create a certificate for domains, IP addresses, or URIs.
        /// </summary>
        /// <param name="hosts">
        /// Host for which the certificate is created. Could be domains, IP addresses, or URIs.
        /// Wildcards are supported.
        /// </param>
        /// <param name="issuer">The issuer certificate.</param>
        /// <param name="client">Defines whether this certificate will be used for client authentication.</param>
        /// <param name="ecdsa">Create a certificate with an ECDSA key.</param>
        /// <returns></returns>
        public static CertificateChainWithPrivateKey CreateCertificate(
            string[] hosts,
            CertificateChainWithPrivateKey issuer,
            bool client = false,
            bool ecdsa  = false)
        {
            var randomGenerator = new CryptoApiRandomGenerator();
            var secureRandom    = new SecureRandom(randomGenerator);

            // generate the key
            var keyPair = ecdsa ? GenerateEllipticCurveKeyPair(secureRandom) : GenerateRsaKeyPair(secureRandom, 2048);
            var certificateGenerator = new X509V3CertificateGenerator();

            // serial number
            certificateGenerator.SetSerialNumber(GenerateRandomSerialNumber(secureRandom));

            // set subject
            var subject = new X509Name($"O=concerto development,OU={UserName}@{MachineName},CN={hosts[0]}");

            certificateGenerator.SetSubjectDN(subject);
            certificateGenerator.SetNotAfter(DateTime.UtcNow.AddDays(820));
            certificateGenerator.SetNotBefore(DateTime.UtcNow);
            certificateGenerator.SetPublicKey(keyPair.Public);

            // not CA
            certificateGenerator.AddExtension(X509Extensions.BasicConstraints.Id, true,
                                              new BasicConstraints(false));

            // set issuer data
            certificateGenerator.SetIssuerDN(issuer.PrimaryCertificate.SubjectDN);
            certificateGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false,
                                              new AuthorityKeyIdentifier(
                                                  SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuer.PrimaryCertificate.GetPublicKey())));

            // usage
            certificateGenerator.AddExtension(X509Extensions.KeyUsage, true,
                                              new KeyUsage(KeyUsage.KeyEncipherment | KeyUsage.DigitalSignature));

            var extendedKeyUsages = new List <KeyPurposeID>();

            if (client)
            {
                extendedKeyUsages.Add(KeyPurposeID.IdKPClientAuth);
            }

            extendedKeyUsages.Add(KeyPurposeID.IdKPServerAuth);
            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id,
                                              false, new ExtendedKeyUsage(extendedKeyUsages));
            var subjectAlternativeNames = new List <Asn1Encodable>(hosts.Length);

            foreach (var host in hosts)
            {
                if (Uri.TryCreate(host, UriKind.Absolute, out _))
                {
                    subjectAlternativeNames.Add(new GeneralName(GeneralName.UniformResourceIdentifier, host));
                }
                else if (!string.IsNullOrEmpty(host))
                {
                    var h = host[0] == '*' ? "wildcard" + host[1..] : host;
Пример #16
0
        public static (Org.BouncyCastle.Crypto.Tls.Certificate crtificate, AsymmetricKeyParameter privateKey) CreateSelfSignedTlsCert(string subjectName, string issuerName, AsymmetricKeyParameter issuerPrivateKey)
        {
            const int keyStrength = DEFAULT_KEY_SIZE;

            if (issuerPrivateKey == null)
            {
                issuerPrivateKey = CreatePrivateKeyResource(issuerName);
            }

            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);
            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", issuerPrivateKey, random);

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

            certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName[] { new GeneralName(GeneralName.DnsName, "localhost"), new GeneralName(GeneralName.DnsName, "127.0.0.1") }));
            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(new List <DerObjectIdentifier>()
            {
                new DerObjectIdentifier("1.3.6.1.5.5.7.3.1")
            }));

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

            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            var subjectDn = new X509Name(subjectName);
            var issuerDn  = new X509Name(issuerName);

            certificateGenerator.SetIssuerDN(issuerDn);
            certificateGenerator.SetSubjectDN(subjectDn);

            // Valid For
            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = notBefore.AddYears(70);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // self sign certificate
            var certificate = certificateGenerator.Generate(signatureFactory);

            var chain          = new Org.BouncyCastle.Asn1.X509.X509CertificateStructure[] { X509CertificateStructure.GetInstance(certificate.GetEncoded()) };
            var tlsCertificate = new Org.BouncyCastle.Crypto.Tls.Certificate(chain);

            return(tlsCertificate, subjectKeyPair.Private);
        }
Пример #17
0
        /// <summary>
        /// Generate a self-signed certificate and add it to the Windows certificate store.
        /// </summary>
        /// <param name="subjectName">The subject name of the certificate.</param>
        /// <param name="friendlyName">The friendly name of the certificate.</param>
        /// <param name="location">Location of the certificate; either the Current User or Local Machine.</param>
        /// <param name="addAsTrustedRoot">Whether to add the generated certificate as a trusted root.</param>
        /// <param name="keyLength">Size of the key in bits.</param>
        /// <param name="durationYears">Duration of the certificate, specified in years.</param>
        /// <param name="oids">Collection of OIDs identifying certificate usage.</param>
        /// <returns>Self-signed certificate.</returns>
        public static X509Certificate2 CreateSelfSignedCertificate(string subjectName, string friendlyName, StoreLocation location, bool addAsTrustedRoot, int keyLength, int durationYears, List <DerObjectIdentifier> oids)
        {
            // Prepare random number generation.
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom             random          = new SecureRandom(randomGenerator);

            // Create asymmetric key.
            AsymmetricCipherKeyPair subjectKeyPair;
            KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, keyLength);
            RsaKeyPairGenerator     keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();
            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();

            // Generate a serial number.
            BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Assign the subject name.
            X509Name subjectDN = new X509Name("CN=" + subjectName);
            X509Name issuerDN  = subjectDN;

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Set valid dates.
            DateTime notBefore = DateTime.UtcNow.Date;
            DateTime notAfter  = notBefore.AddYears(durationYears);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Set key usage for digital signatures and key encipherment.
            KeyUsage usage = new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyEncipherment);

            certificateGenerator.AddExtension(X509Extensions.KeyUsage, true, usage);

            // Load the OIDs passed in and specify enhanced key usages.
            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(oids));

            // Assign the public key.
            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Self-sign the certificate using SHA-512.
            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", subjectKeyPair.Private, random);

            Org.BouncyCastle.X509.X509Certificate bouncyCastleCertificate = certificateGenerator.Generate(signatureFactory);

            // Convert from BouncyCastle private key format to System.Security.Cryptography format.
            AsymmetricAlgorithm privateKey      = ToDotNetKey((RsaPrivateCrtKeyParameters)subjectKeyPair.Private);
            X509Certificate2    x509certificate = new X509Certificate2(DotNetUtilities.ToX509Certificate(bouncyCastleCertificate));

            x509certificate.PrivateKey   = privateKey;
            x509certificate.FriendlyName = subjectName;

            return(x509certificate);
        }
Пример #18
0
        private void ProvideEssentialParameters()
        {
            var randomGenerator = new CryptoApiRandomGenerator();

            Random = new SecureRandom(randomGenerator);

            SerialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), Random);
        }
Пример #19
0
        // ReSharper disable once RedundantAssignment
        private static X509Certificate2 GenerateCACertificate(string subjectName, ref AsymmetricCipherKeyPair caKeyPair)
        {
            const int keyStrength = 2048;

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

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

            // Subject Public Key
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            caKeyPair = keyPairGenerator.GenerateKeyPair();

            // Serial Number
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Signature Algorithm
            const string signatureAlgorithm = "SHA256WithRSA";

            // Set the public key
            certificateGenerator.SetPublicKey(caKeyPair.Public);
            certificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, false, new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(caKeyPair.Public)));

            // Issuer and Subject Name
            var subjectDN = new X509Name(subjectName);

            certificateGenerator.SetSubjectDN(subjectDN);

            // Issuer
            certificateGenerator.SetIssuerDN(subjectDN);
            certificateGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(caKeyPair.Public)));

            // Valid For
            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = notBefore.AddYears(2);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Make this a CA
            certificateGenerator.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(true));

            // selfsign certificate
            var signatureFactory = new Asn1SignatureFactory(signatureAlgorithm, caKeyPair.Private);
            var certificate      = certificateGenerator.Generate(signatureFactory);
            var x509             = new X509Certificate2(certificate.GetEncoded());

            return(x509);

            // return issuerKeyPair.Private;
        }
Пример #20
0
        public static X509Certificate2 CreateCertificateAuthorityCertificate(string subjectName, out AsymmetricKeyParameter CaPrivateKey)
        {
            const int keyStrength = 2048;

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

            // The Certificate Generator
            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();

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

            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            X509Name subjectDN = new X509Name("CN=" + subjectName);
            X509Name issuerDN  = subjectDN;

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Valid For
            DateTime notBefore = DateTime.UtcNow.Date;
            DateTime notAfter  = notBefore.AddYears(2);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            RsaKeyPairGenerator     keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            AsymmetricCipherKeyPair subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Generating the Certificate
            AsymmetricCipherKeyPair issuerKeyPair    = subjectKeyPair;
            ISignatureFactory       signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerKeyPair.Private, random);

            // selfsign certificate
            Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(signatureFactory);
            //var dotNetPrivateKey = ToDotNetKey((RsaPrivateCrtKeyParameters)subjectKeyPair.Private);

            X509Certificate2 x509 = new X509Certificate2(certificate.GetEncoded())
            {
                FriendlyName = subjectName,
                PrivateKey   = DotNetUtilities.ToRSA((RsaPrivateCrtKeyParameters)subjectKeyPair.Private)
            };

            CaPrivateKey = issuerKeyPair.Private;

            return(x509);
        }
Пример #21
0
        /// <summary>
        /// Issues a Domain Validation certificate for the supplied hostname.
        /// </summary>
        /// <param name="host">
        /// The hostname for which to issue a DV certificate.
        /// </param>
        /// <returns>
        /// A DV certificate for the specified host.
        /// </returns>
        public System.Security.Cryptography.X509Certificates.X509Certificate2 GetSpoofedCertificateForHost(string host)
        {
            lock (m_genLock)
            {
                System.Security.Cryptography.X509Certificates.X509Certificate2 cloned = null;

                if (m_certificates.TryGetValue(host, out cloned))
                {
                    return(cloned);
                }

                var certGen = new X509V3CertificateGenerator();

                var serialRandomGen = new CryptoApiRandomGenerator();
                var serialRandom    = new SecureRandom(serialRandomGen);
                var serialNumber    = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), serialRandom);

                X509Name dnName = new X509Name(string.Format("CN={0}", host));
                certGen.SetSerialNumber(serialNumber);
                certGen.SetIssuerDN(m_caCertificate.SubjectDN);
                certGen.SetNotBefore(DateTime.Now.AddYears(-1).ToUniversalTime());
                certGen.SetNotAfter(DateTime.Now.AddYears(2).ToUniversalTime());
                certGen.SetSubjectDN(dnName);

                /*
                 * var certificatePermissions = new List<KeyPurposeID>()
                 * {
                 *   KeyPurposeID.IdKPServerAuth
                 * };
                 *
                 * certGen.AddExtension(Org.BouncyCastle.Asn1.X509.X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(certificatePermissions));
                 */

                var subjectAlternativeNamesExtension = new DerSequence(new[] { host }.Select(name => new GeneralName(GeneralName.DnsName, name)).ToArray <Asn1Encodable>());

                certGen.AddExtension(X509Extensions.SubjectAlternativeName.Id, false, subjectAlternativeNamesExtension);

                var kpg = new ECKeyPairGenerator();
                kpg.Init(new KeyGenerationParameters(new SecureRandom(), 256));

                var fkp = kpg.GenerateKeyPair();

                certGen.SetPublicKey(fkp.Public);

                certGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(m_caCertificate));
                certGen.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(fkp.Public));

                X509Certificate cert = certGen.Generate(m_caSigner);

                var converted = cert.ConvertFromBouncyCastle(fkp);

                m_certificates.Add(host, converted);

                return(converted);
            }
        }
        /// <summary>
        /// Create a self signed certificate in the specified file.
        /// </summary>
        /// <param name="subjectName">The subject of the certificate to create.</param>
        /// <param name="fileName">The file name to write the certificate to.</param>
        /// <param name="signatureAlgorithm">The signature algorithm to use</param>
        /// <param name="password">True if there is a password, false otherwise.  Note that if there is a password, PFX format is assumed.</param>
        public static void CreateSelfSignedInFile(string subjectName, string fileName, string signatureAlgorithm, string password = "")
        {
            byte[] serialNumber = GenerateSerialNumber();
            string subject      = string.Format("CN={0}", subjectName);

            var subjectDN = new X509Name(subject);
            var issuerDN  = subjectDN;

            const int keyStrength             = 2048;
            var       randomGenerator         = new CryptoApiRandomGenerator();
            var       random                  = new SecureRandom(randomGenerator);
            var       keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var       keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();
            var issuerKeyPair  = subjectKeyPair;

            ISignatureFactory signatureFactory = new Asn1SignatureFactory(signatureAlgorithm, issuerKeyPair.Private, random);


            var certificateGenerator = new X509V3CertificateGenerator();

            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id, true, new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth));
            certificateGenerator.SetSerialNumber(new BigInteger(serialNumber.Concat(new Byte[] { 0 }).ToArray()));
            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);
            certificateGenerator.SetNotBefore(DateTime.Now);
            certificateGenerator.SetNotAfter(DateTime.Now);
            certificateGenerator.SetPublicKey(subjectKeyPair.Public);
            var certificate = certificateGenerator.Generate(signatureFactory);


            var    store            = new Pkcs12Store();
            string friendlyName     = certificate.SubjectDN.ToString();
            var    certificateEntry = new X509CertificateEntry(certificate);

            store.SetCertificateEntry(friendlyName, certificateEntry);
            store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(subjectKeyPair.Private), new[] { certificateEntry });
            var stream = new MemoryStream();

            store.Save(stream, password.ToCharArray(), random);

            var convertedCertificate = new X509Certificate2(stream.ToArray(), password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

            //If password is not empty, generate a PKCS#12 formatted file
            if (!string.IsNullOrEmpty(password))
            {
                File.WriteAllBytes(fileName, stream.ToArray());
            }
            //If password is empty generate a DER formatted file
            else
            {
                File.WriteAllBytes(fileName, convertedCertificate.RawData);
            }
        }
Пример #23
0
        public static AsymmetricKeyParameter GenerateCACertificate(string subjectName, int keyStrength = 2048)
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

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

            certificateGenerator.SetSerialNumber(serialNumber);

            // Signature Algorithm
            const string signatureAlgorithm = "SHA256WithRSA";

            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);

            // Issuer and Subject Name
            var subjectDN = new X509Name(subjectName);
            var issuerDN  = subjectDN;

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Valid For
            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = notBefore.AddYears(2);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            AsymmetricCipherKeyPair subjectKeyPair;
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Generating the Certificate
            var issuerKeyPair = subjectKeyPair;

            // selfsign certificate
            var certificate = certificateGenerator.Generate(issuerKeyPair.Private, random);
            var x509        = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());


            // Add CA certificate to Root store
            addCertToStore(x509, StoreName.Root, StoreLocation.CurrentUser);

            return(issuerKeyPair.Private);
        }
Пример #24
0
        public X509Certificate2 CreateSelfSignedCertificateBasedOnCertificateAuthorityPrivateKey(string subjectName, string issuerName, AsymmetricKeyParameter issuerPrivKey)
        {
            const int keyStrength = 2048;

            // Generating Random Numbers
            CryptoApiRandomGenerator randomGenerator  = new CryptoApiRandomGenerator();
            SecureRandom             random           = new SecureRandom(randomGenerator);
            ISignatureFactory        signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerPrivKey, random);

            // The Certificate Generator
            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();

            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id, true, new ExtendedKeyUsage(KeyPurposeID.AnyExtendedKeyUsage));

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

            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            X509Name subjectDN = new X509Name("CN=" + subjectName);
            X509Name issuerDN  = new X509Name("CN=" + issuerName);

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);


            // Valid For
            DateTime notBefore = DateTime.UtcNow.Date;
            DateTime notAfter  = notBefore.AddYears(2);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            AsymmetricCipherKeyPair subjectKeyPair;
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // selfsign certificate
            Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(signatureFactory);
            //var dotNetPrivateKey = ToDotNetKey((RsaPrivateCrtKeyParameters)subjectKeyPair.Private);

            // merge into X509Certificate2
            X509Certificate2 x509 = new X509Certificate2(DotNetUtilities.ToX509Certificate(certificate));

            //x509.PrivateKey = dotNetPrivateKey;
            x509.FriendlyName = subjectName;

            return(x509);
        }
Пример #25
0
            public static SecureRandom GetSecureRandom()
            {
                // Since we're on Windows, we'll use the CryptoAPI one (on the assumption
                // that it might have access to better sources of entropy than the built-in
                // Bouncy Castle ones):
                var randomGenerator = new CryptoApiRandomGenerator();
                var random          = new SecureRandom(randomGenerator);

                return(random);
            }
Пример #26
0
        private static AsymmetricCipherKeyPair GenerateKeys(int keySizeInBits)
        {
            var r = new RsaKeyPairGenerator();
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();

            r.Init(new KeyGenerationParameters(new SecureRandom(randomGenerator), keySizeInBits));
            var keys = r.GenerateKeyPair();

            return(keys);
        }
        public static AsymmetricCipherKeyPair GetKeyPair()
        {
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom             secureRandom    = new SecureRandom(randomGenerator);
            var keyGenerationParameters = new KeyGenerationParameters(secureRandom, RsaKeySize);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            return(keyPairGenerator.GenerateKeyPair());
        }
Пример #28
0
        public static byte[] toto(string subjectName, string issuerName, AsymmetricKeyParameter issuerPrivKey, int keyStrength = 2048)
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

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

            certificateGenerator.SetSerialNumber(serialNumber);

            // Signature Algorithm
            const string signatureAlgorithm = "SHA1WithRSA";

            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);

            // Issuer and Subject Name
            var subjectDN = new X509Name(subjectName);
            var issuerDN  = new X509Name(issuerName);

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Valid For
            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = notBefore.AddDays(5);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            AsymmetricCipherKeyPair subjectKeyPair;
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Generating the Certificate
            var issuerKeyPair = subjectKeyPair;

            // selfsign certificate
            var certificate = certificateGenerator.Generate(subjectKeyPair.Private, random);

            // correcponding private key
            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);


            return(certificate.GetEncoded());
        }
Пример #29
0
        private static X509Certificate2 GenerateCACertificate(string subjectName, ref AsymmetricKeyParameter asymmetricKeyParameter)
        {
            const int keyStrength = 2048;

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

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(int.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Signature Algorithm
            const string signatureAlgorithm = "SHA256WithRSA";

            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);

            // Issuer and Subject Name
            var subjectDN = new X509Name(subjectName);
            var issuerDN  = subjectDN;

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Valid For
            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = notBefore.AddYears(2);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            var asymmetricCipherKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(asymmetricCipherKeyPair.Public);

            // Generating the Certificate
            var issuerKeyPair = asymmetricCipherKeyPair;

            // self-sign certificate
            var certificate = certificateGenerator.Generate(issuerKeyPair.Private, random);
            var x509        = new X509Certificate2(certificate.GetEncoded());

            asymmetricKeyParameter = issuerKeyPair.Private;

            return(x509);
        }
Пример #30
0
        /// <summary>	Generates a ca certificate. </summary>
        /// <param name="subjectName">  Name of the subject. </param>
        /// <param name="caPrivateKey">	[in,out] The ca private key. </param>
        /// <param name="validTill">    The valid till Date/Time. </param>
        /// <param name="keyStrength">  (Optional) The key strength. </param>
        /// <returns>	The ca certificate. </returns>
        public static X509Certificate2 GenerateCaCertificate(string subjectName,
                                                             out AsymmetricKeyParameter caPrivateKey,
                                                             DateTime validTill, int keyStrength = 2048)
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            var serialNumber =
                BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            var subjectDn = new X509Name(subjectName);
            var issuerDn  = subjectDn;

            certificateGenerator.SetIssuerDN(issuerDn);
            certificateGenerator.SetSubjectDN(subjectDn);

            // Valid For
            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = validTill;

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Generating the Certificate
            var issuerKeyPair = subjectKeyPair;

            // Signature Algorithm
            ISignatureFactory signatureFactory = new Asn1SignatureFactory(SignatureAlgorithm, issuerKeyPair.Private);

            // selfsign certificate
            var certificate = certificateGenerator.Generate(signatureFactory);
            var x509        = new X509Certificate2(certificate.GetEncoded());

            caPrivateKey = issuerKeyPair.Private;

            return(x509);
        }