Esempio n. 1
0
        public static X509Certificate GenerateEndEntityCert(
            AsymmetricKeyParameter entityKey,
            AsymmetricKeyParameter caKey,
            X509Certificate caCert)
        {
            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);
            certGen.SetIssuerDN(PrincipalUtilities.GetSubjectX509Principal(caCert));
            certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
            certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
            certGen.SetSubjectDN(new X509Name("CN=Test End Certificate"));
            certGen.SetPublicKey(entityKey);
            certGen.SetSignatureAlgorithm("SHA256WithRSAEncryption");

            certGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert));
            certGen.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(entityKey));
            certGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
            certGen.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyEncipherment));

            return(certGen.Generate(caKey));
        }
Esempio n. 2
0
        /// <summary>
        /// Generates the certificate for <see cref="ChallengeTypes.TlsAlpn01" /> validation.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="token">The <see cref="ChallengeTypes.TlsAlpn01" /> token.</param>
        /// <param name="subjectName">Name of the subject.</param>
        /// <param name="certificateKey">The certificate key pair.</param>
        /// <returns>The tls-alpn-01 certificate in PEM.</returns>
        public static string TlsAlpnCertificate(this IKey key, string token, string subjectName, IKey certificateKey)
        {
            var keyAuthz = key.KeyAuthorization(token);
            var hashed   = DigestUtilities.CalculateDigest("SHA256", Encoding.UTF8.GetBytes(keyAuthz));

            var(_, keyPair) = signatureAlgorithmProvider.GetKeyPair(certificateKey.ToDer());

            var signatureFactory = new Asn1SignatureFactory(certificateKey.Algorithm.ToPkcsObjectId(), keyPair.Private, new SecureRandom());
            var gen      = new X509V3CertificateGenerator();
            var certName = new X509Name($"CN={subjectName}");
            var serialNo = BigInteger.ProbablePrime(120, new SecureRandom());

            gen.SetSerialNumber(serialNo);
            gen.SetSubjectDN(certName);
            gen.SetIssuerDN(certName);
            gen.SetNotBefore(DateTime.UtcNow);
            gen.SetNotAfter(DateTime.UtcNow.AddDays(7));
            gen.SetPublicKey(keyPair.Public);

            // SAN for validation
            var gns = new[] { new GeneralName(GeneralName.DnsName, subjectName) };

            gen.AddExtension(X509Extensions.SubjectAlternativeName.Id, false, new GeneralNames(gns));

            // ACME-TLS/1
            gen.AddExtension(
                acmeValidationV1Id,
                true,
                hashed);

            var newCert = gen.Generate(signatureFactory);

            using (var sr = new StringWriter())
            {
                var pemWriter = new PemWriter(sr);
                pemWriter.WriteObject(newCert);
                return(sr.ToString());
            }
        }
Esempio n. 3
0
        public static Org.BouncyCastle.X509.X509Certificate CreateCert(String cn,
                                                                       AsymmetricKeyParameter pubKey,
                                                                       AsymmetricKeyParameter privKey)
        {
            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);
            certGen.SetIssuerDN(new X509Name(cn));
            certGen.SetNotBefore(DateTime.UtcNow.AddDays(-30));
            certGen.SetNotAfter(DateTime.UtcNow.AddDays(30));
            certGen.SetSubjectDN(new X509Name(cn));
            certGen.SetPublicKey(pubKey);
            certGen.SetSignatureAlgorithm("SHA1WithRSAEncryption");

            Org.BouncyCastle.X509.X509Certificate cert = certGen.Generate(privKey);

            cert.CheckValidity(DateTime.UtcNow);

            cert.Verify(pubKey);

            return(cert);
        }
Esempio n. 4
0
        public static AsymmetricKeyParameter CreatePrivateKeyResource(string subjectName = "CN=root")
        {
            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(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  = 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();

            return(subjectKeyPair.Private);
        }
        /// <summary>
        /// Renews a <see cref="X509Certificate2"/>. This keeps all but the serial number, effective date, and expiration date./>
        /// </summary>
        /// <param name="certificate">Certificate being renewed</param>
        /// <param name="effectiveDate">New effective date</param>
        /// <param name="expirationDate">New expiration date</param>
        /// <param name="caCertificate">Signing certificate</param>
        /// <returns>New <seealso cref="X509Certificate2"/> renewed from <paramref name="certificate"/></returns>
        public static X509Certificate2 Renew(X509Certificate2 certificate, DateTime effectiveDate, DateTime expirationDate,
                                             X509Certificate2 caCertificate)
        {
            AsymmetricKeyParameter signingKey = caCertificate == null ? null : Certificate.TransformRSAPrivateKey((RSACryptoServiceProvider)caCertificate.PrivateKey);
            var privateKeyParameter           = TransformRSAPrivateKey((RSACryptoServiceProvider)certificate.PrivateKey);
            var bcCert                      = DotNetUtilities.FromX509Certificate(certificate);
            var publicKeyParameter          = bcCert.GetPublicKey();
            AsymmetricCipherKeyPair keyPair = new AsymmetricCipherKeyPair(publicKeyParameter, privateKeyParameter);

            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
            BigInteger serialNumber            = CreateSerialNumber();

            certGen.SetSerialNumber(serialNumber);
            certGen.SetIssuerDN(bcCert.IssuerDN);

            // Converted time to Universal Time so that the time set when calling Generate is the same as the time specified
            certGen.SetNotBefore(effectiveDate.ToUniversalTime());
            certGen.SetNotAfter(expirationDate.ToUniversalTime());

            certGen.SetSubjectDN(bcCert.SubjectDN);
            certGen.SetPublicKey(keyPair.Public);
            certGen.SetSignatureAlgorithm(SIGNATURE_ALGORITHM);

            // Copy all extensions
            foreach (var ext in certificate.Extensions)
            {
                certGen.CopyAndAddExtension(ext.Oid.Value, ext.Critical, bcCert);
            }

            Org.BouncyCastle.X509.X509Certificate bcNewCert = certGen.Generate(signingKey ?? keyPair.Private);

            X509Certificate2 dotNetCert = new X509Certificate2(bcNewCert.GetEncoded())
            {
                // Restore private key
                PrivateKey = certificate.PrivateKey
            };

            return(dotNetCert);
        }
        /// <summary>
        /// Generate the certificate
        /// </summary>
        /// <param name="certName">Certificate name</param>
        /// <param name="certPublicKey">Certificate public key</param>
        /// <param name="certPublicKeyInfo">Certificate public key info</param>
        /// <param name="issuer">Issuer name</param>
        /// <param name="issuerPublicKey">Issuer public key</param>
        /// <param name="issuerPrivateKey">Issuer private key</param>
        /// <param name="issuerSerialNumber">Issuer serial number</param>
        /// <returns>X509Certificate2 Certificate</returns>
        private X509Certificate2 GenerateCertificate(X509Name certName, AsymmetricKeyParameter certPublicKey, SubjectPublicKeyInfo certPublicKeyInfo,
                                                     X509Name issuer, AsymmetricKeyParameter issuerPublicKey, AsymmetricKeyParameter issuerPrivateKey, BigInteger issuerSerialNumber)
        {
            var randomGenerator       = new CryptoApiRandomGenerator();
            var random                = new SecureRandom(randomGenerator);
            ISignatureFactory factory = new Asn1SignatureFactory("SHA256withRSA", issuerPrivateKey, random);

            X509V3CertificateGenerator builder = new X509V3CertificateGenerator();

            builder.SetSerialNumber(new BigInteger(16, new SecureRandom(randomGenerator)));
            builder.SetIssuerDN(issuer);
            builder.SetSubjectDN(certName);
            builder.SetPublicKey(certPublicKey);
            builder.SetNotBefore(DateTime.UtcNow);
            builder.SetNotAfter(DateTime.UtcNow.AddDays(_config.DeviceCertificateValidityDays));

            builder.AddExtension(X509Extensions.KeyUsage.Id, true, new X509KeyUsage(X509KeyUsage.DigitalSignature | X509KeyUsage.KeyEncipherment));
            builder.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(false));

            var subjectAlternativeNames          = new Asn1Encodable[] { new GeneralName(GeneralName.DnsName, certName.GetValueList()[0].ToString()) };
            var subjectAlternativeNamesExtension = new DerSequence(subjectAlternativeNames);

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

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

            builder.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, false, GetAuthorityKeyIdentifier(issuer, issuerPublicKey, issuerSerialNumber));
            builder.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, false, new SubjectKeyIdentifier(certPublicKeyInfo));

            // Sign the certificate
            Org.BouncyCastle.X509.X509Certificate newCertificate = builder.Generate(factory);

            return(new X509Certificate2(DotNetUtilities.ToX509Certificate(newCertificate)));
        }
