Beispiel #1
0
        /// <summary>
        /// Add the Subject Key Identifier.
        /// </summary>
        /// <param name="certificateGenerator">cert generator</param>
        /// <param name="subjectKeyPair">subject key pair</param>
        private static void AddSubjectKeyIdentifier(
            X509V3CertificateGenerator certificateGenerator,
            AsymmetricCipherKeyPair subjectKeyPair)
        {
            var subjectKeyIdentifierExtension =
                new SubjectKeyIdentifier(
                    SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public));

            certificateGenerator.AddExtension(
                X509Extensions.SubjectKeyIdentifier.Id, false, subjectKeyIdentifierExtension);
        }
Beispiel #2
0
            /// <summary>
            /// Add the "Subject Alternative Names" extension. Note that you have to repeat
            /// the value from the "Subject Name" property.
            /// </summary>
            /// <param name="certificateGenerator"></param>
            /// <param name="subjectAlternativeNames"></param>
            public static void AddSubjectAlternativeNames(X509V3CertificateGenerator certificateGenerator,
                                                          IEnumerable <string> subjectAlternativeNames)
            {
                var subjectAlternativeNamesExtension =
                    new DerSequence(
                        subjectAlternativeNames.Select(name => new GeneralName(GeneralName.DnsName, name))
                        .ToArray <Asn1Encodable>());

                certificateGenerator.AddExtension(
                    X509Extensions.SubjectAlternativeName.Id, false, subjectAlternativeNamesExtension);
            }
Beispiel #3
0
        public X509Certificate2 Sign(Pkcs10CertificationRequestDelaySigned inputCSR, X509Name issuerName, AsymmetricKeyParameter issuerPrivKey, AsymmetricCipherKeyPair pair)
        {
            const int keyStrength = 2048;

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

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

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

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

            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            var csrInfo = inputCSR.GetCertificationRequestInfo();

            certificateGenerator.SetIssuerDN(issuerName);
            certificateGenerator.SetSubjectDN(csrInfo.Subject);

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

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

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

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

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

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

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

            //x509.PrivateKey = dotNetPrivateKey;
            //x509.FriendlyName = csrInfo.Subject;

            return(x509);
        }
Beispiel #4
0
        public static X509Certificate2 CreateX509Certificate2(AsymmetricCipherKeyPair kp)
        {
            var random = new SecureRandom();
            var sf     = new Asn1SignatureFactory(HashAlg.SHA256withRSA.ToString(), kp.Private, random);

            var gen = new X509V3CertificateGenerator();

            gen.SetSerialNumber(BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random));
            var subject = new X509Name("CN=" + "ebics.org");

            gen.SetSubjectDN(subject);
            gen.SetIssuerDN(subject);
            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = notBefore.AddYears(10);

            gen.SetNotBefore(notBefore);
            gen.SetNotAfter(notAfter);
            gen.SetPublicKey(kp.Public);
            var bouncyCert = gen.Generate(sf);

            var authorityKeyIdentifier = new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public), new GeneralNames(new GeneralName(subject)), bouncyCert.SerialNumber);

            gen.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, false, authorityKeyIdentifier);
            var subjectKeyIdentifier = new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public));

            gen.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, false, subjectKeyIdentifier);
            gen.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(false));

            var store            = new Pkcs12Store();
            var certificateEntry = new X509CertificateEntry(bouncyCert);

            store.SetCertificateEntry(bouncyCert.SubjectDN.ToString(), certificateEntry);
            store.SetKeyEntry(bouncyCert.SubjectDN.ToString(), new AsymmetricKeyEntry(kp.Private), new[] { certificateEntry });
            const string pwd    = "password";
            var          stream = new MemoryStream();

            store.Save(stream, pwd.ToCharArray(), random);
            var msCert = new X509Certificate2(stream.ToArray(), pwd, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

            return(msCert);
        }
