Example #1
0
        /// <summary>
        /// Generates the certificate. This should be used for root/self signed certfificates as they will have no issuer.
        /// This also returns the private key of the certificate generated.
        /// </summary>
        /// <returns></returns>
        public X509Certificate GenerateRootWithPrivateKey(out AsymmetricCipherKeyPair keyPair)
        {
            keyPair = this.keyPair;
            ISignatureFactory signatureFactory = new Asn1SignatureFactory(signatureAlgorithm, keyPair.Private, SecureRandom);

            return(certificateGenerator.Generate(signatureFactory));
        }
        private CertificateDto CreateCertificate(CertificateCreateDto certificateCreateDto,
                                                 AsymmetricCipherKeyPair rsaKeyPair,
                                                 SecureRandom random)
        {
            ValidateCreateDto(certificateCreateDto);

            var certificateGenerator = new X509V3CertificateGenerator();
            var signatureFactory     = new Asn1SignatureFactory(_signatureAlgorithm, rsaKeyPair.Private, random);
            var serialNumber         = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            var subject = CreateSubject(certificateCreateDto);

            certificateGenerator.SetIssuerDN(subject);
            certificateGenerator.SetSubjectDN(subject);
            certificateGenerator.SetSerialNumber(serialNumber);
            certificateGenerator.SetNotBefore(certificateCreateDto.NotBefore);
            certificateGenerator.SetNotAfter(certificateCreateDto.NotAfter);
            certificateGenerator.SetPublicKey(rsaKeyPair.Public);

            var certificate = certificateGenerator.Generate(signatureFactory);

            return(new CertificateDto
            {
                Certificate = new SystemX509.X509Certificate2(certificate.GetEncoded()),
                KeyPair = rsaKeyPair
            });
        }
Example #3
0
        private static X509Certificate GenerateCert(string signatureAlgorithmName,
                                                    AsymmetricKeyParameter issuerPrivateKey,
                                                    X509Name issuerDN,
                                                    AsymmetricKeyParameter subjectPublicKey,
                                                    X509Name subjectDN,
                                                    X509Extensions subjectExtensions,
                                                    DateTime start,
                                                    int days)
        {
            ISignatureFactory          signatureFactory = new Asn1SignatureFactory(signatureAlgorithmName, issuerPrivateKey, Common.ThreadSecureRandom.Value);
            BigInteger                 sn        = new BigInteger(128, Common.ThreadSecureRandom.Value);
            X509V3CertificateGenerator generator = new X509V3CertificateGenerator();

            generator.SetSerialNumber(sn);
            generator.SetIssuerDN(issuerDN);
            generator.SetPublicKey(subjectPublicKey);
            generator.SetSubjectDN(subjectDN);
            if (subjectExtensions != null)
            {
                foreach (DerObjectIdentifier oid in subjectExtensions.ExtensionOids)
                {
                    X509Extension extension = subjectExtensions.GetExtension(oid);
                    generator.AddExtension(oid, extension.IsCritical, extension.GetParsedValue());
                }
            }
            generator.SetNotBefore(start);
            generator.SetNotAfter(start.AddDays(days));
            return(generator.Generate(signatureFactory));
        }
        private static X509Certificate GenerateCertificate(Org.BouncyCastle.Security.SecureRandom random,
                                                           string subjectName,
                                                           AsymmetricCipherKeyPair subjectKeyPair,
                                                           BigInteger subjectSerialNumber,
                                                           string[] subjectAlternativeNames,
                                                           string issuerName,
                                                           AsymmetricCipherKeyPair issuerKeyPair,
                                                           BigInteger issuerSerialNumber,
                                                           bool isCertificateAuthority,
                                                           KeyPurposeID[] usages,
                                                           int expiresIn)
        {
            var certificateGenerator = new X509V3CertificateGenerator();

            certificateGenerator.SetSerialNumber(subjectSerialNumber);

            // Set the signature algorithm. This is used to generate the thumbprint which is then signed
            // with the issuer's private key. We'll use SHA-256, which is (currently) considered fairly strong.
            const string signatureAlgorithm = "SHA256WithRSA";

            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);

            var issuerDN = new X509Name(issuerName);

            certificateGenerator.SetIssuerDN(issuerDN);

            // Note: The subject can be omitted if you specify a subject alternative name (SAN).
            var subjectDN = new X509Name(subjectName);

            certificateGenerator.SetSubjectDN(subjectDN);

            // Our certificate needs valid from/to values.
            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = notBefore.AddYears(expiresIn);

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

            // The subject's public key goes in the certificate.
            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            certificateGenerator.AddAuthorityKeyIdentifier(issuerDN, issuerKeyPair, issuerSerialNumber);
            certificateGenerator.AddSubjectKeyIdentifier(subjectKeyPair);
            certificateGenerator.AddBasicConstraints(isCertificateAuthority);

            if (usages != null && usages.Any())
            {
                certificateGenerator.AddExtendedKeyUsage(usages);
            }

            if (subjectAlternativeNames != null && subjectAlternativeNames.Any())
            {
                certificateGenerator.AddSubjectAlternativeNames(subjectAlternativeNames);
            }

            // The certificate is signed with the issuer's private key.
            var certificate = certificateGenerator.Generate(issuerKeyPair.Private, random);

            return(certificate);
        }