Esempio n. 7
0
        public static Tuple <SigningCredentials, X509Certificate2> GenerateSigningInformation()
        {
            var kp  = GenereateKeys();
            var gen = new X509V3CertificateGenerator();

            var certName = new X509Name("CN=Test_" + Guid.NewGuid());
            var serialNo = BigInteger.ProbablePrime(120, new 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.SetPublicKey(kp.Public);

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

            gen.AddExtension(
                X509Extensions.ExtendedKeyUsage.Id,
                false,
                new ExtendedKeyUsage(new ArrayList()
            {
                new DerObjectIdentifier("1.3.6.1.5.5.7.3.1")
            }));

            var signatureFactory = new Asn1SignatureFactory("MD5WithRSA", kp.Private);
            var x509Certificate  = new X509Certificate2(gen.Generate(signatureFactory).GetEncoded());
            var rsa = ToRsaParameters((RsaPrivateCrtKeyParameters)kp.Private);
            var signingCredentials = new SigningCredentials(new RsaSecurityKey(rsa), SecurityAlgorithms.RsaSha256Signature);

            return(new Tuple <SigningCredentials, X509Certificate2>(signingCredentials, x509Certificate));
        }
Esempio n. 8
0
        public static X509Certificate2 SampleTEST(SecureString samplPwd)
        {
            // Keypair Generator
            RsaKeyPairGenerator kpGenerator = new RsaKeyPairGenerator();

            kpGenerator.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 2048));

            // Create a keypair
            AsymmetricCipherKeyPair kp = kpGenerator.GenerateKeyPair();
            var privateKey             = (RsaPrivateCrtKeyParameters)kp.Private;

            // Certificate Generator
            X509V3CertificateGenerator cGenerator = new X509V3CertificateGenerator();

            cGenerator.SetSerialNumber(BigInteger.ProbablePrime(120, new Random()));
            cGenerator.SetSubjectDN(new X509Name("CN=" + "azureworking"));
            cGenerator.SetIssuerDN(new X509Name("CN=" + "azureworking"));
            cGenerator.SetNotBefore(DateTime.Now.Date.Subtract(new TimeSpan(10, 0, 0, 0)));
            cGenerator.SetNotAfter(DateTime.Now.Add(new TimeSpan(365, 0, 0, 0))); // Expire in 1 year
            const string signatureAlgorithm = "SHA1WithRSA";

            cGenerator.SetSignatureAlgorithm(signatureAlgorithm);


            cGenerator.SetPublicKey(kp.Public);                                           // Only the public key should be used here!

            Org.BouncyCastle.X509.X509Certificate cert = cGenerator.Generate(kp.Private); // Create a self-signed cert
            var dotNetPrivateKey = ToDotNetKey(privateKey);

            byte[] certStream = DotNetUtilities.ToX509Certificate(cert).Export(X509ContentType.Pkcs12, samplPwd);


            X509Certificate2 certToReturn = new X509Certificate2(certStream, samplPwd, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

            certToReturn.PrivateKey = dotNetPrivateKey;

            return(certToReturn);
        }
Esempio n. 9
0
        public X509Certificate2 MakeCertificate(string password, string issuedToDomainName, string friendlyName, int validMonths)
        {
            _certificateGenerator.Reset();
            _certificateGenerator.SetSignatureAlgorithm(SignatureAlgorithm);
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), _random);

            _certificateGenerator.SetSerialNumber(serialNumber);

            _certificateGenerator.SetSubjectDN(new X509Name(issuedToDomainName));
            _certificateGenerator.SetIssuerDN(_issuer);

            var utcNow = DateTime.UtcNow.AddDays(-1);

            _certificateGenerator.SetNotBefore(utcNow);
            _certificateGenerator.SetNotAfter(utcNow.AddMonths(validMonths));
            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();
            var certificateEntry = new X509CertificateEntry(certificate);

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

            using (var stream = new MemoryStream())
            {
                store.Save(stream, password.ToCharArray(), _random);
                return(new X509Certificate2(stream.ToArray(), password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable));
            }
        }
Esempio n. 10
0
        private static X509Certificate CreateCertificate(
            AsymmetricKeyParameter certificatePublicKey,
            Asn1SignatureFactory signatureFactory,
            BigInteger serialNumber,
            X509Name issuerName,
            X509Name subjectName,
            DateTimeOffset notBefore,
            DateTimeOffset notAfter,
            Action <X509V3CertificateGenerator> customizeCertificate)
        {
            var generator = new X509V3CertificateGenerator();

            generator.SetSerialNumber(serialNumber);
            generator.SetIssuerDN(issuerName);
            generator.SetNotBefore(notBefore.UtcDateTime);
            generator.SetNotAfter(notAfter.UtcDateTime);
            generator.SetSubjectDN(subjectName);
            generator.SetPublicKey(certificatePublicKey);

            customizeCertificate(generator);

            return(generator.Generate(signatureFactory));
        }
Esempio n. 11
0
            public void CreateCertificate(Key clientPublicKey, Key caPrivateKey)
            {
                DateTime               startDate  = DateTime.Now;
                DateTime               expiryDate = startDate.AddDays(365);
                SecureRandom           random     = new SecureRandom(new CryptoApiRandomGenerator());
                AsymmetricKeyParameter publicKey  = clientPublicKey.GetPublicAsAsymmetricKeyParam;

                System.Security.Cryptography.X509Certificates.X509Certificate2 caCert2 = LoadPKCS12FromFile();
                var utilities = DotNetUtilities.FromX509Certificate(caCert2);
                ISignatureFactory          signatureAlgorithm = new Asn1SignatureFactory("SHA256WITHRSA", caPrivateKey.GetPrivateAsAsymmetricKeyParam, random);
                X509V3CertificateGenerator certGen            = new X509V3CertificateGenerator();
                X509Name subjectName = new X509Name("C=Poland, O=West Pomeranian University of Technology, OU=IT department, ST=Szczecin, CN=bm29690.wi.zut.edu.pl, serialNumber=29690, Surname=Maciej Bartłomiejczyk");

                certGen.SetSerialNumber(BigInteger.ValueOf(DateTime.Now.Millisecond));
                certGen.SetIssuerDN(utilities.SubjectDN);
                certGen.SetNotBefore(startDate);
                certGen.SetNotAfter(expiryDate);
                certGen.SetSubjectDN(subjectName);
                certGen.SetPublicKey(publicKey);
                X509Certificate newCertificate = certGen.Generate(signatureAlgorithm);

                _certificate = newCertificate;
            }
Esempio n. 12
0
 public void CreateCertificate(Key clientPublicKey, Key caPrivateKey, System.Security.Cryptography.X509Certificates.X509Certificate2 caCert)
 {
     if (_certificateDN != null)
     {
         DateTime               startDate  = DateTime.Now;
         DateTime               expiryDate = startDate.AddDays(365);
         SecureRandom           random     = new SecureRandom(new CryptoApiRandomGenerator());
         AsymmetricKeyParameter publicKey  = clientPublicKey.GetPublicAsAsymmetricKeyParam;
         var utilities = DotNetUtilities.FromX509Certificate(caCert);
         ISignatureFactory          signatureAlgorithm = new Asn1SignatureFactory("SHA256WITHRSA", caPrivateKey.GetPrivateAsAsymmetricKeyParam, random);
         X509V3CertificateGenerator certGen            = new X509V3CertificateGenerator();
         X509Name subjectName = _certificateDN;
         certGen.SetSerialNumber(BigInteger.ValueOf(DateTime.Now.Millisecond));
         certGen.SetIssuerDN(utilities.SubjectDN);
         certGen.SetNotBefore(startDate);
         certGen.SetNotAfter(expiryDate);
         certGen.SetSubjectDN(subjectName);
         certGen.SetPublicKey(publicKey);
         X509Certificate newCertificate = certGen.Generate(signatureAlgorithm);
         _certificate = newCertificate;
         SaveAsString();
     }
 }