Beispiel #5
0
        /// <summary>
        /// Generate single certificate
        /// </summary>
        /// <param name="hash"></param>
        /// <param name="san"></param>
        /// <returns></returns>
        private X509Certificate2 GenerateCertificate(string hash, out string san)
        {
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom             random          = new SecureRandom(randomGenerator);
            BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();

            certificateGenerator.SetSerialNumber(serialNumber);
            certificateGenerator.SetNotBefore(DateTime.UtcNow);
            certificateGenerator.SetNotAfter(DateTime.UtcNow.AddHours(1));

            san = string.Format("{0}.{1}.acme.invalid", hash.Substring(0, 32), hash.Substring(32));
            X509Name subjectDN = new X509Name(string.Format("CN={0}", san));
            X509Name issuerDN  = subjectDN;

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);
            certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false,
                                              new DerSequence(new Asn1Encodable[] { new GeneralName(GeneralName.DnsName, san) }));
            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, false,
                                              new ExtendedKeyUsage(new KeyPurposeID[] { KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPClientAuth }));
            certificateGenerator.AddExtension(X509Extensions.KeyUsage, true,
                                              new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyEncipherment));
            KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, 2048);
            RsaKeyPairGenerator     keyPairGenerator        = new RsaKeyPairGenerator();

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

            certificateGenerator.SetPublicKey(keyPair.Public);

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

            Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(signatureFactory);
            var flags = X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet;
            var x509  = new X509Certificate2(certificate.GetEncoded(), (string)null, flags);

            x509.FriendlyName = san;
            x509.PrivateKey   = ToDotNetKey((RsaPrivateCrtKeyParameters)keyPair.Private);
            return(x509);
        }
Beispiel #6
0
        /// <summary>
        /// Add the Authority Key Identifier. According to http://www.alvestrand.no/objectid/2.5.29.35.html, this
        /// identifies the public key to be used to verify the signature on this certificate.
        /// In a certificate chain, this corresponds to the "Subject Key Identifier" on the *issuer* certificate.
        /// The Bouncy Castle documentation, at http://www.bouncycastle.org/wiki/display/JA1/X.509+Public+Key+Certificate+and+Certification+Request+Generation,
        /// shows how to create this from the issuing certificate. Since we're creating a self-signed certificate, we have to do this slightly differently.
        /// </summary>
        /// <param name="certificateGenerator"></param>
        /// <param name="issuerDN"></param>
        /// <param name="issuerKeyPair"></param>
        /// <param name="issuerSerialNumber"></param>
        private static void AddAuthorityKeyIdentifier(X509V3CertificateGenerator certificateGenerator,
                                                      X509Name issuerDN,
                                                      AsymmetricCipherKeyPair issuerKeyPair,
                                                      BigInteger issuerSerialNumber)
        {
            var authorityKeyIdentifierExtension = new AuthorityKeyIdentifier(
                SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerKeyPair.Public),
                new GeneralNames(new GeneralName(issuerDN)),
                issuerSerialNumber);

            certificateGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, false, authorityKeyIdentifierExtension);
        }
Beispiel #7
0
        protected override void AddSubjectAlternativeNames(X509V3CertificateGenerator certificateGenerator,
                                                           IEnumerable <string> subjectAlternativeNames)
        {
            // Para ver... emails?
            var subjectAlternativeNamesExtension =
                new DerSequence(
                    subjectAlternativeNames.Select(name => new GeneralName(GeneralName.Rfc822Name, name))
                    .ToArray <Asn1Encodable>());

            certificateGenerator.AddExtension(
                X509Extensions.SubjectAlternativeName.Id, false, subjectAlternativeNamesExtension);
        }
        public static void GenerateCertificate(GenerateCertificateOptions options)
        {
            //generate random numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            var keyGenerator = GeneratorUtilities.GetKeyPairGenerator(options.Algorithm);

            keyGenerator.Init(new KeyGenerationParameters(new SecureRandom(), options.KeyStrength));

            var keyPair = keyGenerator.GenerateKeyPair();

            //the certificate generator
            var certificateGenerator = new X509V3CertificateGenerator();

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

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

            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            certificateGenerator.SetIssuerDN(options.Issuer);
            certificateGenerator.SetSubjectDN(options.Subject);

            //valid For
            certificateGenerator.SetNotBefore(options.NotBefore);
            certificateGenerator.SetNotAfter(options.NotAfter);

            certificateGenerator.SetPublicKey(keyPair.Public);

            ISignatureFactory signatureFactory = new Asn1SignatureFactory(options.SignatureAlgorithm, keyPair.Private);

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

            certificate.CheckValidity();        //检查当前日期是否在证书的有效期内
            certificate.Verify(keyPair.Public); //使用公钥验证证书的签名

            var certEntry = new X509CertificateEntry(certificate);
            var store     = new Pkcs12StoreBuilder().Build();

            store.SetCertificateEntry(options.FriendlyName, certEntry);   //设置证书
            var chain = new X509CertificateEntry[1];

            chain[0] = certEntry;
            store.SetKeyEntry(options.FriendlyName, new AsymmetricKeyEntry(keyPair.Private), chain);   //设置私钥
            using (var fs = File.Create(options.Path))
            {
                store.Save(fs, options.Password.ToCharArray(), new SecureRandom()); //保存
            }
        }