Example #5
0
        public static byte[] GenerateRootCACertificate(CertificateSubject subject, DateTime startDate, DateTime expiryDate, SignatureHashAlgorithm signatureAlgorithm, TCertificateFormat certificateFormat)
        {
            byte[] result = null;

            SecureRandom random = Porthelp.CreateSecureRandom();
            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();

            AddStandardCertificateInfo(certificateGenerator, random, subject, subject, startDate, expiryDate);
            AsymmetricCipherKeyPair subjectKeyPair = GenerateKeys(certificateGenerator, random, signatureAlgorithm);

            certificateGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
            certificateGenerator.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyCertSign));
            byte[] subjectKeyID = new byte[20];
            random.NextBytes(subjectKeyID, 0, 20);
            certificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(subjectKeyID));
            certificateGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(subjectKeyID));

            string algorithm = GetAlgorithm(signatureAlgorithm);

            // selfsign certificate
            Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(new Asn1SignatureFactory(algorithm, subjectKeyPair.Private, random));

            result = ExportCertificate(certificate, subjectKeyPair, certificateFormat);

            return(result);
        }
Example #6
0
        private static void Teste(AsymmetricCipherKeyPair keys)
        {
            string certSubjectName = "UShadow_RSA";
            var    certName        = new X509Name("CN=" + certSubjectName);
            var    serialNo        = Org.BouncyCastle.Math.BigInteger.ProbablePrime(120, new Random());


            X509V3CertificateGenerator gen2 = new X509V3CertificateGenerator();

            gen2.SetSerialNumber(serialNo);
            gen2.SetSubjectDN(certName);
            gen2.SetIssuerDN(new X509Name(true, "CN=UShadow"));
            gen2.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(30, 0, 0, 0)));
            gen2.SetNotAfter(DateTime.Now.AddYears(2));
            gen2.SetSignatureAlgorithm("sha256WithRSA");

            gen2.SetPublicKey(keys.Public);

            Org.BouncyCastle.X509.X509Certificate newCert = gen2.Generate(keys.Private);

            Pkcs12Store store = new Pkcs12StoreBuilder().Build();

            X509CertificateEntry certEntry = new X509CertificateEntry(newCert);

            store.SetCertificateEntry(newCert.SubjectDN.ToString(), certEntry);

            AsymmetricKeyEntry keyEntry = new AsymmetricKeyEntry(keys.Private);

            store.SetKeyEntry(newCert.SubjectDN.ToString() + "_key", keyEntry, new X509CertificateEntry[] { certEntry });
        }
