Exemplo n.º 1
0
 public void Reset()
 {
     s_certGenerator.Reset();
     s_crlGenerator.Reset();
     _authorityCertificate = null;
     _isInitialized        = false;
 }
Exemplo n.º 2
0
        /**
         * intermediate cert
         */
        private X509Certificate CreateIntmedCert(
            AsymmetricKeyParameter pubKey,
            AsymmetricKeyParameter caPrivKey,
            AsymmetricKeyParameter caPubKey,
            Asn1EncodableVector policies,
            Hashtable policyMap)
        {
            string issuer  = "C=JP, O=policyMappingAdditionalTest, OU=trustAnchor";
            string subject = "C=JP, O=policyMappingAdditionalTest, OU=intmedCA";

            v3CertGen.Reset();
            v3CertGen.SetSerialNumber(BigInteger.ValueOf(20));
            v3CertGen.SetIssuerDN(new X509Name(issuer));
            v3CertGen.SetNotBefore(DateTime.UtcNow.AddDays(-30));
            v3CertGen.SetNotAfter(DateTime.UtcNow.AddDays(30));
            v3CertGen.SetSubjectDN(new X509Name(subject));
            v3CertGen.SetPublicKey(pubKey);
            v3CertGen.SetSignatureAlgorithm("SHA1WithRSAEncryption");
            v3CertGen.AddExtension(X509Extensions.CertificatePolicies, true, new DerSequence(policies));
            v3CertGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
            v3CertGen.AddExtension(X509Extensions.PolicyMappings, true, new PolicyMappings(policyMap));
            X509Certificate cert = v3CertGen.Generate(caPrivKey);

            return(cert);
        }
Exemplo n.º 3
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);
        }
 private byte[] MakeCertificateFromCSR(string CSR, AsymmetricCipherKeyPair rootKeyPair, X509Name rootSubject)
 {
     byte[] encoded;
     try
     {
         Pkcs10CertificationRequest pkcs10CertificationRequest = (Pkcs10CertificationRequest)(new PemReader(new StringReader(CSR))).ReadObject();
         AsymmetricKeyParameter     @private = rootKeyPair.Private;
         AsymmetricKeyParameter     @public  = rootKeyPair.Public;
         X509V3CertificateGenerator x509V3CertificateGenerator = new X509V3CertificateGenerator();
         x509V3CertificateGenerator.Reset();
         if (this.SerialNumber != -9223372036854775808L)
         {
             x509V3CertificateGenerator.SetSerialNumber(new BigInteger(this.SerialNumber.ToString()));
         }
         else
         {
             DateTime now = DateTime.Now;
             x509V3CertificateGenerator.SetSerialNumber(new BigInteger(128, new Random(now.Millisecond + Environment.TickCount)));
         }
         x509V3CertificateGenerator.SetIssuerDN(rootSubject);
         x509V3CertificateGenerator.SetNotBefore(this.ValidFrom.ToUniversalTime());
         x509V3CertificateGenerator.SetNotAfter(this.ValidTo.ToUniversalTime());
         x509V3CertificateGenerator.SetSubjectDN(pkcs10CertificationRequest.GetCertificationRequestInfo().Subject);
         x509V3CertificateGenerator.SetPublicKey(pkcs10CertificationRequest.GetPublicKey());
         x509V3CertificateGenerator.SetSignatureAlgorithm(string.Concat(this.SignatureAlgorithm.ToString(), "Encryption"));
         x509V3CertificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pkcs10CertificationRequest.GetPublicKey())));
         x509V3CertificateGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(@public)));
         int extensionType = 0;
         Asn1EncodableVector asn1EncodableVectors = new Asn1EncodableVector(new Asn1Encodable[0]);
         foreach (ExtensionInfo extension in this.Extensions.extensionInfo)
         {
             if (!extension.ExtendedKeyUsage)
             {
                 extensionType |= (int)extension.ExtensionType;
             }
             if (!extension.ExtendedKeyUsage)
             {
                 continue;
             }
             asn1EncodableVectors.Add(new Asn1Encodable[] { (Asn1Encodable)extension.ExtensionType });
         }
         if (extensionType != 0)
         {
             x509V3CertificateGenerator.AddExtension(X509Extensions.KeyUsage, this.Extensions.KeyUsageIsCritical, new KeyUsage(extensionType));
         }
         if (asn1EncodableVectors.Count > 0)
         {
             x509V3CertificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, this.Extensions.EnhancedKeyUsageIsCritical, ExtendedKeyUsage.GetInstance(new DerSequence(asn1EncodableVectors)));
         }
         X509Certificate x509Certificate = x509V3CertificateGenerator.Generate(@private, this.GetSecureRandom());
         x509Certificate.Verify(@public);
         encoded = x509Certificate.GetEncoded();
     }
     catch
     {
         throw;
     }
     return(encoded);
 }