Beispiel #9
0
        private static bool CreateRootCert()
        {
            const int    ROOT_KEY_LENGTH = 2048;
            const string OU            = "Tsanie Lily";
            const string O             = "tsanie.org";
            const string CN            = "Cacher";
            const int    YEARS_VALID   = 10;
            const string SIGNATURE_ALG = "SHA1withRSA";

            var generator = new RsaKeyPairGenerator();

            generator.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), ROOT_KEY_LENGTH));
            var pair         = generator.GenerateKeyPair();
            var generator2   = new X509V3CertificateGenerator();
            var serialNumber = BigInteger.ProbablePrime(120, new Random());

            generator2.SetSerialNumber(serialNumber);
            var issuer = new X509Name(string.Format("OU={0}, O={1}, CN={2}", OU, O, CN));

            generator2.SetIssuerDN(issuer);
            generator2.SetSubjectDN(issuer);
            generator2.SetNotBefore(DateTime.Today.AddDays(-7.0));
            generator2.SetNotAfter(DateTime.Now.AddYears(YEARS_VALID));
            generator2.SetPublicKey(pair.Public);
            generator2.SetSignatureAlgorithm(SIGNATURE_ALG);
            generator2.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0));
            generator2.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(4));
            generator2.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pair.Public));
            var oCACert = generator2.Generate(pair.Private);
            var oCAKey  = pair.Private;

            var encoded = oCACert.GetEncoded();

            FiddlerApplication.Prefs.SetStringPref("fiddler.certmaker.bc.cert", Convert.ToBase64String(encoded));
            var derEncoded = PrivateKeyInfoFactory.CreatePrivateKeyInfo(oCAKey).ToAsn1Object().GetDerEncoded();

            FiddlerApplication.Prefs.SetStringPref("fiddler.certmaker.bc.key", Convert.ToBase64String(derEncoded));

            return(CertMaker.rootCertExists());
        }
Beispiel #10
0
        public static byte[] GenerateCertificate(CertificateSubject subject, CertificateInfo issuer, DateTime startDate, DateTime expiryDate, SignatureHashAlgorithm signatureAlgorithm, TCertificateFormat certificateFormat)
        {
            byte[] result = null;
            AsymmetricKeyParameter privateKey = issuer.PrivateKey as AsymmetricKeyParameter;

            if (privateKey != null)
            {
                CryptoApiRandomGenerator   randomGenerator      = new CryptoApiRandomGenerator();
                SecureRandom               random               = new SecureRandom(randomGenerator);
                X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
                AddStandardCertificateInfo(certificateGenerator, random, subject, issuer.Subject, startDate, expiryDate);
                AsymmetricCipherKeyPair subjectKeyPair = GenerateKeys(certificateGenerator, random, signatureAlgorithm);

                string algorithm = GetAlgorithm(signatureAlgorithm);

                certificateGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
                certificateGenerator.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyEncipherment));
                certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeID[] { KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPClientAuth }));
                byte[] subjectKeyID = new byte[20];
                random.NextBytes(subjectKeyID, 0, 20);
                certificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(subjectKeyID));
                if (issuer.SubjectKeyID != null)
                {
                    certificateGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(issuer.SubjectKeyID));
                }

                //if ((subject.AlternativeNames != null) && (subject.AlternativeNames.Count > 0))
                //{
                //    certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName, true, new SubjectAlternativeNames(false));
                //    //SubjectAlternativeName
                //    //GeneralName.DirectoryName
                //    //GeneralName.IPAddress
                //}

                Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(new Asn1SignatureFactory(algorithm, privateKey, random));
                result = ExportCertificate(certificate, subjectKeyPair, certificateFormat);
            }
            return(result);
        }
Beispiel #11
0
        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());

            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);
        }
Beispiel #12
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());
            }
        }
Beispiel #13
0
        // 上位 CA によって署名されている証明書の作成
        public Certificate(PrivKey thisCertPrivateKey, CertificateStore parentCertificate, CertificateOptions options, CertificateOptions?alternativeIssuerDN = null)
        {
            X509Name name = options.GenerateName();
            X509V3CertificateGenerator gen = new X509V3CertificateGenerator();

            gen.SetSerialNumber(new BigInteger(options.Serial.ToArray()));
            if (alternativeIssuerDN == null)
            {
                gen.SetIssuerDN(parentCertificate.PrimaryCertificate.CertData.IssuerDN);
            }
            else
            {
                gen.SetIssuerDN(alternativeIssuerDN.GenerateName());
            }
            gen.SetSubjectDN(name);
            gen.SetNotBefore(DateTime.Now.AddDays(-1));
            gen.SetNotAfter(options.Expires.UtcDateTime);
            gen.SetPublicKey(thisCertPrivateKey.PublicKey.PublicKeyData);

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

            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(), parentCertificate.PrimaryPrivateKey.PrivateKeyData.Private, PkiUtil.NewSecureRandom()));

            InitFields();
        }