Example #7
0
        public static X509Certificate2 GenerateSelfSignedCert(string subjectName)
        {
            var keyGenerator = new RsaKeyPairGenerator();
            var random       = new SecureRandom(new CryptoApiRandomGenerator());

            keyGenerator.Init(new KeyGenerationParameters(random, 1024));

            AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair();

            var        certName      = new X509Name($"CN={subjectName}");
            BigInteger serialNo      = BigInteger.ProbablePrime(120, random);
            var        certGenerator = new X509V3CertificateGenerator();

            certGenerator.SetSerialNumber(serialNo);
            certGenerator.SetSubjectDN(certName);
            certGenerator.SetIssuerDN(certName);
            certGenerator.SetNotAfter(DateTime.Now.AddYears(10));
            certGenerator.SetNotBefore(DateTime.Now.Subtract(TimeSpan.FromDays(2)));
            certGenerator.SetPublicKey(keyPair.Public);

            var signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", keyPair.Private, random);

            BCX509.X509Certificate bcCert = certGenerator.Generate(signatureFactory);

            return(new X509Certificate2(DotNetUtilities.ToX509Certificate(bcCert)));
        }
Example #8
0
        public X509Certificate Generate(
            X509Name issuer,
            AsymmetricKeyParameter issuerPrivate,
            AsymmetricKeyParameter subjectPublic)
        {
            ISignatureFactory signatureFactory;

            if (issuerPrivate is ECPrivateKeyParameters)
            {
                signatureFactory = new Asn1SignatureFactory(
                    X9ObjectIdentifiers.ECDsaWithSha256.ToString(),
                    issuerPrivate);
            }
            else
            {
                signatureFactory = new Asn1SignatureFactory(
                    PkcsObjectIdentifiers.Sha256WithRsaEncryption.ToString(),
                    issuerPrivate);
            }

            var certGenerator = new X509V3CertificateGenerator();

            certGenerator.SetIssuerDN(issuer);
            certGenerator.SetSubjectDN(issuer);
            certGenerator.SetSerialNumber(BigInteger.ValueOf(1));
            certGenerator.SetNotAfter(DateTime.UtcNow.AddHours(1));
            certGenerator.SetNotBefore(DateTime.UtcNow);
            certGenerator.SetPublicKey(subjectPublic);
            return(certGenerator.Generate(signatureFactory));
        }
Example #9
0
 private static X509Certificate GenerateCertificateAsn1(
     this X509V3CertificateGenerator certificateGenerator,
     AsymmetricCipherKeyPair issuerKeyPair,
     SecureRandom random)
 {
     return(certificateGenerator.Generate(new Asn1SignatureFactory("SHA256WithRSA", issuerKeyPair.Private, random)));
 }
        public static X509Certificate2 CreateCertificate(X509Name subjectDN, DateTime effectiveDate, DateTime expirationDate, AsymmetricCipherKeyPair keyPair, X509Name issuerDN = null,
                                                         AsymmetricKeyParameter signingKey = null, Action <X509V3CertificateGenerator, BigInteger> extend = null)
        {
            if (issuerDN == null)
            {
                issuerDN = subjectDN;
            }

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

            certGen.SetSerialNumber(serialNumber);
            certGen.SetIssuerDN(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(subjectDN);
            certGen.SetPublicKey(keyPair.Public);
            certGen.SetSignatureAlgorithm(SIGNATURE_ALGORITHM);

            extend?.Invoke(certGen, serialNumber);

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

            X509Certificate2 dotNetCert = new X509Certificate2(bcCert.GetEncoded());

            return(dotNetCert);
        }
Example #11
0
        private static X509Certificate CreateCertificate(string subjectName, DateTime startDate, DateTime expiryDate, BigInteger serialNumber, AsymmetricKeyParameter parentPrivateKey, X509Certificate parentCert, AsymmetricCipherKeyPair keysToSign)
        {
            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(serialNumber);
            if (parentCert != null)
            {
                certGen.SetIssuerDN(parentCert.SubjectDN);
            }
            else//is CA cert
            {
                certGen.SetIssuerDN(new X509Name("CN=" + subjectName));
            }
            certGen.SetNotBefore(startDate);
            certGen.SetNotAfter(expiryDate);
            certGen.SetSubjectDN(new X509Name("CN=" + subjectName));
            certGen.SetPublicKey(keysToSign.Public);

            if (parentCert == null) //is CA cert
            {
                certGen.AddExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(true));
            }
            else
            {
                certGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(parentCert));
            }

            certGen.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keysToSign.Public));

            X509Certificate cert = certGen.Generate(new Asn1SignatureFactory("SHA512WITHRSA", parentPrivateKey));

            return(cert);
        }