Esempio n. 13
0
        public static X509Certificate GenerateCertificate(AsymmetricCipherKeyPair keyPair, string certName,
                                                          string signatureAlgorithm)
        {
            signatureAlgorithm = signatureAlgorithm ?? DefaultSignatureAlgorithm;

            var gen = new X509V3CertificateGenerator();

            var cn     = new X509Name("CN=" + certName);
            var serial = BigInteger.ProbablePrime(120, new Random());

            gen.SetSerialNumber(serial);
            gen.SetSubjectDN(cn);
            gen.SetIssuerDN(cn);
            gen.SetNotAfter(DateTime.MaxValue);
            gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0)));
            gen.SetPublicKey(keyPair.Public);

            var sf = new Asn1SignatureFactory(signatureAlgorithm, keyPair.Private);

            var r = gen.Generate(sf);

            return(DotNetUtilities.ToX509Certificate(r));
        }
Esempio n. 14
0
        /// <summary>
        /// Creates a new X509 certificate and returns its data in PEM format.
        ///
        /// <see cref="PatchingCertificatePem"/> is generated using this method.
        /// </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);

            // TODO: Figure out ISignatureFactory to avoid these deprecated methods
#pragma warning disable 618
            certificateGenerator.SetSignatureAlgorithm("SHA256WithRSA");
#pragma warning restore 618
            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);

            // TODO: Figure out ISignatureFactory to avoid these deprecated methods
#pragma warning disable 618
            X509Certificate cert = certificateGenerator.Generate(subjectKeyPair.Private);
#pragma warning restore 618

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

            pemWriter.WriteObject(new PemObject("CERTIFICATE", cert.GetEncoded()));
            pemWriter.WriteObject(subjectKeyPair.Private);
            return(writer.ToString());
        }
        public static SX.X509Certificate2 GenerateCA(
            string name,
            int keySize,
            int days)
        {
            var key = GenerateRsaKeyPair(Random, keySize);

            var cert = new X509V3CertificateGenerator();

            var subject = new X509Name($"CN={name}");



            cert.SetIssuerDN(subject);

            cert.SetSubjectDN(subject);

            cert.SetSerialNumber(GenerateSerialNumber(Random));

            SetDateTime(cert, days);

            cert.SetPublicKey(key.Public);

            SetKeyUsageCA(cert);

            SetBasicConstraints(cert, true);

            SetExtendedKeyUsage(cert);

            SetuthorityKeyIdentifier(cert, key.Public);

            SetSubjectPublicKey(cert, key.Public);

            var x509 = cert.Generate(new Asn1SignatureFactory(PkcsObjectIdentifiers.Sha256WithRsaEncryption.Id, key.Private));

            return(AsForm(x509, key, Random));
        }
        public static X509Certificate2 CreateCertificate(string certName, X509Certificate2 ca, int keyStrength)
        {
            var caCert     = DotNetUtilities.FromX509Certificate(ca);
            var random     = new SecureRandom(new CryptoApiRandomGenerator());
            var keyPairGen = new RsaKeyPairGenerator();

            keyPairGen.Init(new KeyGenerationParameters(random, keyStrength));
            AsymmetricCipherKeyPair keyPair = keyPairGen.GenerateKeyPair();

            var certificateGenerator = new X509V3CertificateGenerator();

            var CN = new X509Name("CN=" + certName);
            var SN = BigInteger.ProbablePrime(120, random);

            certificateGenerator.SetSerialNumber(SN);
            certificateGenerator.SetSubjectDN(CN);
            certificateGenerator.SetIssuerDN(caCert.IssuerDN);
            certificateGenerator.SetNotAfter(DateTime.MaxValue);
            certificateGenerator.SetNotBefore(DateTime.UtcNow.Subtract(new TimeSpan(1, 0, 0, 0)));
            certificateGenerator.SetPublicKey(keyPair.Public);
            certificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.Public));
            certificateGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert.GetPublicKey()));

            var caKeyPair = DotNetUtilities.GetKeyPair(ca.PrivateKey);

            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", caKeyPair.Private, random);

            var certificate = certificateGenerator.Generate(signatureFactory);

            certificate.Verify(caCert.GetPublicKey());

            var certificate2 = new X509Certificate2(DotNetUtilities.ToX509Certificate(certificate));

            certificate2.PrivateKey = DotNetUtilities.ToRSA(keyPair.Private as RsaPrivateCrtKeyParameters);

            return(certificate2);
        }
Esempio n. 17
0
        public X509Certificate2 Generate()
        {
            subjectKeyPair = KeyRepository.Next();

            if (Issuer == null)
            {
                issuerKeyPair      = subjectKeyPair;
                issuerName         = SubjectName;
                issuerSerialNumber = SerialNumber;
            }
            else
            {
                issuerName         = Issuer.Subject;
                issuerKeyPair      = DotNetUtilities.GetKeyPair(Issuer.PrivateKey);
                issuerSerialNumber = new BigInteger(Issuer.GetSerialNumber());
            }

            certificateGenerator.SetSerialNumber(SerialNumber);
            certificateGenerator.SetSignatureAlgorithm("SHA256WithRSA");
            certificateGenerator.SetIssuerDN(new X509Name(issuerName));
            certificateGenerator.SetSubjectDN(new X509Name(SubjectName));
            certificateGenerator.SetNotBefore(NotBefore);
            certificateGenerator.SetNotAfter(NotAfter);
            certificateGenerator.SetPublicKey(subjectKeyPair.Public);
            AddAuthorityKeyIdentifier();
            AddSubjectKeyIdentifier();
            AddBasicConstraints();
            AddKeyUsage();
            AddExtendedKeyUsage();
            AddSubjectAlternativeNames();
            AddOcspPoints();
            AddCrlDistributionPoints();

            var certificate = certificateGenerator.Generate(issuerKeyPair.Private);

            return(ConvertCertificate(certificate));
        }
        public static X509Certificate2 CreateX509Certificate2()
        {
            // generate new key pair
            var keypairgen = new RsaKeyPairGenerator();

            keypairgen.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
            var keypair = keypairgen.GenerateKeyPair();

            // generate x509
            var signatureFactory = new Asn1SignatureFactory("SHA256WithRSA", keypair.Private, new SecureRandom());
            var generator        = new X509V3CertificateGenerator();
            var commonName       = new X509Name("CN=test");
            var serialNumber     = BigInteger.ProbablePrime(120, new SecureRandom());

            generator.SetSerialNumber(serialNumber);
            generator.SetSubjectDN(commonName);
            generator.SetIssuerDN(commonName);
            generator.SetNotAfter(DateTime.UtcNow.AddYears(99));
            generator.SetNotBefore(DateTime.UtcNow);
            generator.SetPublicKey(keypair.Public);

            var bouncyCert = generator.Generate(signatureFactory);

            // convert to .NET certificate
            var store            = new Pkcs12Store();
            var alias            = bouncyCert.SubjectDN.ToString();
            var certificateEntry = new X509CertificateEntry(bouncyCert);

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

            var          stream   = new MemoryStream();
            const string password = "******";

            store.Save(stream, password.ToCharArray(), new SecureRandom());
            return(new X509Certificate2(stream.ToArray(), password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable));
        }
Esempio n. 19
0
        /// <summary>
        /// Set all mandatory fields.
        /// </summary>
        /// <param name="cg">The cert generator</param>
        private void CreateMandatoryFields(X509V3CertificateGenerator cg)
        {
            m_subjectDN = new CertificateFactoryX509Name(SubjectName.Name);
            // subject and issuer DN
            m_issuerDN = null;
            if (IssuerCAKeyCert != null)
            {
                m_issuerDN = new CertificateFactoryX509Name(IssuerCAKeyCert.Subject);
            }
            else
            {
                // self signed
                m_issuerDN = m_subjectDN;
            }
            cg.SetIssuerDN(m_issuerDN);
            cg.SetSubjectDN(m_subjectDN);

            // valid for
            cg.SetNotBefore(NotBefore.ToUniversalTime());
            cg.SetNotAfter(NotAfter.ToUniversalTime());

            // serial number
            cg.SetSerialNumber(new BigInteger(1, m_serialNumber.Reverse().ToArray()));
        }