Beispiel #14
0
        //TODO change to functors
        public static X509Certificate CreateX509Certificate2(AsymmetricCipherKeyPair kp, string issuer, DateTime notBefore, DateTime notAfter, KeyType keyUsage, string filename, string password)
        {
            var random = new SecureRandom();
            var sf     = new Asn1SignatureFactory(HashAlg.SHA256withRSA.ToString(), kp.Private, random);

            var gen    = new X509V3CertificateGenerator();
            var serial = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            gen.SetSerialNumber(serial);
            var subject = new X509Name(issuer);

            gen.SetIssuerDN(subject);
            gen.SetSubjectDN(subject);
            gen.SetNotBefore(notBefore);
            gen.SetNotAfter(notAfter);
            gen.SetPublicKey(kp.Public);
            gen.AddExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(true));
            var subjectKeyIdentifier = new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public));

            gen.AddExtension(X509Extensions.SubjectKeyIdentifier, false, subjectKeyIdentifier);
            var authorityKeyIdentifier = new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public), new GeneralNames(new GeneralName(subject)), serial);

            gen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, authorityKeyIdentifier);
            ////gen.AddExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeID.IdKPEmailProtection));

            switch (keyUsage)
            {
            case KeyType.Signature:    //signature
                gen.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(X509KeyUsage.NonRepudiation)); break;

            case KeyType.Authentication:    //authentication
                gen.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(X509KeyUsage.DigitalSignature)); break;

            case KeyType.Encryption:    //encryption
                gen.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(X509KeyUsage.KeyEncipherment | X509KeyUsage.KeyAgreement)); break;

            default:
                gen.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(X509KeyUsage.KeyEncipherment | X509KeyUsage.DigitalSignature)); break;
            }

            var bouncyCert = gen.Generate(sf);

            bouncyCert.CheckValidity();
            bouncyCert.Verify(kp.Public);

            var store            = new Pkcs12Store();
            var certificateEntry = new X509CertificateEntry(bouncyCert);

            store.SetCertificateEntry(bouncyCert.SubjectDN.ToString(), certificateEntry);
            store.SetKeyEntry(bouncyCert.SubjectDN.ToString(), new AsymmetricKeyEntry(kp.Private), new[] { certificateEntry });
            using (var sw = File.Create(filename))
                store.Save(sw, password.ToCharArray(), random);
            return(bouncyCert);
        }
Beispiel #15
0
        public static X509Certificate GenerateEndEntityCert(
            IAsymmetricKeyParameter entityKey,
            IAsymmetricKeyParameter 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));
        }
Beispiel #16
0
        private static Certificate CreateSelfSignedCertificate(CertType certType, KeyPair keyPair, string commonName, string signatureAlgorithm, string san)
        {
            X509V3CertificateGenerator certBuilder = CreateCertBuilder(keyPair, commonName);
            // Basic constraints
            BasicConstraints constraints = new BasicConstraints(true);

            certBuilder.AddExtension(X509Extensions.BasicConstraints, true, constraints);
            // Key usage
            KeyUsage usage = new KeyUsage(Org.BouncyCastle.Asn1.X509.KeyUsage.KeyEncipherment | Org.BouncyCastle.Asn1.X509.KeyUsage.DigitalSignature | Org.BouncyCastle.Asn1.X509.KeyUsage.KeyCertSign);

            certBuilder.AddExtension(X509Extensions.KeyUsage, false, usage);
            // Extended key usage
            //var usages = new[] { KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPClientAuth };
            certBuilder.AddExtension(X509Extensions.ExtendedKeyUsage, false, KeyUsage(certType));
            if (san != null)
            {
                AddSAN(certBuilder, san);
            }
            ISignatureFactory signatureFactory = new Asn1SignatureFactory(signatureAlgorithm, keyPair.PrivateKey, new SecureRandom());

            return(Certificate.Create(certBuilder.Generate(signatureFactory), keyPair.PrivateKey));
        }
        protected void AddSubjectKeyIdentifier(X509V3CertificateGenerator certificateGenerator,
                                               AsymmetricCipherKeyPair subjectKeyPair)
        {
            // Subject Key Identifier, usado para facilitar a validação de certificados.
            // Em CA são gerados, em geral, a partir da sua chave pública.
            // Secção 4.2.1.2 do http://www.ietf.org/rfc/rfc3280.txt
            var subjectKeyIdentifierExtension =
                new SubjectKeyIdentifier(
                    SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public));

            certificateGenerator.AddExtension(
                X509Extensions.SubjectKeyIdentifier.Id, false, subjectKeyIdentifierExtension);
        }