Example #12
0
        public static X509Certificate2 GenerateCertificate(string certName)
        {
            var keypairgen      = new RsaKeyPairGenerator();
            var randomGenerator = new CustomCryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            keypairgen.Init(new KeyGenerationParameters(random, 1024));

            var keypair = keypairgen.GenerateKeyPair();

            var gen = new X509V3CertificateGenerator();

            var CN = new X509Name("CN=" + certName);
            var SN = Org.BouncyCastle.Math.BigInteger.ProbablePrime(120, new Random());

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

            gen.SetSerialNumber(SN);
            gen.SetPublicKey(keypair.Private);
            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 newCert = gen.Generate(signatureFactory);

            return(new X509Certificate2(newCert.GetEncoded()));
        }
        public X509Certificate Build(AsymmetricKeyParameter privateKey)
        {
            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);

            if (Issuer != null)
            {
                certGen.SetIssuerDN(Issuer);
            }
            else
            {
                certGen.SetIssuerDN(new X509Name(ord, attrs));
            }


            certGen.SetNotBefore(NotBefore);
            certGen.SetNotAfter(NotAfter);

            if (Subject != null)
            {
                certGen.SetSubjectDN(Subject);
            }
            else
            {
                certGen.SetSubjectDN(new X509Name(ord, attrs));
            }


            certGen.SetPublicKey(PublicKey);
            certGen.SetSignatureAlgorithm(SignatureAlgorithm);

            return(certGen.Generate(privateKey));
        }
Example #14
0
        public static X509Certificate2 genCert()
        {
            var gen        = new X509V3CertificateGenerator();
            var keypairgen = new RsaKeyPairGenerator();

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

            var keypair = keypairgen.GenerateKeyPair();
            var random  = new Random();

            random.Next(); random.Next(); random.Next(); random.Next(); random.Next(); random.Next(); random.Next();

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

            gen.SetSerialNumber(SN);
            gen.SetIssuerDN(CN);
            gen.SetSubjectDN(CN);
            gen.SetNotBefore(DateTime.UtcNow.Subtract(new TimeSpan(5, 0, 0)));
            gen.SetNotAfter(DateTime.UtcNow.AddYears(5));
            gen.SetPublicKey(keypair.Public);

            var gcert = gen.Generate(new Asn1SignatureFactory("MD5WithRSA", keypair.Private));

            Console.WriteLine($"Keypair results: Public: {keypair.Public}\nPrivate: {keypair.Private}");

            var cert = new X509Certificate2(gcert.GetEncoded(), "irclib", X509KeyStorageFlags.Exportable);

            Console.WriteLine($"Public Key: {cert.PublicKey}\nPrivate Key present: {cert.HasPrivateKey} at creation time.");

            return(cert);
        }