Esempio n. 20
0
        private static X509Certificate2 GenerateCert()
        {
            var keypairgen = new RsaKeyPairGenerator();

            keypairgen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 1024));

            var keypair = keypairgen.GenerateKeyPair();

            var gen = new X509V3CertificateGenerator();
            var CN  = new X509Name("CN=" + "Jabra test");
            var SN  = BigInteger.ProbablePrime(120, new Random());

            gen.SetSerialNumber(SN);
            gen.SetSubjectDN(CN);
            gen.SetIssuerDN(CN);
            gen.SetNotAfter(DateTime.MaxValue);
            gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0)));
            gen.SetSignatureAlgorithm("MD5WithRSA");
            gen.SetPublicKey(keypair.Public);

            var newCert = gen.Generate(keypair.Private);

            return(new X509Certificate2(DotNetUtilities.ToX509Certificate((Org.BouncyCastle.X509.X509Certificate)newCert)));
        }
Esempio n. 21
0
        public static X509Certificate2 GenerateSelfSigned(TimeSpan lifetime)
        {
            Guid         guid = Guid.NewGuid();
            DateTime     now  = DateTime.UtcNow;
            SecureRandom rand = new SecureRandom();


            //Generate a key pair
            RsaKeyPairGenerator keyGen = new RsaKeyPairGenerator();

            keyGen.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(rand, 1024));
            AsymmetricCipherKeyPair key = keyGen.GenerateKeyPair();

            //Generate a certificate
            X509Name dn = new X509Name("CN=" + guid.ToString());
            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetIssuerDN(dn);
            certGen.SetSerialNumber(new BigInteger(1, guid.ToByteArray()));
            certGen.SetSignatureAlgorithm("SHA1WITHRSA");
            certGen.SetSubjectDN(dn);
            certGen.SetPublicKey(key.Public);
            certGen.SetNotBefore(now);
            certGen.SetNotAfter(now.Add(lifetime));
            Org.BouncyCastle.X509.X509Certificate bcCert = certGen.Generate(key.Private);

            //Save it as pkcs12
            MemoryStream p12Stream = new MemoryStream();
            Pkcs12Store  p12       = new Pkcs12Store();

            p12.SetKeyEntry("sts", new AsymmetricKeyEntry(key.Private), new X509CertificateEntry[] { new X509CertificateEntry(bcCert) });
            p12.Save(p12Stream, p12TmpPwd.ToCharArray(), rand);

            //Load the pkcs12 as .Net Certificate
            return(new X509Certificate2(p12Stream.ToArray(), p12TmpPwd, X509KeyStorageFlags.DefaultKeySet));
        }
Esempio n. 22
0
        private static byte[] GenerateSelfSignedCertificate(string subjectName)
        {
            // Generating Random Numbers
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom             random          = new SecureRandom(randomGenerator);

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

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

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

            certificateGenerator.SetSerialNumber(BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random));
            certificateGenerator.SetSignatureAlgorithm(SignatureAlgorithm);
            certificateGenerator.SetIssuerDN(new X509Name(subjectName));
            certificateGenerator.SetSubjectDN(new X509Name(subjectName));
            certificateGenerator.SetNotBefore(DateTime.UtcNow.Date);
            certificateGenerator.SetNotAfter(DateTime.UtcNow.Date);
            certificateGenerator.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyEncipherment));
            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id, false, new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPClientAuth));
            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            Org.BouncyCastle.X509.X509Certificate cert = certificateGenerator.Generate(subjectKeyPair.Private, random);
            Pkcs12Store store = new Pkcs12StoreBuilder().SetUseDerEncoding(true).Build();

            store.SetKeyEntry("unused", new AsymmetricKeyEntry(subjectKeyPair.Private), new X509CertificateEntry[] { new X509CertificateEntry(cert) });
            using (MemoryStream stream = new MemoryStream())
            {
                store.Save(stream, new char[0], random);
                return(stream.ToArray());
            }
        }
        static X509V3CertificateGenerator GenerateTls(
            X509Name issuerName,
            AsymmetricKeyParameter issuerPublicKey,
            X509Name subjectName,
            AsymmetricKeyParameter subjectPublicKey,
            int days,
            string[] subjectNames
            )
        {
            var cert = new X509V3CertificateGenerator();

            cert.SetIssuerDN(issuerName);

            cert.SetSubjectDN(subjectName);

            cert.SetSerialNumber(GenerateSerialNumber(Random));

            SetDateTime(cert, days);

            cert.SetPublicKey(subjectPublicKey);

            SetBasicConstraints(cert, false);

            SetExtendedKeyUsage(cert);

            SetuthorityKeyIdentifier(cert, issuerPublicKey);

            SetKeyUsageTls(cert);

            SetSubjectPublicKey(cert, subjectPublicKey);

            SetSubjectAlternativeNames(cert, subjectNames);


            return(cert);
        }
Esempio n. 24
0
        /// <inheritdoc/>
        public async Task <(X509Certificate Certificate, RsaKeyParameters Key)> GetLocalCertificateAsync(ApplicationDescription applicationDescription, ILogger logger = null)
        {
            string applicationUri = applicationDescription.ApplicationUri;

            if (string.IsNullOrEmpty(applicationUri))
            {
                throw new ArgumentOutOfRangeException(nameof(applicationDescription), "Expecting ApplicationUri in the form of 'http://{hostname}/{appname}' -or- 'urn:{hostname}:{appname}'.");
            }

            string subjectName = null;
            string hostName    = null;
            string appName     = null;

            UriBuilder appUri = new UriBuilder(applicationUri);

            if (appUri.Scheme == "http" && !string.IsNullOrEmpty(appUri.Host))
            {
                var path = appUri.Path.Trim('/');
                if (!string.IsNullOrEmpty(path))
                {
                    hostName    = appUri.Host;
                    appName     = path;
                    subjectName = $"CN={appName},DC={hostName}";
                }
            }

            if (appUri.Scheme == "urn")
            {
                var parts = appUri.Path.Split(new[] { ':' }, 2);
                if (parts.Length == 2)
                {
                    hostName    = parts[0];
                    appName     = parts[1];
                    subjectName = $"CN={appName},DC={hostName}";
                }
            }

            if (subjectName == null)
            {
                throw new ArgumentOutOfRangeException(nameof(applicationDescription), "Expecting ApplicationUri in the form of 'http://{hostname}/{appname}' -or- 'urn:{hostname}:{appname}'.");
            }

            var crt = default(X509Certificate);
            var key = default(RsaKeyParameters);

            // Build 'own/certs' certificate store.
            var ownCerts     = new Org.BouncyCastle.Utilities.Collections.HashSet();
            var ownCertsInfo = new DirectoryInfo(Path.Combine(this.pkiPath, "own", "certs"));

            if (ownCertsInfo.Exists)
            {
                foreach (var info in ownCertsInfo.EnumerateFiles())
                {
                    using (var crtStream = info.OpenRead())
                    {
                        var c = this.certParser.ReadCertificate(crtStream);
                        if (c != null)
                        {
                            ownCerts.Add(c);
                        }
                    }
                }
            }

            IX509Store ownCertStore = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(ownCerts));

            // Select the newest certificate that matches by subject name.
            var selector = new X509CertStoreSelector()
            {
                Subject = new X509Name(subjectName)
            };

            crt = ownCertStore.GetMatches(selector).OfType <X509Certificate>().OrderBy(c => c.NotBefore).LastOrDefault();
            if (crt != null)
            {
                // If certificate found, verify alt-name, and retrieve private key.
                var asn1OctetString = crt.GetExtensionValue(X509Extensions.SubjectAlternativeName);
                if (asn1OctetString != null)
                {
                    var          asn1Object = X509ExtensionUtilities.FromExtensionValue(asn1OctetString);
                    GeneralNames gns        = GeneralNames.GetInstance(asn1Object);
                    if (gns.GetNames().Any(n => n.TagNo == GeneralName.UniformResourceIdentifier && n.Name.ToString() == applicationUri))
                    {
                        var ki = new FileInfo(Path.Combine(this.pkiPath, "own", "private", $"{crt.SerialNumber}.key"));
                        if (ki.Exists)
                        {
                            using (var keyStream = new StreamReader(ki.OpenRead()))
                            {
                                var keyReader = new PemReader(keyStream);
                                var keyPair   = keyReader.ReadObject() as AsymmetricCipherKeyPair;
                                if (keyPair != null)
                                {
                                    key = keyPair.Private as RsaKeyParameters;
                                }
                            }
                        }
                    }
                }
            }

            // If certificate and key are found, return to caller.
            if (crt != null && key != null)
            {
                logger?.LogTrace($"Found certificate with subject alt name '{applicationUri}'.");
                return(crt, key);
            }

            if (!this.CreateLocalCertificateIfNotExist)
            {
                return(null, null);
            }

            // Create new certificate
            var subjectDN = new X509Name(subjectName);

            // Create a keypair.
            var kp = await Task.Run <AsymmetricCipherKeyPair>(() =>
            {
                RsaKeyPairGenerator kg = new RsaKeyPairGenerator();
                kg.Init(new KeyGenerationParameters(this.rng, 2048));
                return(kg.GenerateKeyPair());
            });

            key = kp.Private as RsaPrivateCrtKeyParameters;

            // Create a certificate.
            X509V3CertificateGenerator cg = new X509V3CertificateGenerator();
            var subjectSN = BigInteger.ProbablePrime(120, this.rng);

            cg.SetSerialNumber(subjectSN);
            cg.SetSubjectDN(subjectDN);
            cg.SetIssuerDN(subjectDN);
            cg.SetNotBefore(DateTime.Now.Date.ToUniversalTime());
            cg.SetNotAfter(DateTime.Now.Date.ToUniversalTime().AddYears(25));
            cg.SetPublicKey(kp.Public);

            cg.AddExtension(
                X509Extensions.BasicConstraints.Id,
                true,
                new BasicConstraints(false));

            cg.AddExtension(
                X509Extensions.SubjectKeyIdentifier.Id,
                false,
                new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public)));

            cg.AddExtension(
                X509Extensions.AuthorityKeyIdentifier.Id,
                false,
                new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public), new GeneralNames(new GeneralName(subjectDN)), subjectSN));

            cg.AddExtension(
                X509Extensions.SubjectAlternativeName,
                false,
                new GeneralNames(new[] { new GeneralName(GeneralName.UniformResourceIdentifier, applicationUri), new GeneralName(GeneralName.DnsName, hostName) }));

            cg.AddExtension(
                X509Extensions.KeyUsage,
                true,
                new KeyUsage(KeyUsage.DataEncipherment | KeyUsage.DigitalSignature | KeyUsage.NonRepudiation | KeyUsage.KeyCertSign | KeyUsage.KeyEncipherment));

            cg.AddExtension(
                X509Extensions.ExtendedKeyUsage,
                true,
                new ExtendedKeyUsage(KeyPurposeID.IdKPClientAuth, KeyPurposeID.IdKPServerAuth));

            crt = cg.Generate(new Asn1SignatureFactory("SHA256WITHRSA", key, this.rng));

            logger?.LogTrace($"Created certificate with subject alt name '{applicationUri}'.");

            var keyInfo = new FileInfo(Path.Combine(this.pkiPath, "own", "private", $"{crt.SerialNumber}.key"));

            if (!keyInfo.Directory.Exists)
            {
                Directory.CreateDirectory(keyInfo.DirectoryName);
            }
            else if (keyInfo.Exists)
            {
                keyInfo.Delete();
            }

            using (var keystream = new StreamWriter(keyInfo.OpenWrite()))
            {
                var pemwriter = new PemWriter(keystream);
                pemwriter.WriteObject(key);
            }

            var crtInfo = new FileInfo(Path.Combine(this.pkiPath, "own", "certs", $"{crt.SerialNumber}.crt"));

            if (!crtInfo.Directory.Exists)
            {
                Directory.CreateDirectory(crtInfo.DirectoryName);
            }
            else if (crtInfo.Exists)
            {
                crtInfo.Delete();
            }

            using (var crtstream = new StreamWriter(crtInfo.OpenWrite()))
            {
                var pemwriter = new PemWriter(crtstream);
                pemwriter.WriteObject(crt);
            }

            return(crt, key);
        }