Beispiel #18
0
        public X509Certificate2 MakeCertificate(string password, string issuedToDomainName, int validYears)
        {
            _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 subjectAlternativeNames = new Asn1Encodable[_generalNames.Length + 1];

            // first subject alternative name is the same as the subject
            subjectAlternativeNames[0] = new GeneralName(new X509Name(issuedToDomainName));
            for (int t = 1; t <= _generalNames.Length; t++)
            {
                subjectAlternativeNames[t] = _generalNames[t - 1];
            }
            var subjectAlternativeNamesExtension = new DerSequence(subjectAlternativeNames);

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

            _certificateGenerator.SetNotBefore(DateTime.UtcNow.Date);
            _certificateGenerator.SetNotAfter(DateTime.UtcNow.Date.AddYears(validYears));
            var keyGenerationParameters = new KeyGenerationParameters(_random, _strength);

            var keyPairGenerator = new RsaKeyPairGenerator();

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

            _certificateGenerator.SetPublicKey(subjectKeyPair.Public);
            var issuerKeyPair = subjectKeyPair;
            var certificate   = _certificateGenerator.Generate(issuerKeyPair.Private, _random);

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

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

            using (var stream = new MemoryStream())
            {
                store.Save(stream, password.ToCharArray(), _random);
                return(new X509Certificate2(stream.ToArray(), password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable));
            }
        }
Beispiel #19
0
        public PublicCertificatePfxPair Generate(string name, string pfxPassword)
        {
            var keyStrength             = 2048;
            var randomGenerator         = new CryptoApiRandomGenerator();
            var random                  = new SecureRandom(randomGenerator);
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyGenerator            = new RsaKeyPairGenerator();

            keyGenerator.Init(keyGenerationParameters);
            Console.WriteLine("Generating key pair...");
            var subjectKeyPair = keyGenerator.GenerateKeyPair();

            Console.WriteLine("Keypair generated.");
            var privateKey = (RsaPrivateCrtKeyParameters)subjectKeyPair.Private;
            var publicKey  = (RsaKeyParameters)subjectKeyPair.Public;

            Console.WriteLine($"Public key exponent: {publicKey.Exponent}");
            Console.WriteLine($"Public key modulus: {publicKey.Modulus}");
            ISignatureFactory signatureFactory = new Asn1SignatureFactory(PkcsObjectIdentifiers.Sha256WithRsaEncryption.ToString(), privateKey);
            var        certificateGenerator    = new X509V3CertificateGenerator();
            BigInteger serialNo    = BigInteger.ProbablePrime(128, random);
            var        subjectName = new X509Name($"CN={name}");

            certificateGenerator.SetSerialNumber(serialNo);
            certificateGenerator.SetSubjectDN(subjectName);
            certificateGenerator.SetIssuerDN(subjectName);
            var notBefore = new DateTime(2000, 1, 1);
            var notAfter  = notBefore.AddYears(1000);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);
            certificateGenerator.SetPublicKey(subjectKeyPair.Public);
            var certificatePermissions = new List <KeyPurposeID>()
            {
                KeyPurposeID.IdKPServerAuth,
                KeyPurposeID.IdKPClientAuth,
                KeyPurposeID.AnyExtendedKeyUsage
            };

            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(certificatePermissions));
            var newCert = certificateGenerator.Generate(signatureFactory);

            // DotNetUtilities.ToX509Certificate(newCert).Export(X509ContentType.Pfx, pfxPassword);
            // produced a pfx file where the private key could not be loaded
            var pfxBytes  = CreatePfxFile(newCert, privateKey, name, pfxPassword);
            var certBytes = DotNetUtilities.ToX509Certificate(newCert).Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert);

            return(new PublicCertificatePfxPair {
                PfxBytes = pfxBytes, PublicCertificateBytes = certBytes
            });
        }