Example #15
0
        // 自己署名証明書の作成
        public Certificate(PrivKey selfSignKey, CertificateOptions options)
        {
            X509Name name = options.GenerateName();
            X509V3CertificateGenerator gen = new X509V3CertificateGenerator();

            gen.SetSerialNumber(new BigInteger(options.Serial.ToArray()));
            gen.SetIssuerDN(name);
            gen.SetSubjectDN(name);
            gen.SetNotBefore(DateTime.Now.AddDays(-1));
            gen.SetNotAfter(options.Expires.UtcDateTime);
            gen.SetPublicKey(selfSignKey.PublicKey.PublicKeyData);

            X509Extension extConst = new X509Extension(true, new DerOctetString(new BasicConstraints(true)));

            gen.AddExtension(X509Extensions.BasicConstraints, true, extConst.GetParsedValue());

            X509Extension extBasicUsage = new X509Extension(false, new DerOctetString(new KeyUsage(options.KeyUsages)));

            gen.AddExtension(X509Extensions.KeyUsage, false, extBasicUsage.GetParsedValue());

            X509Extension extExtendedUsage = new X509Extension(false, new DerOctetString(new ExtendedKeyUsage(options.ExtendedKeyUsages)));

            gen.AddExtension(X509Extensions.ExtendedKeyUsage, false, extExtendedUsage.GetParsedValue());

            X509Extension altName = new X509Extension(false, new DerOctetString(options.GenerateAltNames()));

            gen.AddExtension(X509Extensions.SubjectAlternativeName, false, altName.GetParsedValue());

            this.CertData = gen.Generate(new Asn1SignatureFactory(options.GetSignatureAlgorithmOid(), selfSignKey.PrivateKeyData.Private, PkiUtil.NewSecureRandom()));

            InitFields();
        }
Example #16
0
        private X509Certificate GenerateX509Certificate(AsymmetricCipherKeyPair KeyPair, DateTime NotBefore, DateTime NotAfter, string DN)
        {
            var certificateGenerator = new X509V3CertificateGenerator();

            // Assign public key
            certificateGenerator.SetPublicKey(KeyPair.Public);
            // Set serial number
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);
            // Set validity timeframe
            certificateGenerator.SetNotBefore(NotBefore);
            certificateGenerator.SetNotAfter(NotAfter);
            // set subject and issuer DN
            var subjectDN = new X509Name(DN);
            var issuerDN  = subjectDN;

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);
            // Add netscape-comment extension
            certificateGenerator.AddExtension(NetscapeCommentExtOid, false, new DerUtf8String("Generated by Wnmp"));
            // Sign cert with SHA256
            var signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", KeyPair.Private, random);

            return(certificateGenerator.Generate(signatureFactory));
        }
Example #17
0
        public static X509Certificate2 CreateCertificateAuthority(string caName, int keyStrength)
        {
            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=" + caName);
            var SN = BigInteger.ProbablePrime(120, random);

            certificateGenerator.SetSerialNumber(SN);
            certificateGenerator.SetSubjectDN(CN);
            certificateGenerator.SetIssuerDN(CN);
            certificateGenerator.SetNotAfter(DateTime.MaxValue);
            certificateGenerator.SetNotBefore(DateTime.UtcNow.Subtract(new TimeSpan(2, 0, 0, 0)));
            certificateGenerator.SetPublicKey(keypair.Public);
            certificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keypair.Public));
            certificateGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));

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

            var certificate = certificateGenerator.Generate(signatureFactory);

            byte[] pkcs12Bytes = DotNetUtilities.ToX509Certificate(certificate).Export(X509ContentType.Pkcs12, Settings.CertificatePassword);

            var certificate2 = new X509Certificate2(pkcs12Bytes, Settings.CertificatePassword);

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

            return(certificate2);
        }