Exemplo n.º 5
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));
            }
        }
Exemplo n.º 6
0
        public static X509Certificate MakeCertificate(AsymmetricCipherKeyPair _subKP,
                                                      string _subDN, AsymmetricCipherKeyPair _issKP, string _issDN, bool _ca)
        {
            AsymmetricKeyParameter _subPub  = _subKP.Public;
            AsymmetricKeyParameter _issPriv = _issKP.Private;
            AsymmetricKeyParameter _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("MD5WithRSAEncryption");

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

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

            if (_ca)
            {
                _v3CertGen.AddExtension(X509Extensions.BasicConstraints, false,
                                        new BasicConstraints(_ca));
            }
            else
            {
                _v3CertGen.AddExtension(X509Extensions.ExtendedKeyUsage, true,
                                        ExtendedKeyUsage.GetInstance(new DerSequence(KeyPurposeID.IdKPTimeStamping)));
            }

            X509Certificate _cert = _v3CertGen.Generate(_issPriv);

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

            return(_cert);
        }
Exemplo n.º 7
0
        public X509Certificate2 MakeCertificate(string password,
                                                string issuedToDomainName,
                                                string friendlyName,
                                                int validDays)
        {
            _certificateGenerator.Reset();
            _certificateGenerator.SetSignatureAlgorithm(SignatureAlgorithm);
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), _random);

            _certificateGenerator.SetSerialNumber(serialNumber);

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

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

            _certificateGenerator.SetNotBefore(utcNow);
            _certificateGenerator.SetNotAfter(utcNow.AddDays(validDays));
            var keyGenerationParameters = new KeyGenerationParameters(_random, _strength);

            var keyPairGenerator = new RsaKeyPairGenerator();

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

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

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

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

            using (var stream = new MemoryStream())
            {
                store.Save(stream, password.ToCharArray(), _random);
                return(new X509Certificate2(stream.ToArray(), password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable));
            }
        }
        private X509Certificate MakeCertificate(AsymmetricCipherKeyPair subjectKeyPair, X509Name certificateSubject, AsymmetricCipherKeyPair rootKeyPair, X509Name rootSubject, bool isRootCertificate, bool addAuthorityKeyIdentifier)
        {
            X509Certificate x509Certificate;

            try
            {
                AsymmetricKeyParameter     @public  = subjectKeyPair.Public;
                AsymmetricKeyParameter     @private = rootKeyPair.Private;
                AsymmetricKeyParameter     asymmetricKeyParameter     = rootKeyPair.Public;
                X509V3CertificateGenerator x509V3CertificateGenerator = new X509V3CertificateGenerator();
                x509V3CertificateGenerator.Reset();
                if (this.SerialNumber != -9223372036854775808L)
                {
                    x509V3CertificateGenerator.SetSerialNumber(new BigInteger(this.SerialNumber.ToString()));
                }
                else
                {
                    DateTime now = DateTime.Now;
                    x509V3CertificateGenerator.SetSerialNumber(new BigInteger(128, new Random(now.Millisecond + Environment.TickCount)));
                }
                x509V3CertificateGenerator.SetIssuerDN(rootSubject);
                x509V3CertificateGenerator.SetNotBefore(this.ValidFrom.ToUniversalTime());
                x509V3CertificateGenerator.SetNotAfter(this.ValidTo.ToUniversalTime());
                x509V3CertificateGenerator.SetSubjectDN(certificateSubject);
                x509V3CertificateGenerator.SetPublicKey(@public);
                x509V3CertificateGenerator.SetSignatureAlgorithm(string.Concat(this.SignatureAlgorithm.ToString(), "Encryption"));
                int extensionType = 0;
                Asn1EncodableVector asn1EncodableVectors = new Asn1EncodableVector(new Asn1Encodable[0]);
                foreach (ExtensionInfo extension in this.Extensions.extensionInfo)
                {
                    if (!extension.ExtendedKeyUsage)
                    {
                        extensionType |= (int)extension.ExtensionType;
                    }
                    if (!extension.ExtendedKeyUsage)
                    {
                        continue;
                    }
                    asn1EncodableVectors.Add(new Asn1Encodable[] { (Asn1Encodable)extension.ExtensionType });
                }
                bool keyUsageIsCritical = this.Extensions.KeyUsageIsCritical;
                if (isRootCertificate)
                {
                    x509V3CertificateGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
                    extensionType     |= 6;
                    keyUsageIsCritical = true;
                }
                if (extensionType != 0)
                {
                    x509V3CertificateGenerator.AddExtension(X509Extensions.KeyUsage, keyUsageIsCritical, new KeyUsage(extensionType));
                }
                if (asn1EncodableVectors.Count > 0)
                {
                    x509V3CertificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, this.Extensions.EnhancedKeyUsageIsCritical, ExtendedKeyUsage.GetInstance(new DerSequence(asn1EncodableVectors)));
                }
                x509V3CertificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(@public)));
                if (addAuthorityKeyIdentifier)
                {
                    x509V3CertificateGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(asymmetricKeyParameter)));
                }
                X509Certificate x509Certificate1 = x509V3CertificateGenerator.Generate(@private, this.GetSecureRandom());
                x509Certificate1.Verify(asymmetricKeyParameter);
                x509Certificate = x509Certificate1;
            }
            catch
            {
                throw;
            }
            return(x509Certificate);
        }