Esempio n. 25
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);

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

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

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

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);
//            certificateGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
            certificateGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, true, new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public), new GeneralNames(new GeneralName(issuerDN)), serialNumber));

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

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

            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
            X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);

            store.Open(OpenFlags.ReadWrite);
            store.Add(x509);
            store.Close();

            store = new X509Store(StoreName.TrustedPublisher, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadWrite);
            store.Add(x509);
            store.Close();

            RsaPrivateCrtKeyParameters rsaparams = (RsaPrivateCrtKeyParameters)issuerKeyPair.Private;

            x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams);
            store           = new X509Store("PrivateCertStore", StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadWrite);
            store.Add(x509);
            store.Close();

            return(issuerKeyPair.Private);
        }
Esempio n. 26
0
        /// <summary>
        /// Creates a self signed application instance certificate.
        /// </summary>
        /// <param name="storeType">Type of certificate store (Directory) <see cref="CertificateStoreType"/>.</param>
        /// <param name="storePath">The store path (syntax depends on storeType).</param>
        /// <param name="password">The password to use to protect the certificate.</param>
        /// <param name="applicationUri">The application uri (created if not specified).</param>
        /// <param name="applicationName">Name of the application (optional if subjectName is specified).</param>
        /// <param name="subjectName">The subject used to create the certificate (optional if applicationName is specified).</param>
        /// <param name="domainNames">The domain names that can be used to access the server machine (defaults to local computer name if not specified).</param>
        /// <param name="keySize">Size of the key (1024, 2048 or 4096).</param>
        /// <param name="startTime">The start time.</param>
        /// <param name="lifetimeInMonths">The lifetime of the key in months.</param>
        /// <param name="hashSizeInBits">The hash size in bits.</param>
        /// <param name="isCA">if set to <c>true</c> then a CA certificate is created.</param>
        /// <param name="issuerCAKeyCert">The CA cert with the CA private key.</param>
        /// <returns>The certificate with a private key.</returns>
        public static X509Certificate2 CreateCertificate(
            string storeType,
            string storePath,
            string password,
            string applicationUri,
            string applicationName,
            string subjectName,
            IList <String> domainNames,
            ushort keySize,
            DateTime startTime,
            ushort lifetimeInMonths,
            ushort hashSizeInBits,
            bool isCA,
            X509Certificate2 issuerCAKeyCert)
        {
            if (!String.IsNullOrEmpty(storeType) &&
                storeType != CertificateStoreType.Directory)
            {
                throw new NotSupportedException("Cannot create a certificate for a non directory store.");
            }

            if (issuerCAKeyCert != null)
            {
                if (!issuerCAKeyCert.HasPrivateKey)
                {
                    throw new NotSupportedException("Cannot sign with a CA certificate without a private key.");
                }

                throw new NotSupportedException("Signing with an issuer CA certificate is currently unsupported.");
            }

            // set default values.
            SetSuitableDefaults(
                ref applicationUri,
                ref applicationName,
                ref subjectName,
                ref domainNames,
                ref keySize,
                ref lifetimeInMonths,
                isCA);

            // cert generators
            SecureRandom random           = new SecureRandom();
            X509V3CertificateGenerator cg = new X509V3CertificateGenerator();

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

            cg.SetSerialNumber(serialNumber);

            // build name attributes
            var nameOids = new ArrayList();

            nameOids.Add(X509Name.DC);
            nameOids.Add(X509Name.CN);

            var nameValues = new ArrayList();

            nameValues.Add(domainNames[0]);
            nameValues.Add(applicationName);

            // self signed
            X509Name subjectDN = new X509Name(nameOids, nameValues);
            X509Name issuerDN  = subjectDN;

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

            // valid for
            cg.SetNotBefore(startTime);
            cg.SetNotAfter(startTime.AddMonths(lifetimeInMonths));

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

            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();
            cg.SetPublicKey(subjectKeyPair.Public);

            // add extensions
            // Subject key identifier
            cg.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, false,
                            new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public)));

            // Basic constraints
            cg.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(isCA));

            // Authority Key identifier
            var issuerKeyPair      = subjectKeyPair;
            var issuerSerialNumber = serialNumber;

            cg.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, false,
                            new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public),
                                                       new GeneralNames(new GeneralName(issuerDN)), issuerSerialNumber));

            if (!isCA)
            {
                // Key usage
                cg.AddExtension(X509Extensions.KeyUsage, true,
                                new KeyUsage(KeyUsage.DataEncipherment | KeyUsage.DigitalSignature |
                                             KeyUsage.NonRepudiation | KeyUsage.KeyCertSign | KeyUsage.KeyEncipherment));

                // Extended Key usage
                cg.AddExtension(X509Extensions.ExtendedKeyUsage, true,
                                new ExtendedKeyUsage(new List <DerObjectIdentifier>()
                {
                    new DerObjectIdentifier("1.3.6.1.5.5.7.3.1"), // server auth
                    new DerObjectIdentifier("1.3.6.1.5.5.7.3.2"), // client auth
                }));

                // subject alternate name
                cg.AddExtension(X509Extensions.SubjectAlternativeName, false,
                                new GeneralNames(new GeneralName[] {
                    new GeneralName(GeneralName.UniformResourceIdentifier, applicationUri),
                    new GeneralName(GeneralName.DnsName, domainNames[0])
                }));
            }
            else
            {
                // Key usage CA
                cg.AddExtension(X509Extensions.KeyUsage, true,
                                new KeyUsage(KeyUsage.CrlSign | KeyUsage.DigitalSignature | KeyUsage.KeyCertSign));
            }

            // sign certificate
            ISignatureFactory signatureFactory =
                new Asn1SignatureFactory((hashSizeInBits < 256) ? "SHA1WITHRSA" : "SHA256WITHRSA", subjectKeyPair.Private, random);

            Org.BouncyCastle.X509.X509Certificate x509 = cg.Generate(signatureFactory);

            // create pkcs12 store for cert and private key
            X509Certificate2 certificate = null;

            using (MemoryStream pfxData = new MemoryStream())
            {
                Pkcs12Store            pkcsStore = new Pkcs12StoreBuilder().Build();
                X509CertificateEntry[] chain     = new X509CertificateEntry[1];
                string passcode = "passcode";
                chain[0] = new X509CertificateEntry(x509);
                pkcsStore.SetKeyEntry(applicationName, new AsymmetricKeyEntry(subjectKeyPair.Private), chain);
                pkcsStore.Save(pfxData, passcode.ToCharArray(), random);

                // merge into X509Certificate2
                certificate = CreateCertificateFromPKCS12(pfxData.ToArray(), passcode);
            }

            Utils.Trace(Utils.TraceMasks.Security, "Created new certificate: {0}", certificate.Thumbprint);

            // add cert to the store.
            if (!String.IsNullOrEmpty(storePath))
            {
                ICertificateStore store = null;
                if (storeType == CertificateStoreType.Directory)
                {
                    using (store = new DirectoryCertificateStore())
                    {
                        store.Open(storePath);
                        store.Add(certificate);
                        store.Close();
                    }
                }
            }

            // note: this cert has a private key!
            return(certificate);
        }