Beispiel #20
0
        public override void Build(
            X509V3CertificateGenerator certGen,
            Pkcs10CertificationRequest request,
            X509Certificate caCert)
        {
            var requestInfo = request.GetCertificationRequestInfo();

            var extensionSequence =
                requestInfo
                .Attributes.OfType <DerSequence>()
                .First(o => o.OfType <DerObjectIdentifier>().Any(oo => oo.Id == "1.2.840.113549.1.9.14"));

            var extensionSet = extensionSequence.OfType <DerSet>().First().OfType <DerSequence>().First();

            var exts = X509Extensions.GetInstance(extensionSet);

            var extOIDs = exts.GetExtensionOids();

            foreach (var x509ExtOid in extOIDs)
            {
                var ext = exts.GetExtension(x509ExtOid);

                if (x509ExtOid.Id == "2.5.29.37") //extKeyUsage sequence
                {
                    Asn1OctetString oct = ext.Value;
                    Asn1Sequence    seq = Asn1Sequence.GetInstance(oct.GetOctets());

                    foreach (DerObjectIdentifier obj in seq)
                    {
                        if (threeYearsValidExtKeyId == obj.Id)
                        {
                            var startDate = DateTime.Now;

                            certGen.SetNotBefore(startDate);
                            certGen.SetNotAfter(startDate.AddYears(3));

                            break;
                        }
                    }
                }

                certGen.AddExtension(
                    x509ExtOid,
                    ext.IsCritical,
                    ext.GetParsedValue()
                    );
            }

            ApplyCrlExtension(certGen, _crlLink);
            ApplyAuthorityInfoAccess(certGen, _rootCertLink);
        }
Beispiel #21
0
        public static X509Certificate2 GenerateNewCertificate(string name)
        {
            var kpGen = new RsaKeyPairGenerator();

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

            AsymmetricCipherKeyPair keyPair = kpGen.GenerateKeyPair();
            var        gen             = new X509V3CertificateGenerator();
            var        certificateName = new X509Name("CN=" + name);
            BigInteger serialNumber    = BigInteger.ProbablePrime(120, new Random());

            gen.SetSerialNumber(serialNumber);
            gen.SetSubjectDN(certificateName);
            gen.SetIssuerDN(certificateName);
            gen.SetNotAfter(DateTime.Now.AddYears(100));
            gen.SetNotBefore(DateTime.Now.AddDays(-1));
            gen.SetSignatureAlgorithm("SHA256WithRSAEncryption");
            gen.SetPublicKey(keyPair.Public);

            gen.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, false,
                             new AuthorityKeyIdentifier(
                                 SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public),
                                 new GeneralNames(new GeneralName(certificateName)), serialNumber));

            X509Certificate newCert = gen.Generate(keyPair.Private);

            var newStore = new Pkcs12Store();

            var certEntry = new X509CertificateEntry(newCert);

            newStore.SetCertificateEntry(
                Environment.MachineName,
                certEntry
                );

            newStore.SetKeyEntry(
                Environment.MachineName,
                new AsymmetricKeyEntry(keyPair.Private),
                new[] { certEntry }
                );

            var memoryStream = new MemoryStream();

            newStore.Save(
                memoryStream,
                new char[0],
                new SecureRandom(new CryptoApiRandomGenerator())
                );

            return(new X509Certificate2(memoryStream.ToArray()));
        }