Exemplo n.º 9
0
        public static X509Certificate MakeCertificate(
            AsymmetricCipherKeyPair subKP, string _subDN,
            AsymmetricCipherKeyPair issKP, string _issDN, bool _ca)
        {
            AsymmetricKeyParameter subPub  = subKP.Public;
            AsymmetricKeyParameter issPriv = issKP.Private;
            AsymmetricKeyParameter 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);

            if (issPub is RsaKeyParameters)
            {
                v3CertGen.SetSignatureAlgorithm("SHA1WithRSA");
            }
            else if (issPub is ECPublicKeyParameters)
            {
                ECPublicKeyParameters ecPub = (ECPublicKeyParameters)issPub;
                if (ecPub.AlgorithmName == "ECGOST3410")
                {
                    v3CertGen.SetSignatureAlgorithm("GOST3411withECGOST3410");
                }
                else
                {
                    v3CertGen.SetSignatureAlgorithm("SHA1withECDSA");
                }
            }
            else
            {
                v3CertGen.SetSignatureAlgorithm("GOST3411WithGOST3410");
            }

            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();
            _cert.Verify(issPub);

            return(_cert);
        }
Exemplo n.º 10
0
        /**
         * we generate an intermediate certificate signed by our CA
         */
        public static X509CertificateEntry CreateIntermediateCert(
            AsymmetricKeyParameter pubKey,
            AsymmetricKeyParameter caPrivKey,
            X509Certificate caCert)
        {
            //
            // subject name table.
            //
            IDictionary attrs = new Hashtable();
            IList       order = new ArrayList();

            attrs.Add(X509Name.C, "AU");
            attrs.Add(X509Name.O, "The Legion of the Bouncy Castle");
            attrs.Add(X509Name.OU, "Bouncy Intermediate Certificate");
            attrs.Add(X509Name.EmailAddress, "*****@*****.**");

            order.Add(X509Name.C);
            order.Add(X509Name.O);
            order.Add(X509Name.OU);
            order.Add(X509Name.EmailAddress);

            //
            // create the certificate - version 3
            //
            v3CertGen.Reset();

            v3CertGen.SetSerialNumber(BigInteger.Two);
            v3CertGen.SetIssuerDN(PrincipalUtilities.GetSubjectX509Principal(caCert));
            v3CertGen.SetNotBefore(DateTime.UtcNow.AddMonths(-1));
            v3CertGen.SetNotAfter(DateTime.UtcNow.AddMonths(1));
            v3CertGen.SetSubjectDN(new X509Name(order, attrs));
            v3CertGen.SetPublicKey(pubKey);
            v3CertGen.SetSignatureAlgorithm("SHA1WithRSAEncryption");

            //
            // extensions
            //
            v3CertGen.AddExtension(
                X509Extensions.SubjectKeyIdentifier,
                false,
                new SubjectKeyIdentifierStructure(pubKey));

            v3CertGen.AddExtension(
                X509Extensions.AuthorityKeyIdentifier,
                false,
                new AuthorityKeyIdentifierStructure(caCert));

            v3CertGen.AddExtension(
                X509Extensions.BasicConstraints,
                true,
                new BasicConstraints(0));

            X509Certificate cert = v3CertGen.Generate(caPrivKey);

            cert.CheckValidity(DateTime.UtcNow);

            cert.Verify(caCert.GetPublicKey());

//			PKCS12BagAttributeCarrier   bagAttr = (PKCS12BagAttributeCarrier)cert;
            IDictionary bagAttr = new Hashtable();

            //
            // this is actually optional - but if you want to have control
            // over setting the friendly name this is the way to do it...
            //
//			bagAttr.setBagAttribute(
//				PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
//				new DERBMPString("Bouncy Intermediate Certificate"));
            bagAttr.Add(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id,
                        new DerBmpString("Bouncy Intermediate Certificate"));

            return(new X509CertificateEntry(cert, bagAttr));
        }