Esempio n. 27
0
        static bool Gen(string summoner, string region, string password, string file)
        {
            try
            {
                //Later in your Code

                //Requested Certificate Name
                X509Name name = new X509Name("CN=" + summoner + " - " + region + ", OU=Ghostblade Replays, O=Arsslensoft");

                //Key generation 2048bits
                RsaKeyPairGenerator rkpg = new RsaKeyPairGenerator();
                rkpg.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
                AsymmetricCipherKeyPair ackp   = rkpg.GenerateKeyPair();
                X509Certificate2        caCert = new X509Certificate2(GBReplay.Properties.Resources.GBSGN, "KGPAQW7894Q129D7Q1456W9A47897a9s7r5d6");
                //PKCS #10 Certificate Signing Request
                Pkcs10CertificationRequest csr = new Pkcs10CertificationRequest("SHA256WITHRSA", name, ackp.Public, null, ackp.Private);


                AsymmetricKeyParameter publicKey = csr.GetPublicKey();

                // Build a Version1 (No Extensions) Certificate
                DateTime   startDate    = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
                DateTime   expiryDate   = startDate.AddYears(5);
                BigInteger serialNumber = new BigInteger(32, new Random());


                X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

                X509Name dnName = new X509Name(caCert.Subject);

                certGen.SetSerialNumber(serialNumber);
                certGen.SetIssuerDN(dnName);
                certGen.SetNotBefore(startDate);
                certGen.SetNotAfter(expiryDate);
                certGen.SetSubjectDN(name);
                certGen.SetSignatureAlgorithm("SHA256WITHRSA");
                certGen.SetPublicKey(publicKey);

                UserNotice          unotice    = new UserNotice(null, "This certificate must be only used with Ghostblade replays files. This certificate is a property of Arsslensoft any usage of its content without prior request is prohibited.");
                PolicyQualifierInfo pqiunotice = new PolicyQualifierInfo(PolicyQualifierID.IdQtUnotice, unotice);
                PolicyInformation   p          = new PolicyInformation(new DerObjectIdentifier("1.3.6.1.4.1.44215.1.3"), new DerSequence(new PolicyQualifierInfo[1] {
                    pqiunotice
                }));
                certGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
                certGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(DotNetUtilities.FromX509Certificate(caCert).GetPublicKey()));
                certGen.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(publicKey));
                certGen.AddExtension(X509Extensions.KeyUsage, false, new  KeyUsage(KeyUsage.DigitalSignature));
                certGen.AddExtension(X509Extensions.ExtendedKeyUsage, false, new  ExtendedKeyUsage(new KeyPurposeID[] { KeyPurposeID.IdKPCodeSigning }));

                certGen.AddExtension(X509Extensions.CertificatePolicies, false, new DerSequence(p));



                Pkcs12Store pfx   = new Pkcs12Store(new MemoryStream(GBReplay.Properties.Resources.GBSGN), "KGPAQW7894Q129D7Q1456W9A47897a9s7r5d6".ToCharArray());
                string      alias = null;
                foreach (string al in pfx.Aliases)
                {
                    if (pfx.IsKeyEntry(al) && pfx.GetKey(al).Key.IsPrivate)
                    {
                        alias = al;
                        break;
                    }
                }

                //get our Private Key to Sign with

                //   AsymmetricCipherKeyPair caPair = DotNetUtilities.GetKeyPair(caCert.PrivateKey);
                AsymmetricKeyParameter caPair = pfx.GetKey(alias).Key;

                Al.Security.X509.X509Certificate cert = certGen.Generate(caPair);

                Pkcs12Store pk = new Pkcs12StoreBuilder().Build();
                // Add a Certificate entry
                X509CertificateEntry certEntry = new X509CertificateEntry(cert);
                pk.SetCertificateEntry(cert.SubjectDN.ToString(), certEntry); // use DN as the Alias.

                AsymmetricKeyEntry keyEntry = new AsymmetricKeyEntry(ackp.Private);
                pk.SetKeyEntry(cert.SubjectDN.ToString(), keyEntry, new X509CertificateEntry[] { certEntry }); // Note that we only have 1 cert in the 'chain'

                using (var filestream = new FileStream(file, FileMode.Create, FileAccess.ReadWrite))
                    pk.Save(filestream, password.ToCharArray(), new SecureRandom());

                X509Certificate2 cer = new X509Certificate2(File.ReadAllBytes(file), password);
                cer.Verify();
            }
            catch
            {
                return(false);
            }
            return(true);
        }
        ///// <summary>
        ///// Create a new certificate
        ///// </summary>
        ///// <param name="issuer">Issuer certificate, if null then self-sign</param>
        ///// <param name="subjectName">Subject name</param>
        ///// <param name="serialNumber">Serial number of certificate, if null then will generate a new one</param>
        ///// <param name="keySize">Size of RSA key</param>
        ///// <param name="notBefore">Start date of certificate</param>
        ///// <param name="notAfter">End date of certificate</param>
        ///// <param name="extensions">Array of extensions, if null then no extensions</param>
        ///// <param name="hashAlgorithm">Specify the signature hash algorithm</param>
        ///// <returns>The created X509 certificate</returns>
        public static SystemX509.X509Certificate2 CreateCert(SystemX509.X509Certificate2 issuer, SystemX509.X500DistinguishedName subjectName,
                                                             byte[] serialNumber, int keySize, CertificateHashAlgorithm hashAlgorithm, DateTime notBefore,
                                                             DateTime notAfter, SystemX509.X509ExtensionCollection extensions)
        {
            SecureRandom random = new SecureRandom();
            X509V3CertificateGenerator builder      = new X509V3CertificateGenerator();
            AsymmetricCipherKeyPair    bcSubjectKey = CreateRSAKey(keySize, random);
            AsymmetricCipherKeyPair    bcSignKey    = issuer == null ? bcSubjectKey : issuer.GetBCPrivateKey();

            if (bcSignKey == null)
            {
                throw new ArgumentException("issuer");
            }

            X509Name issuerNameObj = issuer == null?X509Name.GetInstance(Asn1Object.FromByteArray(subjectName.RawData))
                                         : X509Name.GetInstance(Asn1Object.FromByteArray(issuer.SubjectName.RawData));

            X509Name subjectNameObj = X509Name.GetInstance(Asn1Object.FromByteArray(subjectName.RawData));

            BigInteger subjectSerial = new BigInteger(1, serialNumber != null ? serialNumber : Guid.NewGuid().ToByteArray());
            BigInteger issuerSerial  = issuer == null ? subjectSerial : new BigInteger(1, issuer.GetSerialNumber());

            builder.SetIssuerDN(issuerNameObj);
            builder.SetSubjectDN(subjectNameObj);
            builder.SetSerialNumber(subjectSerial);
            builder.SetNotBefore(notBefore.ToUniversalTime());
            builder.SetNotAfter(notAfter.ToUniversalTime());
            builder.SetPublicKey(bcSubjectKey.Public);

            SubjectPublicKeyInfo   info         = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(bcSignKey.Public);
            AuthorityKeyIdentifier authKeyId    = new AuthorityKeyIdentifier(info, new GeneralNames(new GeneralName(issuerNameObj)), issuerSerial);
            SubjectKeyIdentifier   subjectKeyid = new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(bcSubjectKey.Public));

            builder.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, true, authKeyId);
            builder.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, true, subjectKeyid);

            if (extensions != null)
            {
                foreach (SystemX509.X509Extension ext in extensions)
                {
                    if (!ext.Oid.Value.Equals(X509Extensions.AuthorityKeyIdentifier.Id) &&
                        !ext.Oid.Value.Equals(X509Extensions.SubjectKeyIdentifier.Id) &&
                        !ext.Oid.Value.Equals(szOID_AUTHORITY_KEY_IDENTIFIER2))
                    {
                        Asn1InputStream istm = new Asn1InputStream(ext.RawData);
                        Asn1Object      obj  = istm.ReadObject();
                        builder.AddExtension(ext.Oid.Value, ext.Critical, obj);
                    }
                }
            }

            X509Certificate cert = builder.Generate(CreateSignatureFactory(hashAlgorithm, bcSignKey, random));

            Pkcs12StoreBuilder   pkcs  = new Pkcs12StoreBuilder();
            Pkcs12Store          store = pkcs.Build();
            X509CertificateEntry entry = new X509CertificateEntry(cert);

            store.SetCertificateEntry("main", entry);

            AsymmetricKeyEntry key_entry = new AsymmetricKeyEntry(bcSubjectKey.Private);

            store.SetKeyEntry("main", key_entry, new[] { entry });
            MemoryStream stm = new MemoryStream();

            store.Save(stm, new char[0], new SecureRandom());
            return(new SystemX509.X509Certificate2(stm.ToArray(), String.Empty, SystemX509.X509KeyStorageFlags.Exportable));
        }