Example #18
0
        public static byte[] GenerateRootCACertificate(CertificateSubject subject, DateTime startDate, DateTime expiryDate,
                                                       SignatureHashAlgorithm signatureAlgorithm, TCertificateFormat certificateFormat)
        {
            if (subject == null)
            {
                throw new ArgumentNullException(nameof(subject));
            }

            if (signatureAlgorithm == null)
            {
                throw new ArgumentNullException(nameof(signatureAlgorithm));
            }

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

            AddStandardCertificateInfo(certificateGenerator, random, subject, subject, startDate, expiryDate);
            var subjectKeyPair = GenerateKeys(certificateGenerator, random, signatureAlgorithm);

            certificateGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
            certificateGenerator.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyCertSign));
            var subjectKeyID = new byte[20];

            random.NextBytes(subjectKeyID, 0, 20);
            certificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(subjectKeyID));
            certificateGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(subjectKeyID));

            var algorithm = GetAlgorithm(signatureAlgorithm);
            // selfsign certificate
            var certificate = certificateGenerator.Generate(new Asn1SignatureFactory(algorithm, subjectKeyPair.Private, random));

            return(ExportCertificate(certificate, subjectKeyPair, certificateFormat));
        }
Example #19
0
        public static X509Certificate2 GenerateCertificate(
            string issuer, string subject,
            AsymmetricAlgorithm issuerPrivate,
            AsymmetricAlgorithm subjectPublic)
        {
            ISignatureFactory signatureFactory = new Asn1SignatureFactory(
                PkcsObjectIdentifiers.Sha256WithRsaEncryption.ToString(),
                DotNetUtilities.GetRsaKeyPair((RSA)issuerPrivate).Private);

            var certGenerator = new X509V3CertificateGenerator();

            certGenerator.SetIssuerDN(new X509Name(issuer));
            if (!string.IsNullOrEmpty(subject))
            {
                certGenerator.SetSubjectDN(new X509Name(subject));
            }
            else
            {
                certGenerator.SetSubjectDN(X509Name.GetInstance(Asn1Object.FromByteArray(new byte[] { 0x30, 0x00 })));
            }
            certGenerator.SetSerialNumber(BigInteger.ValueOf(LongRandom(0, 1000000000, new Random())));
            certGenerator.SetNotAfter(DateTime.UtcNow.AddHours(1));
            certGenerator.SetNotBefore(DateTime.UtcNow);
            certGenerator.SetPublicKey(DotNetUtilities.GetRsaPublicKey((RSA)subjectPublic));
            var rawData = certGenerator.Generate(signatureFactory).GetEncoded();

            return(new X509Certificate2(rawData));
        }
Example #20
0
        public static Org.BouncyCastle.X509.X509Certificate CreateCert(String cn,
                                                                       AsymmetricKeyParameter pubKey, AsymmetricKeyParameter privKey)
        {
            Hashtable attrs = new Hashtable();

            attrs.Add(X509Name.CN, cn);

            ArrayList ord = new ArrayList(attrs.Keys);

            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

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

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

            cert.CheckValidity(DateTime.UtcNow);

            cert.Verify(pubKey);

            return(cert);
        }
Example #21
0
        public static X509Certificate MakeCertificate(IAsymmetricCipherKeyPair _subKP,
                                                      string _subDN, IAsymmetricCipherKeyPair _issKP, string _issDN, string algorithm, bool _ca)
        {
            IAsymmetricKeyParameter _subPub  = _subKP.Public;
            IAsymmetricKeyParameter _issPriv = _issKP.Private;
            IAsymmetricKeyParameter _issPub  = _issKP.Public;

            X509V3CertificateGenerator _v3CertGen = new X509V3CertificateGenerator();

            _v3CertGen.Reset();
            _v3CertGen.SetSerialNumber(allocateSerialNumber());
            _v3CertGen.SetIssuerDN(new X509Name(_issDN));
            _v3CertGen.SetNotBefore(DateTime.UtcNow);
            _v3CertGen.SetNotAfter(DateTime.UtcNow.AddDays(100));
            _v3CertGen.SetSubjectDN(new X509Name(_subDN));
            _v3CertGen.SetPublicKey(_subPub);
            _v3CertGen.SetSignatureAlgorithm(algorithm);

            _v3CertGen.AddExtension(X509Extensions.SubjectKeyIdentifier, false,
                                    createSubjectKeyId(_subPub));

            _v3CertGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false,
                                    createAuthorityKeyId(_issPub));

            _v3CertGen.AddExtension(X509Extensions.BasicConstraints, false,
                                    new BasicConstraints(_ca));

            X509Certificate _cert = _v3CertGen.Generate(_issPriv);

            _cert.CheckValidity(DateTime.UtcNow);
            _cert.Verify(_issPub);

            return(_cert);
        }