Beispiel #22
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));
        }
        protected override void AddSubjectAlternativeNames(X509V3CertificateGenerator certificateGenerator,
                                                           IEnumerable <string> subjectAlternativeNames)
        {
            // Adição de 'Subject Alternative Names'
            // NOTA: tem que se repetir o 'Subject Name'
            // Serve para wildcards certificates. Tipo '*.dominio.com', 'dominio.com'
            var subjectAlternativeNamesExtension =
                new DerSequence(
                    subjectAlternativeNames.Select(name => new GeneralName(GeneralName.DnsName, name))
                    .ToArray <Asn1Encodable>());

            certificateGenerator.AddExtension(
                X509Extensions.SubjectAlternativeName.Id, false, subjectAlternativeNamesExtension);
        }
 protected void AddAuthorityKeyIdentifier(
     X509V3CertificateGenerator certificateGenerator,
     AsymmetricCipherKeyPair issuerKeyPair)
 {
     // Apenas adicionando KeyId.
     // Razões: ver outra implementação
     // a maioria das entidades certificadoras apenas usam KeyID
     certificateGenerator.AddExtension(
         X509Extensions.AuthorityKeyIdentifier.Id,
         false,
         new AuthorityKeyIdentifier(
             SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerKeyPair.Public))
         );
 }
        public void GenerateCertUsingExistigCertificate()
        {
            var root                  = File.ReadAllBytes(@"root.pfx");
            var childRoot             = File.ReadAllBytes(@"childroot.pfx");
            X509KeyUsageExtension var = new X509KeyUsageExtension(
                X509KeyUsageFlags.CrlSign | X509KeyUsageFlags.DecipherOnly | X509KeyUsageFlags.KeyCertSign, true);
            var x509ChildCertificate = new X509Certificate2(childRoot, "airwatch",
                                                            X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);
            var x509RootCert = new X509Certificate2(root, "airwatch",
                                                    X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);

            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);
            var cert            = new X509V3CertificateGenerator();
            var serialNumber    =
                BigIntegers.CreateRandomInRange(
                    BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            cert.SetSerialNumber(serialNumber);
            var rootSubject = new X509Name(x509RootCert.SubjectName.Name);
            var subjectDN   = new X509Name(x509ChildCertificate.SubjectName.Name);

            cert.SetIssuerDN(rootSubject);
            cert.SetSubjectDN(subjectDN);
            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = notBefore.AddYears(10);

            cert.SetNotBefore(notBefore);
            cert.SetNotAfter(notAfter);
            //var x509Certificate = new X509Certificate(X509CertificateStructure.GetInstance(new DerTaggedObject(x509RootCert, new )))
            cert.SetSignatureAlgorithm("SHA256withRSA");
            cert.SetPublicKey(TransformRSAPublicKey(x509ChildCertificate.PublicKey.Key, false));
            cert.AddExtension(X509Extensions.AuthorityKeyIdentifier, true, new AuthorityKeyIdentifierStructure(new X509CertificateParser().ReadCertificate(x509RootCert.RawData)));
            //new X509CertificateParser().ReadCertificate(x509RootCert.RawData);
            //var factory = new Asn1SignatureFactory(SHA256.Create().ToString(), TransformRSAPrivateKey(x509RootCert.PrivateKey, true));
            var certificate = cert.Generate(TransformRSAPrivateKey(x509RootCert.PrivateKey, true), random);

            x509ChildCertificate.Extensions.Add(var);

            var certexp = new X509Certificate2(certificate.GetEncoded(), "1234");
            //var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            //store.Open(OpenFlags.ReadWrite);
            //store.Add(certexp);
            var chain = new X509Chain(true);

            chain.Build(certexp);
            File.WriteAllBytes(@"C:\cmstest\test.pfx", certexp
                               .Export(X509ContentType.Pfx, "1234"));
        }
Beispiel #26
0
        public static Pkcs12Store CreateCert(string commonName, DateTime notBefore, DateTime notAfter,
                                             IEnumerable <string> dnsAltNames, IEnumerable <string> ipAddressAltNames, Pkcs12Store signBy)
        {
            var keyPairGen = new RsaKeyPairGenerator();

            keyPairGen.Init(new KeyGenerationParameters(new SecureRandom(), 2048));

            var keyPair = keyPairGen.GenerateKeyPair();

            var certGenerator = new X509V3CertificateGenerator();

            certGenerator.SetSubjectDN(new X509Name("CN=" + commonName));
            if (signBy == null)
            {
                certGenerator.SetIssuerDN(new X509Name("CN=" + commonName));
            }
            else
            {
                certGenerator.SetIssuerDN(signBy.GetCertificate().SubjectDN);
            }

            certGenerator.SetSerialNumber(BigInteger.ProbablePrime(64, new Random()));
            certGenerator.SetNotBefore(notBefore);
            certGenerator.SetNotAfter(notAfter);
            certGenerator.SetPublicKey(keyPair.Public);

            if ((dnsAltNames?.Any() ?? false) || (ipAddressAltNames?.Any() ?? false))
            {
                var alternativeNames = new List <Asn1Encodable>();
                alternativeNames.AddRange(dnsAltNames?.Select(name => new GeneralName(GeneralName.DnsName, name)) ??
                                          Enumerable.Empty <Asn1Encodable>());
                alternativeNames.AddRange(ipAddressAltNames?.Select(ip => new GeneralName(GeneralName.IPAddress, ip)) ??
                                          Enumerable.Empty <Asn1Encodable>());

                certGenerator.AddExtension(
                    X509Extensions.SubjectAlternativeName,
                    false,
                    new DerSequence(alternativeNames.ToArray())
                    );
            }

            var signatureKeyPair = signBy != null
                ? new AsymmetricCipherKeyPair(signBy.GetCertificate().GetPublicKey(), signBy.GetKey())
                : keyPair;
            var signer      = new Asn1SignatureFactory("SHA256WITHRSA", signatureKeyPair.Private);
            var certificate = certGenerator.Generate(signer);

            return(ToPkcs12(certificate, keyPair.Private));
        }
 private static void AddExtensionCrlDistributionPoints(X509V3CertificateGenerator certGen, string crl)
 {
     certGen.AddExtension(X509Extensions.CrlDistributionPoints, false,
                          new CrlDistPoint(new[]
     {
         new DistributionPoint(
             new DistributionPointName(
                 DistributionPointName.FullName,
                 new GeneralNames(
                     new GeneralName(GeneralName.UniformResourceIdentifier, crl)
                     )
                 )
             , null, null)
     }));
 }