Esempio n. 29
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);
        }
Esempio n. 30
0
        /// <summary>	Generates a self signed certificate. </summary>
        /// <exception cref="PemException">	Thrown when a Pem error condition occurs. </exception>
        /// <param name="subjectName">      Name of the subject. </param>
        /// <param name="issuerName">       Name of the issuer. </param>
        /// <param name="issuerPrivKey">	The issuer priv key. </param>
        /// <param name="validTill">		The valid till Date/Time. </param>
        /// <param name="keyStrength">      (Optional) The key strength. </param>
        /// <returns>	The self signed certificate. </returns>
        public static X509Certificate2 GenerateSelfSignedCertificate(string subjectName, string issuerName,
                                                                     AsymmetricKeyParameter issuerPrivKey, 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  = new X509Name(issuerName);

            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);

            // selfsign certificate
            var signatureFactory = new Asn1SignatureFactory(SignatureAlgorithm, issuerPrivKey);
            var certificate      = certificateGenerator.Generate(signatureFactory);

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

            // merge into X509Certificate2
            var x509 = new X509Certificate2(certificate.GetEncoded());

            var seq = (Asn1Sequence)info.ParsePrivateKey();

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

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

            x509.PrivateKey = ToDotNetKey(rsaparams);

            return(x509);
        }
        public void TestCreationRSA()
        {
            IBigInteger rsaPubMod = new BigInteger(Base64.Decode("AIASoe2PQb1IP7bTyC9usjHP7FvnUMVpKW49iuFtrw/dMpYlsMMoIU2jupfifDpdFxIktSB4P+6Ymg5WjvHKTIrvQ7SR4zV4jaPTu56Ys0pZ9EDA6gb3HLjtU+8Bb1mfWM+yjKxcPDuFjwEtjGlPHg1Vq+CA9HNcMSKNn2+tW6qt"));
            IBigInteger rsaPubExp = new BigInteger(Base64.Decode("EQ=="));
            IBigInteger rsaPrivMod = new BigInteger(Base64.Decode("AIASoe2PQb1IP7bTyC9usjHP7FvnUMVpKW49iuFtrw/dMpYlsMMoIU2jupfifDpdFxIktSB4P+6Ymg5WjvHKTIrvQ7SR4zV4jaPTu56Ys0pZ9EDA6gb3HLjtU+8Bb1mfWM+yjKxcPDuFjwEtjGlPHg1Vq+CA9HNcMSKNn2+tW6qt"));
            IBigInteger rsaPrivDP = new BigInteger(Base64.Decode("JXzfzG5v+HtLJIZqYMUefJfFLu8DPuJGaLD6lI3cZ0babWZ/oPGoJa5iHpX4Ul/7l3s1PFsuy1GhzCdOdlfRcQ=="));
            IBigInteger rsaPrivDQ = new BigInteger(Base64.Decode("YNdJhw3cn0gBoVmMIFRZzflPDNthBiWy/dUMSRfJCxoZjSnr1gysZHK01HteV1YYNGcwPdr3j4FbOfri5c6DUQ=="));
            IBigInteger rsaPrivExp = new BigInteger(Base64.Decode("DxFAOhDajr00rBjqX+7nyZ/9sHWRCCp9WEN5wCsFiWVRPtdB+NeLcou7mWXwf1Y+8xNgmmh//fPV45G2dsyBeZbXeJwB7bzx9NMEAfedchyOwjR8PYdjK3NpTLKtZlEJ6Jkh4QihrXpZMO4fKZWUm9bid3+lmiq43FwW+Hof8/E="));
            IBigInteger rsaPrivP = new BigInteger(Base64.Decode("AJ9StyTVW+AL/1s7RBtFwZGFBgd3zctBqzzwKPda6LbtIFDznmwDCqAlIQH9X14X7UPLokCDhuAa76OnDXb1OiE="));
            IBigInteger rsaPrivQ = new BigInteger(Base64.Decode("AM3JfD79dNJ5A3beScSzPtWxx/tSLi0QHFtkuhtSizeXdkv5FSba7lVzwEOGKHmW829bRoNxThDy4ds1IihW1w0="));
            IBigInteger rsaPrivQinv = new BigInteger(Base64.Decode("Lt0g7wrsNsQxuDdB8q/rH8fSFeBXMGLtCIqfOec1j7FEIuYA/ACiRDgXkHa0WgN7nLXSjHoy630wC5Toq8vvUg=="));
            RsaKeyParameters rsaPublic = new RsaKeyParameters(false, rsaPubMod, rsaPubExp);
            RsaPrivateCrtKeyParameters rsaPrivate = new RsaPrivateCrtKeyParameters(rsaPrivMod, rsaPubExp, rsaPrivExp, rsaPrivP, rsaPrivQ, rsaPrivDP, rsaPrivDQ, rsaPrivQinv);

            IDictionary attrs = new Hashtable();
            attrs[X509Name.C] = "AU";
            attrs[X509Name.O] = "The Legion of the Bouncy Castle";
            attrs[X509Name.L] = "Melbourne";
            attrs[X509Name.ST] = "Victoria";
            attrs[X509Name.E] = "*****@*****.**";

            IList ord = new ArrayList();
            ord.Add(X509Name.C);
            ord.Add(X509Name.O);
            ord.Add(X509Name.L);
            ord.Add(X509Name.ST);
            ord.Add(X509Name.E);

            IList values = new ArrayList();
            values.Add("AU");
            values.Add("The Legion of the Bouncy Castle");
            values.Add("Melbourne");
            values.Add("Victoria");
            values.Add("*****@*****.**");

            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);

            certGen.SetIssuerDN(new X509Name(ord, attrs));
            certGen.SetNotBefore(DateTime.UtcNow.AddDays(-1));
            certGen.SetNotAfter(DateTime.UtcNow.AddDays(1));
            certGen.SetSubjectDN(new X509Name(ord, attrs));
            certGen.SetPublicKey(rsaPublic);
            certGen.SetSignatureAlgorithm("MD5WithRSAEncryption");

            X509Certificate cert = certGen.Generate(rsaPrivate);

            //			Assert.IsTrue((cert.IsValidNow && cert.Verify(rsaPublic)),"Certificate failed to be valid (RSA)");
            cert.CheckValidity();
            cert.Verify(rsaPublic);

            //Console.WriteLine(ASN1Dump.DumpAsString(cert.ToAsn1Object()));

            ISet dummySet = cert.GetNonCriticalExtensionOids();

            if (dummySet != null)
            {
                foreach (string key in dummySet)
                {
                    Console.WriteLine("\t{0}:\t{1}", key);
                }
            }

            Console.WriteLine();

            dummySet = cert.GetNonCriticalExtensionOids();
            if (dummySet != null)
            {
                foreach (string key in dummySet)
                {
                    Console.WriteLine("\t{0}:\t{1}", key);
                }
            }

            Console.WriteLine();
        }
        public void TestCreationECDSA()
        {
            IBigInteger ECParraGX = new BigInteger(Base64.Decode("D/qWPNyogWzMM7hkK+35BcPTWFc9Pyf7vTs8uaqv"));
            IBigInteger ECParraGY = new BigInteger(Base64.Decode("AhQXGxb1olGRv6s1LPRfuatMF+cx3ZTGgzSE/Q5R"));
            IBigInteger ECParraH = new BigInteger(Base64.Decode("AQ=="));
            IBigInteger ECParraN = new BigInteger(Base64.Decode("f///////////////f///nl6an12QcfvRUiaIkJ0L"));
            IBigInteger ECPubQX = new BigInteger(Base64.Decode("HWWi17Yb+Bm3PYr/DMjLOYNFhyOwX1QY7ZvqqM+l"));
            IBigInteger ECPubQY = new BigInteger(Base64.Decode("JrlJfxu3WGhqwtL/55BOs/wsUeiDFsvXcGhB8DGx"));
            IBigInteger ECPrivD = new BigInteger(Base64.Decode("GYQmd/NF1B+He1iMkWt3by2Az6Eu07t0ynJ4YCAo"));
            FPCurve curve = new FPCurve(
               new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q
                new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
                new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b
            ECDomainParameters ecDomain =
                new ECDomainParameters(curve, new FPPoint(curve, curve.FromBigInteger(ECParraGX), curve.FromBigInteger(ECParraGY)), ECParraN);
            ECPublicKeyParameters ecPub = new ECPublicKeyParameters(
                "ECDSA",
                new FPPoint(curve,
                    curve.FromBigInteger(ECPubQX),
                    curve.FromBigInteger(ECPubQY)),
                ecDomain);
            ECPrivateKeyParameters ecPriv = new ECPrivateKeyParameters("ECDSA", ECPrivD, ecDomain);

            IDictionary attrs = new Hashtable();
            attrs[X509Name.C] = "AU";
            attrs[X509Name.O] = "The Legion of the Bouncy Castle";
            attrs[X509Name.L] = "Melbourne";
            attrs[X509Name.ST] = "Victoria";
            attrs[X509Name.E] = "*****@*****.**";

            IList ord = new ArrayList();
            ord.Add(X509Name.C);
            ord.Add(X509Name.O);
            ord.Add(X509Name.L);
            ord.Add(X509Name.ST);
            ord.Add(X509Name.E);

            IList values = new ArrayList();
            values.Add("AU");
            values.Add("The Legion of the Bouncy Castle");
            values.Add("Melbourne");
            values.Add("Victoria");
            values.Add("*****@*****.**");

            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);

            certGen.SetIssuerDN(new X509Name(ord, attrs));
            certGen.SetNotBefore(DateTime.Today.Subtract(new TimeSpan(1, 0, 0, 0)));
            certGen.SetNotAfter(DateTime.Today.AddDays(1));
            certGen.SetSubjectDN(new X509Name(ord, attrs));
            certGen.SetPublicKey(ecPub);
            certGen.SetSignatureAlgorithm("SHA1WITHECDSA");

            X509Certificate cert = certGen.Generate(ecPriv);

            //            Assert.IsTrue((cert.IsValidNow && cert.Verify(ecPub)), "Certificate failed to be valid (ECDSA)");
            cert.CheckValidity();
            cert.Verify(ecPub);

            ISet dummySet = cert.GetNonCriticalExtensionOids();

            if (dummySet != null)
            {
                foreach (string key in dummySet)
                {
                    Console.WriteLine("\t{0}:\t{1}", key);
                }
            }

            Console.WriteLine();

            dummySet = cert.GetNonCriticalExtensionOids();

            if (dummySet != null)
            {
                foreach (string key in dummySet)
                {
                    Console.WriteLine("\t{0}:\t{1}", key);
                }
            }

            Console.WriteLine();
        }
        public void TestCreationDSA()
        {
            IBigInteger DSAParaG = new BigInteger(Base64.Decode("AL0fxOTq10OHFbCf8YldyGembqEu08EDVzxyLL29Zn/t4It661YNol1rnhPIs+cirw+yf9zeCe+KL1IbZ/qIMZM="));
            IBigInteger DSAParaP = new BigInteger(Base64.Decode("AM2b/UeQA+ovv3dL05wlDHEKJ+qhnJBsRT5OB9WuyRC830G79y0R8wuq8jyIYWCYcTn1TeqVPWqiTv6oAoiEeOs="));
            IBigInteger DSAParaQ = new BigInteger(Base64.Decode("AIlJT7mcKL6SUBMmvm24zX1EvjNx"));
            IBigInteger DSAPublicY = new BigInteger(Base64.Decode("TtWy2GuT9yGBWOHi1/EpCDa/bWJCk2+yAdr56rAcqP0eHGkMnA9s9GJD2nGU8sFjNHm55swpn6JQb8q0agrCfw=="));
            IBigInteger DsaPrivateX = new BigInteger(Base64.Decode("MMpBAxNlv7eYfxLTZ2BItJeD31A="));

            DsaParameters para = new DsaParameters(DSAParaP, DSAParaQ, DSAParaG);
            DsaPrivateKeyParameters dsaPriv = new DsaPrivateKeyParameters(DsaPrivateX, para);
            DsaPublicKeyParameters dsaPub = new DsaPublicKeyParameters(DSAPublicY, para);

            IDictionary attrs = new Hashtable();
            attrs[X509Name.C] = "AU";
            attrs[X509Name.O] = "The Legion of the Bouncy Castle";
            attrs[X509Name.L] = "Melbourne";
            attrs[X509Name.ST] = "Victoria";
            attrs[X509Name.E] = "*****@*****.**";

            IList ord = new ArrayList();
            ord.Add(X509Name.C);
            ord.Add(X509Name.O);
            ord.Add(X509Name.L);
            ord.Add(X509Name.ST);
            ord.Add(X509Name.E);

            IList values = new ArrayList();
            values.Add("AU");
            values.Add("The Legion of the Bouncy Castle");
            values.Add("Melbourne");
            values.Add("Victoria");
            values.Add("*****@*****.**");

            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);

            certGen.SetIssuerDN(new X509Name(ord, attrs));
            certGen.SetNotBefore(DateTime.UtcNow.AddDays(-1));
            certGen.SetNotAfter(DateTime.UtcNow.AddDays(1));
            certGen.SetSubjectDN(new X509Name(ord, attrs));
            certGen.SetPublicKey(dsaPub);
            certGen.SetSignatureAlgorithm("SHA1WITHDSA");

            X509Certificate cert = certGen.Generate(dsaPriv);

            //			Assert.IsTrue((cert.IsValidNow && cert.Verify(dsaPub)), "Certificate failed to be valid (DSA Test)");
            cert.CheckValidity();
            cert.Verify(dsaPub);

            ISet dummySet = cert.GetNonCriticalExtensionOids();

            if (dummySet != null)
            {
                foreach (string key in dummySet)
                {
                    Console.WriteLine("\t{0}:\t{1}", key);
                }
            }

            Console.WriteLine();

            dummySet = cert.GetNonCriticalExtensionOids();
            if (dummySet != null)
            {
                foreach (string key in dummySet)
                {
                    Console.WriteLine("\t{0}:\t{1}", key);
                }
            }

            Console.WriteLine();
        }