Example #22
0
        static X509Certificate2 GenerateCertificate(string certName)
        {
            var keypairgen = new RsaKeyPairGenerator();

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

            var keypair = keypairgen.GenerateKeyPair();

            var gen = new X509V3CertificateGenerator();

            var CN = new X509Name("CN=" + certName);
            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("SHA256WithRSA");
            gen.SetPublicKey(keypair.Public);

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

            X509Certificate2 cert = new X509Certificate2(DotNetUtilities.ToX509Certificate((Org.BouncyCastle.X509.X509Certificate)newCert));

            cert.PrivateKey = DotNetUtilities.ToRSA((RsaPrivateCrtKeyParameters)keypair.Private);
            return(cert);
        }
        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);

            SetBasicConstraints(cert, true);

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

            return(AsForm(x509, key, Random));
        }
Example #24
0
        private void GenerateCertificate()
        {
            // Generate key pair
            RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator();

            keyPairGenerator.Init(new KeyGenerationParameters(SecureRandom, 2048));
            AsymmetricCipherKeyPair keyPair = keyPairGenerator.GenerateKeyPair();

            Key = keyPair.Private;

            // Generate certificate
            DateTime   startDate    = DateTime.Now;
            DateTime   expiryDate   = startDate.AddYears(20);
            BigInteger serialNumber = BigInteger.ProbablePrime(120, new Random());
            X509Name   commonName   = new X509Name("CN=NVIDIA GameStream Client");
            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();

            certificateGenerator.SetSerialNumber(BigInteger.ValueOf(DateTime.Now.Millisecond));
            certificateGenerator.SetSubjectDN(commonName);
            certificateGenerator.SetIssuerDN(commonName);
            certificateGenerator.SetNotAfter(expiryDate);
            certificateGenerator.SetNotBefore(startDate);
            certificateGenerator.SetPublicKey(keyPair.Public);

            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA1WithRSA", Key, SecureRandom);

            Certificate = certificateGenerator.Generate(signatureFactory);
        }