Beispiel #28
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());
            }
        }
Beispiel #29
0
        private static void setSubjectAndIssuer(X509V3CertificateGenerator generator, String subjectName, String issuerName)
        {
            var subjectDN = new X509Name(subjectName);

            generator.SetSubjectDN(subjectDN);

            var issuerDN = issuerName == null ? subjectDN : new X509Name(issuerName);

            generator.SetIssuerDN(issuerDN);

            var subjectAlt     = subjectName.CleanSubject();
            var subjectAltName = new GeneralNames(new GeneralName(GeneralName.DnsName, subjectAlt));

            generator.AddExtension(X509Extensions.SubjectAlternativeName, false, subjectAltName);
        }
        /// <summary>
        /// Call to request a certificate
        /// </summary>
        /// <param name="csr">Certificate signing request</param>
        /// <param name="effectiveDate">Effective date of certificate</param>
        /// <param name="expirationDate">Expiration date of certificate</param>
        /// <param name="ca">Signing authority</param>
        /// <param name="asn1Set">Extensions</param>
        /// <exception cref="InvalidParameterException">Thrown if <paramref name="ca"/> is null</exception>
        /// <returns>Certificate signed by <paramref name="ca"/></returns>
        public static X509Certificate2 RequestCertificate(Pkcs10CertificationRequest csr, DateTime effectiveDate, DateTime expirationDate, X509Certificate2 ca, Asn1Set asn1Set)
        {
            AsymmetricKeyParameter keyParameter = null;

            if (ca == null)
            {
                throw new InvalidParameterException("ca can not be null");
            }

            keyParameter = TransformRSAPrivateKey((RSACryptoServiceProvider)ca.PrivateKey);

            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(CreateSerialNumber());
            certGen.SetIssuerDN(new X509Name(ca.Subject));
            certGen.SetNotBefore(effectiveDate.ToUniversalTime());
            certGen.SetNotAfter(expirationDate.ToUniversalTime());
            certGen.SetSubjectDN(csr.GetCertificationRequestInfo().Subject);
            certGen.SetPublicKey(csr.GetPublicKey());
            certGen.SetSignatureAlgorithm(SIGNATURE_ALGORITHM);

            CertificationRequestInfo info = csr.GetCertificationRequestInfo();

            if (asn1Set != null)
            {
                // Iterate through each extension and add it to the certificate
                for (int i = 0; i < asn1Set.Count; i++)
                {
                    AttributePkcs attr = AttributePkcs.GetInstance(asn1Set[i]);

                    if (attr != null && attr.AttrType.Equals(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest))
                    {
                        X509Extensions extensions = X509Extensions.GetInstance(attr.AttrValues[0]);

                        foreach (DerObjectIdentifier extOid in extensions.ExtensionOids)
                        {
                            Org.BouncyCastle.Asn1.X509.X509Extension ext = extensions.GetExtension(extOid);

                            certGen.AddExtension(extOid, ext.IsCritical, ext.GetParsedValue());
                        }
                    }
                }
            }

            Org.BouncyCastle.X509.X509Certificate bcCert = certGen.Generate(keyParameter);

            return(new X509Certificate2(bcCert.GetEncoded()));
        }
        public void TestCreationECDSA()
        {
            BigInteger ECParraGX = new BigInteger(Base64.Decode("D/qWPNyogWzMM7hkK+35BcPTWFc9Pyf7vTs8uaqv"));
            BigInteger ECParraGY = new BigInteger(Base64.Decode("AhQXGxb1olGRv6s1LPRfuatMF+cx3ZTGgzSE/Q5R"));
            BigInteger ECParraH = new BigInteger(Base64.Decode("AQ=="));
            BigInteger ECParraN = new BigInteger(Base64.Decode("f///////////////f///nl6an12QcfvRUiaIkJ0L"));
            BigInteger ECPubQX = new BigInteger(Base64.Decode("HWWi17Yb+Bm3PYr/DMjLOYNFhyOwX1QY7ZvqqM+l"));
            BigInteger ECPubQY = new BigInteger(Base64.Decode("JrlJfxu3WGhqwtL/55BOs/wsUeiDFsvXcGhB8DGx"));
            BigInteger 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");

            certGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

            X509Certificate cert = certGen.Generate(ecPriv);

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

            ISet extOidSet = cert.GetCriticalExtensionOids();

            if (extOidSet.Count != 1)
            {
                Fail("wrong number of oids");
            }
            //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();
        }