Example #25
0
        /// <summary>
        /// Generate a cert/key pair
        /// </summary>
        private void GenerateCertKeyPair()
        {
            // Generate RSA key pair
            RsaKeyPairGenerator r = new RsaKeyPairGenerator();

            r.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
            keyPair = r.GenerateKeyPair();

            // Generate the X509 certificate
            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
            X509Name dnName = new X509Name("CN=NVIDIA GameStream Client");

            certGen.SetSerialNumber(BigInteger.ValueOf(DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond));
            certGen.SetSubjectDN(dnName);
            certGen.SetIssuerDN(dnName); // use the same
            // Expires in 20 years
            certGen.SetNotBefore(DateTime.Now);
            certGen.SetNotAfter(DateTime.Now.AddYears(20));
            certGen.SetPublicKey(keyPair.Public);
            certGen.SetSignatureAlgorithm("SHA1withRSA");

            try
            {
                cert = certGen.Generate(keyPair.Private);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.StackTrace);
            }

            SaveCertKeyPair();
        }
        static X509Certificate2 GenerateCertificate(string certName)
        {
            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=" + certName);
            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("SHA256withRSA");
            gen.SetPublicKey(keypair.Public);

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

            return(ConvertToWindows(newCert, keypair));

            // var cert = new X509Certificate2(DotNetUtilities.ToX509Certificate(newCert));
        }
        /// <summary>
        /// Create the RSA certificate with a given public key.
        /// </summary>
        /// <returns>The signed certificate.</returns>
        private X509Certificate2 CreateForRSAWithPublicKey(ISignatureFactory signatureFactory = null)
        {
            // Cases locked out by API flow
            Debug.Assert(m_rsaPublicKey != null, "Need a public key for the certificate.");
            if ((IssuerCAKeyCert == null || !IssuerCAKeyCert.HasPrivateKey) && signatureFactory == null)
            {
                throw new NotSupportedException("Need an issuer certificate with a private key or a signature generator.");
            }

            // cert generators
            CreateDefaults();

            var cg = new X509V3CertificateGenerator();

            CreateMandatoryFields(cg);

            // set public key
            AsymmetricKeyParameter subjectPublicKey = X509Utils.GetPublicKeyParameter(m_rsaPublicKey);

            cg.SetPublicKey(subjectPublicKey);

            CreateExtensions(cg, subjectPublicKey);

            // sign certificate by issuer
            if (signatureFactory == null)
            {
                AsymmetricKeyParameter signingKey = X509Utils.GetPrivateKeyParameter(IssuerCAKeyCert);
                signatureFactory = new Asn1SignatureFactory(X509Utils.GetRSAHashAlgorithm(HashAlgorithmName), signingKey);
            }
            Org.BouncyCastle.X509.X509Certificate x509 = cg.Generate(signatureFactory);

            // create the signed cert
            return(new X509Certificate2(x509.GetEncoded()));
        }
Example #28
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());
            }
        }
Example #29
0
        public static X509Certificate2 CreateCertificateAuthority(string caName, int keyStrength)
        {
            var random     = new SecureRandom();
            var keyPairGen = new RsaKeyPairGenerator();

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

            var certificateGenerator = new X509V3CertificateGenerator();

            var issuer   = new X509Name(@"CN=" + caName + ",OU=qwqdanchun,O=DcRat By qwqdanchun,L=SH,C=CN");
            var certName = new X509Name(@"CN=DcRat");
            var SN       = BigInteger.ProbablePrime(160, new SecureRandom());

            certificateGenerator.SetSerialNumber(SN);
            certificateGenerator.SetSubjectDN(certName);
            certificateGenerator.SetIssuerDN(issuer);
            certificateGenerator.SetNotAfter(DateTime.UtcNow.Subtract(new TimeSpan(-3650, 0, 0, 0)));
            certificateGenerator.SetNotBefore(DateTime.UtcNow.Subtract(new TimeSpan(285, 0, 0, 0)));
            certificateGenerator.SetPublicKey(keypair.Public);
            certificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keypair.Public));
            certificateGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));

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

            var certificate = certificateGenerator.Generate(signatureFactory);

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

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

            return(certificate2);
        }
        public static X509Certificate GenerateSelfSignedCertificate(out AsymmetricKeyParameter privateKey)
        {
            var keypair = GenerateGostKeyPair(
                RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512_paramSetA,
                RosstandartObjectIdentifiers.id_tc26_gost_3411_12_512);

            var generator = new X509V3CertificateGenerator();

            generator.SetSerialNumber(new BigInteger(16 * 8, _random));
            generator.SetIssuerDN(new X509Name("CN=Fake CA"));
            generator.SetSubjectDN(new X509Name("CN=Fake Subject"));
            generator.SetNotBefore(DateTime.Today.AddDays(-1));
            generator.SetNotAfter(DateTime.Today.AddYears(1));
            generator.SetPublicKey(keypair.Public);

            var keyUsage = new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.NonRepudiation);

            generator.AddExtension(X509Extensions.KeyUsage, true, keyUsage);

            var signFactory = new GostSignatureFactory(
                RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512.ToString(),
                keypair.Private);

            privateKey = keypair.Private;

            return(generator.Generate(signFactory));
        }
        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();
        }