コード例 #1
0
 public IssuerAndSerialNumber(
     X509Name	name,
     BigInteger	serialNumber)
 {
     this.name = name;
     this.serialNumber = new DerInteger(serialNumber);
 }
コード例 #2
0
		public IssuerAndSerialNumber(
            X509Name	name,
            DerInteger	certSerialNumber)
        {
            this.name = name;
            this.certSerialNumber = certSerialNumber;
        }
コード例 #3
0
 public IssuerAndSerialNumber(
     X509Name	name,
     DerInteger	serialNumber)
 {
     this.name = name;
     this.serialNumber = serialNumber;
 }
コード例 #4
0
ファイル: X509Request.cs プロジェクト: challal/scallion
		/// <summary>
		/// Calls X509_REQ_new() and then initializes version, subject, and key.
		/// </summary>
		/// <param name="version"></param>
		/// <param name="subject"></param>
		/// <param name="key"></param>
		public X509Request(int version, X509Name subject, CryptoKey key)
			: this()
		{
			this.Version = version;
			this.Subject = subject;
			this.PublicKey = key;
		}
コード例 #5
0
ファイル: CsrHelper.cs プロジェクト: bjtucker/letsencrypt-win
        public static Csr GenerateCsr(CsrDetails csrDetails, RsaKeyPair rsaKeyPair, string messageDigest = "SHA256")
        {
            var rsaKeys = CryptoKey.FromPrivateKey(rsaKeyPair.Pem, null);

            // Translate from our external form to our OpenSSL internal form
            // Ref:  https://www.openssl.org/docs/manmaster/crypto/X509_NAME_new.html
            var xn = new X509Name();
            if (!string.IsNullOrEmpty(csrDetails.CommonName         /**/)) xn.Common = csrDetails.CommonName;       // CN;
            if (!string.IsNullOrEmpty(csrDetails.Country            /**/)) xn.Common = csrDetails.Country;          // C;
            if (!string.IsNullOrEmpty(csrDetails.StateOrProvince    /**/)) xn.Common = csrDetails.StateOrProvince;  // ST;
            if (!string.IsNullOrEmpty(csrDetails.Locality           /**/)) xn.Common = csrDetails.Locality;         // L;
            if (!string.IsNullOrEmpty(csrDetails.Organization       /**/)) xn.Common = csrDetails.Organization;     // O;
            if (!string.IsNullOrEmpty(csrDetails.OrganizationUnit   /**/)) xn.Common = csrDetails.OrganizationUnit; // OU;
            if (!string.IsNullOrEmpty(csrDetails.Description        /**/)) xn.Common = csrDetails.Description;      // D;
            if (!string.IsNullOrEmpty(csrDetails.Surname            /**/)) xn.Common = csrDetails.Surname;          // S;
            if (!string.IsNullOrEmpty(csrDetails.GivenName          /**/)) xn.Common = csrDetails.GivenName;        // G;
            if (!string.IsNullOrEmpty(csrDetails.Initials           /**/)) xn.Common = csrDetails.Initials;         // I;
            if (!string.IsNullOrEmpty(csrDetails.Title              /**/)) xn.Common = csrDetails.Title;            // T;
            if (!string.IsNullOrEmpty(csrDetails.SerialNumber       /**/)) xn.Common = csrDetails.SerialNumber;     // SN;
            if (!string.IsNullOrEmpty(csrDetails.UniqueIdentifier   /**/)) xn.Common = csrDetails.UniqueIdentifier; // UID;

            var xr = new X509Request(0, xn, rsaKeys);
            var md = MessageDigest.CreateByName(messageDigest); ;
            xr.Sign(rsaKeys, md);
            using (var bio = BIO.MemoryBuffer())
            {
                xr.Write(bio);
                return new Csr(bio.ReadString());
            }
        }
コード例 #6
0
        public void TestGenCSR()
        {
            var pem = File.ReadAllText("openssl-rsagen-privatekey.txt");
            var rsa = CryptoKey.FromPrivateKey(pem, null);
            //pem = File.ReadAllText("openssl-rsagen-publickey.txt");
            //rsa = CryptoKey.FromPublicKey(pem, null);

            var nam = new X509Name();
            nam.Common = "FOOBAR";
            nam.Country = "US";

            var csr = new X509Request();
            csr.PublicKey = rsa;
            csr.Subject = nam;
            csr.Sign(rsa, MessageDigest.SHA256);

            File.WriteAllText("openssl-requ-csr.txt", csr.PEM);
            using (var bioOut = BIO.MemoryBuffer())
            {
                csr.Write_DER(bioOut);
                var arr = bioOut.ReadBytes((int)bioOut.BytesPending);

                File.WriteAllBytes("openssl-requ-csr.der", arr.Array);
            }

            //using (var bioIn = BIO.MemoryBuffer())
            //{
            //    var pem2 = File.ReadAllText("openssl-requ-csr.txt");
            //    bioIn.Write(pem2);

            //    var csr = new X509Request()
            //    var x509 = new X509Certificate(bioIn);

            //}
        }
コード例 #7
0
ファイル: ResponderID.cs プロジェクト: woutersmit/NBitcoin
		public ResponderID(
            X509Name id)
        {
			if (id == null)
				throw new ArgumentNullException("id");

			this.id = id;
        }
コード例 #8
0
		internal TbsCertificateStructure(
			Asn1Sequence seq)
		{
			int seqStart = 0;

			this.seq = seq;

			//
			// some certficates don't include a version number - we assume v1
			//
			if (seq[0] is DerTaggedObject)
			{
				version = DerInteger.GetInstance((Asn1TaggedObject)seq[0], true);
			}
			else
			{
				seqStart = -1;          // field 0 is missing!
				version = new DerInteger(0);
			}

			serialNumber = DerInteger.GetInstance(seq[seqStart + 1]);

			signature = AlgorithmIdentifier.GetInstance(seq[seqStart + 2]);
			issuer = X509Name.GetInstance(seq[seqStart + 3]);

			//
			// before and after dates
			//
			Asn1Sequence  dates = (Asn1Sequence)seq[seqStart + 4];

			startDate = Time.GetInstance(dates[0]);
			endDate = Time.GetInstance(dates[1]);

			subject = X509Name.GetInstance(seq[seqStart + 5]);

			//
			// public key info.
			//
			subjectPublicKeyInfo = SubjectPublicKeyInfo.GetInstance(seq[seqStart + 6]);

			for (int extras = seq.Count - (seqStart + 6) - 1; extras > 0; extras--)
			{
				DerTaggedObject extra = (DerTaggedObject) seq[seqStart + 6 + extras];

				switch (extra.TagNo)
				{
					case 1:
						issuerUniqueID = DerBitString.GetInstance(extra, false);
						break;
					case 2:
						subjectUniqueID = DerBitString.GetInstance(extra, false);
						break;
					case 3:
						extensions = X509Extensions.GetInstance(extra);
						break;
				}
			}
		}
コード例 #9
0
		private IssuerAndSerialNumber(
            Asn1Sequence seq)
        {
			if (seq.Count != 2)
				throw new ArgumentException("Wrong number of elements in sequence", "seq");

			this.name = X509Name.GetInstance(seq[0]);
            this.certSerialNumber = DerInteger.GetInstance(seq[1]);
        }
コード例 #10
0
ファイル: ServiceLocator.cs プロジェクト: woutersmit/NBitcoin
		public ServiceLocator(
			X509Name	issuer,
			Asn1Object	locator)
		{
			if (issuer == null)
				throw new ArgumentNullException("issuer");

			this.issuer = issuer;
			this.locator = locator;
		}
コード例 #11
0
ファイル: ServiceLocator.cs プロジェクト: woutersmit/NBitcoin
		private ServiceLocator(
			Asn1Sequence seq)
		{
			this.issuer = X509Name.GetInstance(seq[0]);

			if (seq.Count > 1)
			{
				this.locator = seq[1].ToAsn1Object();
			}
		}
コード例 #12
0
		public CertificationRequestInfo(
            X509Name				subject,
            SubjectPublicKeyInfo	pkInfo,
            Asn1Set					attributes)
        {
            this.subject = subject;
            this.subjectPKInfo = pkInfo;
            this.attributes = attributes;

			if (subject == null || version == null || subjectPKInfo == null)
            {
                throw new ArgumentException(
					"Not all mandatory fields set in CertificationRequestInfo generator.");
            }
        }
コード例 #13
0
ファイル: CrlIdentifier.cs プロジェクト: woutersmit/NBitcoin
		public CrlIdentifier(
			X509Name	crlIssuer,
			DateTime	crlIssuedTime,
			BigInteger	crlNumber)
		{
			if (crlIssuer == null)
				throw new ArgumentNullException("crlIssuer");

			this.crlIssuer = crlIssuer;
			this.crlIssuedTime = new DerUtcTime(crlIssuedTime);

			if (crlNumber != null)
			{
				this.crlNumber = new DerInteger(crlNumber);
			}
		}
コード例 #14
0
ファイル: CrlIdentifier.cs プロジェクト: woutersmit/NBitcoin
		private CrlIdentifier(
			Asn1Sequence seq)
		{
			if (seq == null)
				throw new ArgumentNullException("seq");
			if (seq.Count < 2 || seq.Count > 3)
				throw new ArgumentException("Bad sequence size: " + seq.Count, "seq");

			this.crlIssuer = X509Name.GetInstance(seq[0]);
			this.crlIssuedTime = DerUtcTime.GetInstance(seq[1]);

			if (seq.Count > 2)
			{
				this.crlNumber = DerInteger.GetInstance(seq[2]);
			}
		}
コード例 #15
0
ファイル: TestSSL.cs プロジェクト: yaobos/openssl-net
		X509Certificate CreateCertificate(X509CertificateAuthority ca, string name, Configuration cfg, string section)
		{
			var now = DateTime.Now;
			var future = now + TimeSpan.FromDays(365);

			using (var subject = new X509Name(name))
			using (var rsa = new RSA())
			{
				rsa.GenerateKeys(1024, BigNumber.One, null, null);
				using (var key = new CryptoKey(rsa))
				{
					var request = new X509Request(1, subject, key);
					var cert = ca.ProcessRequest(request, now, future, cfg, section);
					cert.PrivateKey = key;
					return cert;
				}
			}
		}
コード例 #16
0
ファイル: CertTemplate.cs プロジェクト: woutersmit/NBitcoin
        private CertTemplate(Asn1Sequence seq)
        {
            this.seq = seq;

            foreach (Asn1TaggedObject tObj in seq)
            {
                switch (tObj.TagNo)
                {
                case 0:
                    version = DerInteger.GetInstance(tObj, false);
                    break;
                case 1:
                    serialNumber = DerInteger.GetInstance(tObj, false);
                    break;
                case 2:
                    signingAlg = AlgorithmIdentifier.GetInstance(tObj, false);
                    break;
                case 3:
                    issuer = X509Name.GetInstance(tObj, true); // CHOICE
                    break;
                case 4:
                    validity = OptionalValidity.GetInstance(Asn1Sequence.GetInstance(tObj, false));
                    break;
                case 5:
                    subject = X509Name.GetInstance(tObj, true); // CHOICE
                    break;
                case 6:
                    publicKey = SubjectPublicKeyInfo.GetInstance(tObj, false);
                    break;
                case 7:
                    issuerUID = DerBitString.GetInstance(tObj, false);
                    break;
                case 8:
                    subjectUID = DerBitString.GetInstance(tObj, false);
                    break;
                case 9:
                    extensions = X509Extensions.GetInstance(tObj, false);
                    break;
                default:
                    throw new ArgumentException("unknown tag: " + tObj.TagNo, "seq");
                }
            }
        }
コード例 #17
0
		private CertificationRequestInfo(
            Asn1Sequence seq)
        {
            version = (DerInteger) seq[0];

			subject = X509Name.GetInstance(seq[1]);
            subjectPKInfo = SubjectPublicKeyInfo.GetInstance(seq[2]);

			//
            // some CertificationRequestInfo objects seem to treat this field
            // as optional.
            //
            if (seq.Count > 3)
            {
                DerTaggedObject tagobj = (DerTaggedObject) seq[3];
                attributes = Asn1Set.GetInstance(tagobj, false);
            }

			if (subject == null || version == null || subjectPKInfo == null)
            {
                throw new ArgumentException(
					"Not all mandatory fields set in CertificationRequestInfo generator.");
            }
        }
コード例 #18
0
		public void CanCreateWithArgs()
		{
			int serial = 101;
			X509Name subject = new X509Name("CN=localhost");
			X509Name issuer = new X509Name("CN=Root");

			CryptoKey key = new CryptoKey(new DSA(true));
			DateTime start = DateTime.Now;
			DateTime end = start + TimeSpan.FromMinutes(10);

			using (X509Certificate cert = new X509Certificate(serial, subject, issuer, key, start, end)) {
				Assert.AreEqual(subject, cert.Subject);
				Assert.AreEqual(issuer, cert.Issuer);
				Assert.AreEqual(serial, cert.SerialNumber);

				// We compare short date/time strings here because the wrapper can't handle milliseconds
				Assert.AreEqual(start.ToShortDateString(), cert.NotBefore.ToShortDateString());
				Assert.AreEqual(start.ToShortTimeString(), cert.NotBefore.ToShortTimeString());
			}
		}
コード例 #19
0
ファイル: Identity.cs プロジェクト: yaobos/openssl-net
		/// <summary>
		/// Create a X509Request for this identity, using the specified name and digest.
		/// </summary>
		/// <param name="name"></param>
		/// <param name="digest"></param>
		/// <returns></returns>
		public X509Request CreateRequest(string name, MessageDigest digest)
		{
			var subject = new X509Name(name);
			var request = new X509Request(2, subject, key);

			request.Sign(key, digest);

			return request;
		}
コード例 #20
0
 public IssuerAndSerialNumber(
     Asn1Sequence seq)
 {
     this.name = X509Name.GetInstance(seq[0]);
     this.serialNumber = (DerInteger) seq[1];
 }
コード例 #21
0
 public AttributeCertificateIssuer(X509Name principal)
 {
     this.form = new V2Form(new GeneralNames(new GeneralName(principal)));
 }
コード例 #22
0
        internal string AliasOf(PkiCertificate cert)
        {
            var x509Name = new X509Name(cert.SubjectName);

            return((x509Name.GetValueList(X509Name.CN)?[0] ?? cert.SubjectName) as string);
        }
コード例 #23
0
        /// <summary>
        /// Factory method that creates a X509CertificateAuthority instance with
        /// an internal self signed certificate. This method allows creation without
        /// the need for the Configuration file, X509V3Extensions may be added
        /// with the X509V3ExtensionList parameter
        /// </summary>
        /// <param name="seq"></param>
        /// <param name="key"></param>
        /// <param name="digest"></param>
        /// <param name="subject"></param>
        /// <param name="start"></param>
        /// <param name="validity"></param>
        /// <param name="extensions"></param>
        /// <returns></returns>
        public static X509CertificateAuthority SelfSigned(
            ISequenceNumber seq,
            CryptoKey key,
            MessageDigest digest,
            X509Name subject,
            DateTime start,
            TimeSpan validity,
            X509V3ExtensionList extensions)
        {
            X509Certificate cert = new X509Certificate(
                seq.Next(),
                subject,
                subject,
                key,
                start,
                start + validity);

            if (null != extensions)
            {
                foreach (X509V3ExtensionValue extValue in extensions)
                {
                    X509Extension ext = new X509Extension(cert, cert, extValue.Name, extValue.IsCritical, extValue.Value);
                    cert.AddExtension(ext);
                }
            }

            cert.Sign(key, digest);

            return new X509CertificateAuthority(cert, key, seq, null);
		}
コード例 #24
0
 /// <summary>
 /// Set the issuer distinguished name.
 /// The issuer is the entity whose private key is used to sign the certificate.
 /// </summary>
 /// <param name="issuer">The issuers DN.</param>
 public void SetIssuerDN(
     X509Name issuer)
 {
     tbsGen.SetIssuer(issuer);
 }
コード例 #25
0
 public AttributeCertificateHolder(
     X509Name principal)
 {
     holder = new Holder(GenerateGeneralNames(principal));
 }
コード例 #26
0
ファイル: CertificateHelper.cs プロジェクト: yoimhere/IPASign
 public static X509Certificate FindBySubjectDN(List <X509Certificate> certificates, X509Name subjectDN)
 {
     foreach (X509Certificate certificate in certificates)
     {
         if (certificate.SubjectDN.Equivalent(subjectDN))
         {
             return(certificate);
         }
     }
     return(null);
 }
コード例 #27
0
        public async Task ValidateMergeCertificate()
        {
            string serverCertificateName = Recording.GenerateId();

            // Generate the request.
            CertificatePolicy policy = new CertificatePolicy(WellKnownIssuerNames.Unknown, "CN=Azure SDK")
            {
                CertificateTransparency = false,
                ContentType             = CertificateContentType.Pkcs12,
            };

            CertificateOperation operation = await Client.StartCreateCertificateAsync(serverCertificateName, policy);

            RegisterForCleanup(serverCertificateName);
            await using IAsyncDisposable disposableOperation = EnsureDeleted(operation);

            // Read the CA.
            byte[]           caCertificateBytes = Convert.FromBase64String(CaPublicKeyBase64);
            X509Certificate2 caCertificate      = new X509Certificate2(caCertificateBytes);

            // Read CA private key since getting it from caCertificate above throws.
            AsymmetricCipherKeyPair caPrivateKey;

            using (StringReader caPrivateKeyReader = new StringReader(CaPrivateKeyPem))
            {
                Org.BouncyCastle.OpenSsl.PemReader reader = new Org.BouncyCastle.OpenSsl.PemReader(caPrivateKeyReader);
                caPrivateKey = (AsymmetricCipherKeyPair)reader.ReadObject();
            }

            // Read the CSR.
            Pkcs10CertificationRequest csr     = new Pkcs10CertificationRequest(operation.Properties.Csr);
            CertificationRequestInfo   csrInfo = csr.GetCertificationRequestInfo();

            // Parse the issuer subject name.
            Hashtable oidLookup = new Hashtable(X509Name.DefaultLookup)
            {
                { "s", new DerObjectIdentifier("2.5.4.8") },
            };

            X509Name issuerName = new X509Name(true, oidLookup, caCertificate.Subject);

            // Sign the request.
            X509V3CertificateGenerator generator = new X509V3CertificateGenerator();

            generator.SetIssuerDN(issuerName);
            generator.SetSerialNumber(BigInteger.One);
            generator.SetNotBefore(DateTime.Now);
            generator.SetNotAfter(DateTime.Now.AddDays(1));
            generator.SetSubjectDN(csrInfo.Subject);
            generator.SetPublicKey(csr.GetPublicKey());

            Asn1SignatureFactory signatureFactory      = new Asn1SignatureFactory("SHA256WITHRSA", caPrivateKey.Private);
            X509Certificate      serverSignedPublicKey = generator.Generate(signatureFactory);

            // Merge the certificate chain.
            MergeCertificateOptions       options = new MergeCertificateOptions(serverCertificateName, new[] { serverSignedPublicKey.GetEncoded(), caCertificateBytes });
            KeyVaultCertificateWithPolicy mergedServerCertificate = await Client.MergeCertificateAsync(options);

            X509Certificate2 serverCertificate = new X509Certificate2(mergedServerCertificate.Cer);

            Assert.AreEqual(csrInfo.Subject.ToString(), serverCertificate.Subject);
            Assert.AreEqual(serverCertificateName, mergedServerCertificate.Name);

            KeyVaultCertificateWithPolicy completedServerCertificate = await WaitForCompletion(operation);

            Assert.AreEqual(mergedServerCertificate.Name, completedServerCertificate.Name);
            CollectionAssert.AreEqual(mergedServerCertificate.Cer, completedServerCertificate.Cer);
        }
コード例 #28
0
        public Org.BouncyCastle.X509.X509Certificate GenerateCertificate(SecureRandom random,
                                                                         string subjectName,
                                                                         AsymmetricCipherKeyPair subjectKeyPair,
                                                                         BigInteger subjectSerialNumber,
                                                                         string[] subjectAlternativeNames,
                                                                         string issuerName,
                                                                         AsymmetricCipherKeyPair issuerKeyPair,
                                                                         BigInteger issuerSerialNumber,
                                                                         bool isCertificateAuthority,
                                                                         KeyPurposeID[] usages)
        {
            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(20);

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

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

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

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

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



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

            return(certificate);
        }
コード例 #29
0
 public IssuerAndSerialNumber(X509Name name, DerInteger certSerialNumber)
 {
     this.name             = name;
     this.certSerialNumber = certSerialNumber;
 }
コード例 #30
0
 public IssuerAndSerialNumber(X509Name name, BigInteger certSerialNumber)
 {
     this.name             = name;
     this.certSerialNumber = new DerInteger(certSerialNumber);
 }
コード例 #31
0
ファイル: ServiceLocator.cs プロジェクト: waffle-iron/nequeo
 public ServiceLocator(
     X509Name issuer)
     : this(issuer, null)
 {
 }
コード例 #32
0
 /// <summary>
 /// Set the subject distinguished name.
 /// The subject describes the entity associated with the public key.
 /// </summary>
 /// <param name="subject"/>
 public void SetSubjectDN(
     X509Name subject)
 {
     tbsGen.SetSubject(subject);
 }
コード例 #33
0
        /// <summary>
        /// Creates a cert with the connectionstring (token) and stores it in the given cert store.
        /// </summary>
        public async static Task WriteAsync(string name, string connectionString, string storeType, string storePath)
        {
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new ArgumentException("Token not found in X509Store and no new token provided!");
            }

            SecureRandom random = new SecureRandom();
            KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, 2048);
            RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator();
            keyPairGenerator.Init(keyGenerationParameters);
            AsymmetricCipherKeyPair keys = keyPairGenerator.GenerateKeyPair();

            ArrayList nameOids = new ArrayList();
            nameOids.Add(X509Name.CN);
            ArrayList nameValues = new ArrayList();
            nameValues.Add(name);
            X509Name subjectDN = new X509Name(nameOids, nameValues);
            X509Name issuerDN = subjectDN;

            X509V3CertificateGenerator cg = new X509V3CertificateGenerator();
            cg.SetSerialNumber(BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random));
            cg.SetIssuerDN(issuerDN);
            cg.SetSubjectDN(subjectDN);
            cg.SetNotBefore(DateTime.Now);
            cg.SetNotAfter(DateTime.Now.AddMonths(12));
            cg.SetPublicKey(keys.Public);
            cg.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DataEncipherment));

            // encrypt the token with the public key so only the owner of the assoc. private key can decrypt it and
            // "hide" it in the instruction code cert extension
            RSA rsa = RSA.Create();
            RSAParameters rsaParams = new RSAParameters();
            RsaKeyParameters keyParams = (RsaKeyParameters)keys.Public;

            rsaParams.Modulus = new byte[keyParams.Modulus.ToByteArrayUnsigned().Length];
            keyParams.Modulus.ToByteArrayUnsigned().CopyTo(rsaParams.Modulus, 0);

            rsaParams.Exponent = new byte[keyParams.Exponent.ToByteArrayUnsigned().Length];
            keyParams.Exponent.ToByteArrayUnsigned().CopyTo(rsaParams.Exponent, 0);

            rsa.ImportParameters(rsaParams);
            if (rsa != null)
            {
                byte[] bytes = rsa.Encrypt(Encoding.ASCII.GetBytes(connectionString), RSAEncryptionPadding.OaepSHA1);
                if (bytes != null)
                {
                    cg.AddExtension(X509Extensions.InstructionCode, false, bytes);
                }
                else
                {
                    throw new CryptographicException("Can not encrypt IoTHub security token using generated public key!");
                }
            }

            // sign the cert with the private key
            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", keys.Private, random);
            Org.BouncyCastle.X509.X509Certificate x509 = cg.Generate(signatureFactory);

            // create a PKCS12 store for the cert and its private key
            X509Certificate2 certificate = null;
            using (MemoryStream pfxData = new MemoryStream())
            {
                Pkcs12StoreBuilder builder = new Pkcs12StoreBuilder();
                builder.SetUseDerEncoding(true);
                Pkcs12Store pkcsStore = builder.Build();
                X509CertificateEntry[] chain = new X509CertificateEntry[1];
                string passcode = Guid.NewGuid().ToString();
                chain[0] = new X509CertificateEntry(x509);
                pkcsStore.SetKeyEntry(name, new AsymmetricKeyEntry(keys.Private), chain);
                pkcsStore.Save(pfxData, passcode.ToCharArray(), random);

                // create X509Certificate2 object from PKCS12 file
                certificate = CertificateFactory.CreateCertificateFromPKCS12(pfxData.ToArray(), passcode);

                // handle each store type differently
                switch (storeType)
                {
                    case CertificateStoreType.Directory:
                        {
                            // Add to DirectoryStore
                            using (DirectoryCertificateStore store = new DirectoryCertificateStore())
                            {
                                store.Open(storePath);
                                X509CertificateCollection certificates = await store.Enumerate().ConfigureAwait(false);

                                // remove any existing cert with our name from the store
                                foreach (X509Certificate2 cert in certificates)
                                {
                                    if (cert.SubjectName.Decode(X500DistinguishedNameFlags.None | X500DistinguishedNameFlags.DoNotUseQuotes).Equals("CN=" + name, StringComparison.OrdinalIgnoreCase))
                                    {
                                        await store.Delete(cert.Thumbprint).ConfigureAwait(false);
                                    }
                                }

                                // add new one
                                await store.Add(certificate).ConfigureAwait(false);
                            }
                            break;
                        }
                    case CertificateStoreType.X509Store:
                        {
                            // Add to X509Store
                            using (X509Store store = new X509Store(storePath, StoreLocation.CurrentUser))
                            {
                                store.Open(OpenFlags.ReadWrite);

                                // remove any existing cert with our name from the store
                                foreach (X509Certificate2 cert in store.Certificates)
                                {
                                    if (cert.SubjectName.Decode(X500DistinguishedNameFlags.None | X500DistinguishedNameFlags.DoNotUseQuotes).Equals("CN=" + name, StringComparison.OrdinalIgnoreCase))
                                    {
                                        store.Remove(cert);
                                    }
                                }

                                // add new cert to store
                                try
                                {
                                    store.Add(certificate);
                                }
                                catch (Exception e)
                                {
                                    throw new Exception($"Not able to add cert to the requested store type '{storeType}' (exception message: '{e.Message}'.");
                                }
                            }
                            break;
                        }
                    default:
                        {
                            throw new Exception($"The requested store type '{storeType}' is not supported. Please change.");
                        }
                }
                return;
            }
        }
コード例 #34
0
        protected override void CompleteWizard()
        {
            // Generate the CSR
            X509Name subjectName =
                new X509Name(string.Format("C={0},ST={1},L={2},O={3},OU={4},CN={5}",
                                           _wizardData.Country,
                                           _wizardData.State,
                                           _wizardData.City,
                                           _wizardData.Organization,
                                           _wizardData.Unit,
                                           _wizardData.CommonName));

            // Generate the private/public keypair
            RsaKeyPairGenerator      kpgen           = new RsaKeyPairGenerator();
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();

            kpgen.Init(new KeyGenerationParameters(new SecureRandom(randomGenerator), _wizardData.Length));
            AsymmetricCipherKeyPair keyPair = kpgen.GenerateKeyPair();
            // Generate the CSR

            Asn1Set attributes = new DerSet(
                new DerSequence(
                    new DerObjectIdentifier("1.3.6.1.4.1.311.13.2.3"),
                    new DerSet(new DerIA5String(Environment.OSVersion.Version.ToString()))),
                new DerSequence(
                    new DerObjectIdentifier("1.3.6.1.4.1.311.21.20"),
                    new DerSet(
                        new DerSequence(
                            new DerInteger(5),
                            new DerUtf8String(Environment.MachineName),
                            new DerUtf8String(Environment.UserName),
                            new DerUtf8String("JexusManager.exe")))),
                new DerSequence(
                    new DerObjectIdentifier("1.3.6.1.4.1.311.13.2.2"),
                    new DerSet(
                        new DerSequence(
                            new DerInteger(1),
                            new DerBmpString("Microsoft RSA SChannel Cryptographic Provider"),
                            new DerBitString(new byte[0])))),
                new DerSequence(
                    new DerObjectIdentifier("1.2.840.113549.1.9.14"),
                    new DerSet(
                        new DerSequence(
                            new DerSequence(
                                new DerObjectIdentifier("2.5.29.15"),
                                new DerBoolean(new byte[] { 0x01 }),
                                new DerOctetString(new byte[] { 0x03, 0x02, 0x04, 0xF0 })),
                            new DerSequence(
                                new DerObjectIdentifier("2.5.29.37"),
                                new DerOctetString(new byte[]
            {
                0x30, 0x0a, 0x06, 0x08,
                0x2b, 0x06, 0x01, 0x05,
                0x05, 0x07, 0x03, 0x01
            })),
                            new DerSequence(
                                new DerObjectIdentifier("1.2.840.113549.1.9.15"),
                                new DerOctetString(new byte[]
            {
                0x30, 0x69, 0x30, 0x0e,
                0x06, 0x08, 0x2a, 0x86,
                0x48, 0x86, 0xf7, 0x0d,
                0x03, 0x02, 0x02, 0x02,
                0x00, 0x80, 0x30, 0x0e,
                0x06, 0x08, 0x2a, 0x86,
                0x48, 0x86, 0xf7, 0x0d,
                0x03, 0x04, 0x02, 0x02,
                0x00, 0x80, 0x30, 0x0b,
                0x06, 0x09, 0x60, 0x86,
                0x48, 0x01, 0x65, 0x03,
                0x04, 0x01, 0x2a, 0x30,
                0x0b, 0x06, 0x09, 0x60,
                0x86, 0x48, 0x01, 0x65,
                0x03, 0x04, 0x01, 0x2d,
                0x30, 0x0b, 0x06, 0x09,
                0x60, 0x86, 0x48, 0x01,
                0x65, 0x03, 0x04, 0x01,
                0x02, 0x30, 0x0b, 0x06,
                0x09, 0x60, 0x86, 0x48,
                0x01, 0x65, 0x03, 0x04,
                0x01, 0x05, 0x30, 0x07,
                0x06, 0x05, 0x2b, 0x0e,
                0x03, 0x02, 0x07, 0x30,
                0x0a, 0x06, 0x08, 0x2a,
                0x86, 0x48, 0x86, 0xf7,
                0x0d, 0x03, 0x07
            })),
                            new DerSequence(
                                new DerObjectIdentifier("2.5.29.14"),
                                new DerOctetString(new byte[]
            {
                0x04, 0x14, 0xaa, 0x25,
                0xd9, 0xa2, 0x39, 0x7e,
                0x49, 0xd2, 0x94, 0x85,
                0x7e, 0x82, 0xa8, 0x8f,
                0x3b, 0x20, 0xf1, 0x4e, 0x65, 0xe5
            }))))));

            var signing = new Asn1SignatureFactory("SHA256withRSA", keyPair.Private);
            Pkcs10CertificationRequest kpGen = new Pkcs10CertificationRequest(signing, subjectName, keyPair.Public, attributes, keyPair.Private);

            using (var stream = new StreamWriter(_wizardData.FileName))
            {
                stream.WriteLine(_wizardData.UseIisStyle ? "-----BEGIN NEW CERTIFICATE REQUEST-----" : "-----BEGIN CERTIFICATE REQUEST-----");
                stream.WriteLine(Convert.ToBase64String(kpGen.GetDerEncoded(), Base64FormattingOptions.InsertLineBreaks));
                stream.WriteLine(_wizardData.UseIisStyle ? "-----END NEW CERTIFICATE REQUEST-----" : "-----END CERTIFICATE REQUEST-----");
            }

            var        key = DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters)keyPair.Private);
            PrivateKey pvk = new PrivateKey();

            pvk.RSA = new RSACryptoServiceProvider();
            pvk.RSA.ImportParameters(key);

            var file   = DialogHelper.GetPrivateKeyFile(subjectName.ToString());
            var folder = Path.GetDirectoryName(file);

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }

            pvk.Save(file);
        }
コード例 #35
0
        internal static void GetCertStatus(
            DateTime validDate,
            X509Crl crl,
            Object cert,
            CertStatus certStatus)
        {
            X509Crl bcCRL = null;

            try
            {
                bcCRL = new X509Crl(CertificateList.GetInstance((Asn1Sequence)Asn1Sequence.FromByteArray(crl.GetEncoded())));
            }
            catch (Exception exception)
            {
                throw new Exception("Bouncy Castle X509Crl could not be created.", exception);
            }

            X509CrlEntry crl_entry = (X509CrlEntry)bcCRL.GetRevokedCertificate(GetSerialNumber(cert));

            if (crl_entry == null)
            {
                return;
            }

            X509Name issuer = GetIssuerPrincipal(cert);

            if (issuer.Equivalent(crl_entry.GetCertificateIssuer(), true) ||
                issuer.Equivalent(crl.IssuerDN, true))
            {
                DerEnumerated reasonCode = null;
                if (crl_entry.HasExtensions)
                {
                    try
                    {
                        reasonCode = DerEnumerated.GetInstance(
                            GetExtensionValue(crl_entry, X509Extensions.ReasonCode));
                    }
                    catch (Exception e)
                    {
                        new Exception(
                            "Reason code CRL entry extension could not be decoded.",
                            e);
                    }
                }

                // for reason keyCompromise, caCompromise, aACompromise or
                // unspecified
                if (!(validDate.Ticks < crl_entry.RevocationDate.Ticks) ||
                    reasonCode == null ||
                    reasonCode.Value.TestBit(0) ||
                    reasonCode.Value.TestBit(1) ||
                    reasonCode.Value.TestBit(2) ||
                    reasonCode.Value.TestBit(8))
                {
                    if (reasonCode != null)                     // (i) or (j) (1)
                    {
                        certStatus.Status = reasonCode.Value.SignValue;
                    }
                    else                     // (i) or (j) (2)
                    {
                        certStatus.Status = CrlReason.Unspecified;
                    }
                    certStatus.RevocationDate = new DateTimeObject(crl_entry.RevocationDate);
                }
            }
        }
コード例 #36
0
 public X509CrlEntry(
     CrlEntry c)
 {
     this.c = c;
     this.certificateIssuer = loadCertificateIssuer();
 }
コード例 #37
0
        // Only the ctor should be calling with isAuthority = true
        // if isAuthority, value for isMachineCert doesn't matter
        private X509CertificateContainer CreateCertificate(bool isAuthority, bool isMachineCert, X509Certificate signingCertificate, params string[] subjects)
        {
            if (!isAuthority ^ (signingCertificate != null))
            {
                throw new ArgumentException("Either isAuthority == true or signingCertificate is not null");
            }

            if (!isAuthority && (subjects == null || subjects.Length == 0))
            {
                throw new ArgumentException("If not creating an authority, must specify at least one Subject", "subjects");
            }

            if (!isAuthority && string.IsNullOrWhiteSpace(subjects[0]))
            {
                throw new ArgumentException("Certificate Subject must not be an empty string or only whitespace", "subjects");
            }

            EnsureInitialized();

            _certGenerator.Reset();
            _certGenerator.SetSignatureAlgorithm(_signatureAlthorithm);

            X509Name authorityX509Name = CreateX509Name(_authorityCanonicalName);

            var keyPair = isAuthority ? _authorityKeyPair : _keyPairGenerator.GenerateKeyPair();

            if (isAuthority)
            {
                _certGenerator.SetIssuerDN(authorityX509Name);
                _certGenerator.SetSubjectDN(authorityX509Name);

                var authorityKeyIdentifier = new AuthorityKeyIdentifier(
                    SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(_authorityKeyPair.Public),
                    new GeneralNames(new GeneralName(authorityX509Name)),
                    new BigInteger(7, _random).Abs());

                _certGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, true, authorityKeyIdentifier);
                _certGenerator.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(X509KeyUsage.DigitalSignature | X509KeyUsage.KeyAgreement | X509KeyUsage.KeyCertSign | X509KeyUsage.KeyEncipherment | X509KeyUsage.CrlSign));
            }
            else
            {
                X509Name subjectName = CreateX509Name(subjects[0]);
                _certGenerator.SetIssuerDN(PrincipalUtilities.GetSubjectX509Principal(signingCertificate));
                _certGenerator.SetSubjectDN(subjectName);

                _certGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, true, new AuthorityKeyIdentifierStructure(_authorityKeyPair.Public));
                _certGenerator.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(X509KeyUsage.DigitalSignature | X509KeyUsage.KeyAgreement | X509KeyUsage.KeyEncipherment));
            }

            _certGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.Public));

            _certGenerator.SetSerialNumber(new BigInteger(64 /*sizeInBits*/, _random).Abs());
            _certGenerator.SetNotBefore(_validityNotBefore);
            _certGenerator.SetNotAfter(_validityNotAfter);
            _certGenerator.SetPublicKey(keyPair.Public);

            _certGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(isAuthority));
            _certGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPClientAuth));

            if (!isAuthority)
            {
                if (isMachineCert)
                {
                    List <Asn1Encodable> subjectAlternativeNames = new List <Asn1Encodable>();

                    // All endpoints should also be in the Subject Alt Names
                    for (int i = 0; i < subjects.Length; i++)
                    {
                        if (!string.IsNullOrWhiteSpace(subjects[i]))
                        {
                            // Machine certs can have additional DNS names
                            subjectAlternativeNames.Add(new GeneralName(GeneralName.DnsName, subjects[i]));
                        }
                    }

                    _certGenerator.AddExtension(X509Extensions.SubjectAlternativeName, true, new DerSequence(subjectAlternativeNames.ToArray()));
                }
                else
                {
                    if (subjects.Length > 1)
                    {
                        var subjectAlternativeNames = new Asn1EncodableVector();

                        // Only add a SAN for the user if there are any
                        for (int i = 1; i < subjects.Length; i++)
                        {
                            if (!string.IsNullOrWhiteSpace(subjects[i]))
                            {
                                Asn1EncodableVector otherNames = new Asn1EncodableVector();
                                otherNames.Add(new DerObjectIdentifier(_upnObjectId));
                                otherNames.Add(new DerTaggedObject(true, 0, new DerUtf8String(subjects[i])));

                                Asn1Object genName = new DerTaggedObject(false, 0, new DerSequence(otherNames));

                                subjectAlternativeNames.Add(genName);
                            }
                        }
                        _certGenerator.AddExtension(X509Extensions.SubjectAlternativeName, true, new DerSequence(subjectAlternativeNames));
                    }
                }
            }

            var crlDistributionPoints = new DistributionPoint[1] {
                new DistributionPoint(new DistributionPointName(
                                          new GeneralNames(new GeneralName(GeneralName.UniformResourceIdentifier, _crlUri))), null, new GeneralNames(new GeneralName(authorityX509Name)))
            };
            var revocationListExtension = new CrlDistPoint(crlDistributionPoints);

            _certGenerator.AddExtension(X509Extensions.CrlDistributionPoints, false, revocationListExtension);

            X509Certificate cert = _certGenerator.Generate(_authorityKeyPair.Private, _random);

            EnsureCertificateValidity(cert);

            // For now, given that we don't know what format to return it in, preserve the formats so we have
            // the flexibility to do what we need to

            X509CertificateContainer container = new X509CertificateContainer();

            X509CertificateEntry[] chain = new X509CertificateEntry[1];
            chain[0] = new X509CertificateEntry(cert);

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

            store.SetKeyEntry("", new AsymmetricKeyEntry(keyPair.Private), chain);

            using (MemoryStream stream = new MemoryStream())
            {
                store.Save(stream, _password.ToCharArray(), _random);
                container.Pfx = stream.ToArray();
            }

            X509Certificate2 outputCert;

            if (isAuthority)
            {
                // don't hand out the private key for the cert when it's the authority
                outputCert = new X509Certificate2(cert.GetEncoded());
            }
            else
            {
                // Otherwise, allow encode with the private key. note that X509Certificate2.RawData will not provide the private key
                // you will have to re-export this cert if needed
                outputCert = new X509Certificate2(container.Pfx, _password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
            }

            container.Subject             = subjects[0];
            container.InternalCertificate = cert;
            container.Certificate         = outputCert;
            container.Thumbprint          = outputCert.Thumbprint;

            Trace.WriteLine("[CertificateGenerator] generated a certificate:");
            Trace.WriteLine(string.Format("    {0} = {1}", "isAuthority", isAuthority));
            if (!isAuthority)
            {
                Trace.WriteLine(string.Format("    {0} = {1}", "Signed by", signingCertificate.SubjectDN));
                Trace.WriteLine(string.Format("    {0} = {1}", "Subject (CN) ", subjects[0]));
                Trace.WriteLine(string.Format("    {0} = {1}", "Alt names ", string.Join(", ", subjects)));
            }
            Trace.WriteLine(string.Format("    {0} = {1}", "HasPrivateKey:", outputCert.HasPrivateKey));
            Trace.WriteLine(string.Format("    {0} = {1}", "Thumbprint", outputCert.Thumbprint));

            return(container);
        }
コード例 #38
0
        public virtual bool Match(
            object obj)
        {
            X509Crl c = obj as X509Crl;

            if (c == null)
            {
                return(false);
            }

            if (dateAndTime != null)
            {
                DateTime       dt = dateAndTime.Value;
                DateTime       tu = c.ThisUpdate;
                DateTimeObject nu = c.NextUpdate;

                if (dt.CompareTo(tu) < 0 || nu == null || dt.CompareTo(nu.Value) >= 0)
                {
                    return(false);
                }
            }

            if (issuers != null)
            {
                X509Name i = c.IssuerDN;

                bool found = false;

                foreach (X509Name issuer in issuers)
                {
                    if (issuer.Equivalent(i, true))
                    {
                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    return(false);
                }
            }

            if (maxCrlNumber != null || minCrlNumber != null)
            {
                Asn1OctetString extVal = c.GetExtensionValue(X509Extensions.CrlNumber);
                if (extVal == null)
                {
                    return(false);
                }

                IBigInteger cn = CrlNumber.GetInstance(
                    X509ExtensionUtilities.FromExtensionValue(extVal)).PositiveValue;

                if (maxCrlNumber != null && cn.CompareTo(maxCrlNumber) > 0)
                {
                    return(false);
                }

                if (minCrlNumber != null && cn.CompareTo(minCrlNumber) < 0)
                {
                    return(false);
                }
            }

            DerInteger dci = null;

            try
            {
                Asn1OctetString bytes = c.GetExtensionValue(X509Extensions.DeltaCrlIndicator);
                if (bytes != null)
                {
                    dci = DerInteger.GetInstance(X509ExtensionUtilities.FromExtensionValue(bytes));
                }
            }
            catch (Exception)
            {
                return(false);
            }

            if (dci == null)
            {
                if (DeltaCrlIndicatorEnabled)
                {
                    return(false);
                }
            }
            else
            {
                if (CompleteCrlEnabled)
                {
                    return(false);
                }

                if (maxBaseCrlNumber != null && dci.PositiveValue.CompareTo(maxBaseCrlNumber) > 0)
                {
                    return(false);
                }
            }

            if (issuingDistributionPointEnabled)
            {
                Asn1OctetString idp = c.GetExtensionValue(X509Extensions.IssuingDistributionPoint);
                if (issuingDistributionPoint == null)
                {
                    if (idp != null)
                    {
                        return(false);
                    }
                }
                else
                {
                    if (!Arrays.AreEqual(idp.GetOctets(), issuingDistributionPoint))
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
コード例 #39
0
        private void InitializeServerContext(
            X509Certificate serverCertificate,
            bool clientCertificateRequired,
            X509Chain caCerts,
            SslProtocols enabledSslProtocols,
            SslStrength sslStrength,
            bool checkCertificateRevocation)
        {
            if (serverCertificate == null)
            {
                throw new ArgumentNullException("serverCertificate", "Server certificate cannot be null");
            }
            if (!serverCertificate.HasPrivateKey)
            {
                throw new ArgumentException("Server certificate must have a private key", "serverCertificate");
            }

            // Initialize the context
            sslContext = new SslContext(SslMethod.SSLv23_server_method);

            // Remove support for protocols not specified in the enabledSslProtocols
            if ((enabledSslProtocols & SslProtocols.Ssl2) != SslProtocols.Ssl2)
            {
                sslContext.Options |= SslOptions.SSL_OP_NO_SSLv2;
            }
            if ((enabledSslProtocols & SslProtocols.Ssl3) != SslProtocols.Ssl3 &&
                ((enabledSslProtocols & SslProtocols.Default) != SslProtocols.Default))
            {
                // no SSLv3 support
                sslContext.Options |= SslOptions.SSL_OP_NO_SSLv3;
            }
            if ((enabledSslProtocols & SslProtocols.Tls) != SslProtocols.Tls &&
                (enabledSslProtocols & SslProtocols.Default) != SslProtocols.Default)
            {
                sslContext.Options |= SslOptions.SSL_OP_NO_TLSv1;
            }

            /*
             * // Initialize the context with the specified ssl version
             * switch (enabledSslProtocols)
             * {
             *  case SslProtocols.None:
             *      throw new ArgumentException("SslProtocol.None is not supported", "enabledSslProtocols");
             *      break;
             *  case SslProtocols.Ssl2:
             *      sslContext = new SslContext(SslMethod.SSLv2_server_method);
             *      break;
             *  case SslProtocols.Ssl3:
             *  case SslProtocols.Default:
             *      sslContext = new SslContext(SslMethod.SSLv3_server_method);
             *      break;
             *  case SslProtocols.Tls:
             *      sslContext = new SslContext(SslMethod.TLSv1_server_method);
             *      break;
             * }
             */
            // Set the context mode
            sslContext.Mode = SslMode.SSL_MODE_AUTO_RETRY;
            // Set the workaround options
            sslContext.Options = SslOptions.SSL_OP_ALL;
            // Set the client certificate verification callback if we are requiring client certs
            if (clientCertificateRequired)
            {
                sslContext.SetVerify(VerifyMode.SSL_VERIFY_PEER | VerifyMode.SSL_VERIFY_FAIL_IF_NO_PEER_CERT, remoteCertificateSelectionCallback);
            }
            else
            {
                sslContext.SetVerify(VerifyMode.SSL_VERIFY_NONE, null);
            }

            // Set the client certificate max verification depth
            sslContext.SetVerifyDepth(10);
            // Set the certificate store and ca list
            if (caCerts != null)
            {
                // Don't take ownership of the X509Store IntPtr.  When we
                // SetCertificateStore, the context takes ownership of the store pointer.
                X509Store cert_store = new X509Store(caCerts, false);
                sslContext.SetCertificateStore(cert_store);
                Core.Stack <X509Name> name_stack = new Core.Stack <X509Name>();
                foreach (X509Certificate cert in caCerts)
                {
                    X509Name subject = cert.Subject;
                    name_stack.Add(subject);
                }
                // Assign the stack to the context
                sslContext.CAList = name_stack;
            }
            // Set the cipher string
            sslContext.SetCipherList(GetCipherString(false, enabledSslProtocols, sslStrength));
            // Set the certificate
            sslContext.UseCertificate(serverCertificate);
            // Set the private key
            sslContext.UsePrivateKey(serverCertificate.PrivateKey);
            // Set the session id context
            sslContext.SetSessionIdContext(Encoding.ASCII.GetBytes(AppDomain.CurrentDomain.FriendlyName));
        }
コード例 #40
0
        /// <summary>
        /// Gets the Subject/Issuer information for the Certificate Authority.
        /// </summary>
        /// <returns>X509Name object populated with the subject information for the Certificate Authority.</returns>
        private static X509Name GetCertificateAuthoritySubject()
        {
            X509Name subject = new X509Name();
            subject.Common = "Alpaca Self Signing Certificate";
            subject.Country = "UK";
            subject.StateOrProvince = "Hampshire";
            subject.Organization = "MarvinAlpaca";
            subject.OrganizationUnit = "Testings";

            return subject;
        }
コード例 #41
0
        public virtual PkixCertPathValidatorResult Validate(
            PkixCertPath certPath,
            PkixParameters paramsPkix)
        {
            if (paramsPkix.GetTrustAnchors() == null)
            {
                throw new ArgumentException(
                          "trustAnchors is null, this is not allowed for certification path validation.",
                          "parameters");
            }

            //
            // 6.1.1 - inputs
            //

            //
            // (a)
            //
            IList certs = certPath.Certificates;
            int   n     = certs.Count;

            if (certs.Count == 0)
            {
                throw new PkixCertPathValidatorException("Certification path is empty.", null, certPath, 0);
            }

            //
            // (b)
            //
            // DateTime validDate = PkixCertPathValidatorUtilities.GetValidDate(paramsPkix);

            //
            // (c)
            //
            ISet userInitialPolicySet = paramsPkix.GetInitialPolicies();

            //
            // (d)
            //
            TrustAnchor trust;

            try
            {
                trust = PkixCertPathValidatorUtilities.FindTrustAnchor(
                    (X509Certificate)certs[certs.Count - 1],
                    paramsPkix.GetTrustAnchors());
            }
            catch (Exception e)
            {
                throw new PkixCertPathValidatorException(e.Message, e, certPath, certs.Count - 1);
            }

            if (trust == null)
            {
                throw new PkixCertPathValidatorException("Trust anchor for certification path not found.", null, certPath, -1);
            }

            //
            // (e), (f), (g) are part of the paramsPkix object.
            //
            IEnumerator certIter;
            int         index = 0;
            int         i;

            // Certificate for each interation of the validation loop
            // Signature information for each iteration of the validation loop
            //
            // 6.1.2 - setup
            //

            //
            // (a)
            //
            IList[] policyNodes = new IList[n + 1];
            for (int j = 0; j < policyNodes.Length; j++)
            {
                policyNodes[j] = Platform.CreateArrayList();
            }

            ISet policySet = new HashSet();

            policySet.Add(Rfc3280CertPathUtilities.ANY_POLICY);

            PkixPolicyNode validPolicyTree = new PkixPolicyNode(Platform.CreateArrayList(), 0, policySet, null, new HashSet(),
                                                                Rfc3280CertPathUtilities.ANY_POLICY, false);

            policyNodes[0].Add(validPolicyTree);

            //
            // (b) and (c)
            //
            PkixNameConstraintValidator nameConstraintValidator = new PkixNameConstraintValidator();

            // (d)
            //
            int  explicitPolicy;
            ISet acceptablePolicies = new HashSet();

            if (paramsPkix.IsExplicitPolicyRequired)
            {
                explicitPolicy = 0;
            }
            else
            {
                explicitPolicy = n + 1;
            }

            //
            // (e)
            //
            int inhibitAnyPolicy;

            if (paramsPkix.IsAnyPolicyInhibited)
            {
                inhibitAnyPolicy = 0;
            }
            else
            {
                inhibitAnyPolicy = n + 1;
            }

            //
            // (f)
            //
            int policyMapping;

            if (paramsPkix.IsPolicyMappingInhibited)
            {
                policyMapping = 0;
            }
            else
            {
                policyMapping = n + 1;
            }

            //
            // (g), (h), (i), (j)
            //
            AsymmetricKeyParameter workingPublicKey;
            X509Name workingIssuerName;

            X509Certificate sign = trust.TrustedCert;

            try
            {
                if (sign != null)
                {
                    workingIssuerName = sign.SubjectDN;
                    workingPublicKey  = sign.GetPublicKey();
                }
                else
                {
                    workingIssuerName = new X509Name(trust.CAName);
                    workingPublicKey  = trust.CAPublicKey;
                }
            }
            catch (ArgumentException ex)
            {
                throw new PkixCertPathValidatorException("Subject of trust anchor could not be (re)encoded.", ex, certPath,
                                                         -1);
            }

            AlgorithmIdentifier workingAlgId = null;

            try
            {
                workingAlgId = PkixCertPathValidatorUtilities.GetAlgorithmIdentifier(workingPublicKey);
            }
            catch (PkixCertPathValidatorException e)
            {
                throw new PkixCertPathValidatorException(
                          "Algorithm identifier of public key of trust anchor could not be read.", e, certPath, -1);
            }

//			DerObjectIdentifier workingPublicKeyAlgorithm = workingAlgId.Algorithm;
//			Asn1Encodable workingPublicKeyParameters = workingAlgId.Parameters;

            //
            // (k)
            //
            int maxPathLength = n;

            //
            // 6.1.3
            //

            X509CertStoreSelector certConstraints = paramsPkix.GetTargetCertConstraints();

            if (certConstraints != null && !certConstraints.Match((X509Certificate)certs[0]))
            {
                throw new PkixCertPathValidatorException(
                          "Target certificate in certification path does not match targetConstraints.", null, certPath, 0);
            }

            //
            // initialize CertPathChecker's
            //
            IList pathCheckers = paramsPkix.GetCertPathCheckers();

            certIter = pathCheckers.GetEnumerator();

            while (certIter.MoveNext())
            {
                ((PkixCertPathChecker)certIter.Current).Init(false);
            }

            X509Certificate cert = null;

            for (index = certs.Count - 1; index >= 0; index--)
            {
                // try
                // {
                //
                // i as defined in the algorithm description
                //
                i = n - index;

                //
                // set certificate to be checked in this round
                // sign and workingPublicKey and workingIssuerName are set
                // at the end of the for loop and initialized the
                // first time from the TrustAnchor
                //
                cert = (X509Certificate)certs[index];

                //
                // 6.1.3
                //

                Rfc3280CertPathUtilities.ProcessCertA(certPath, paramsPkix, index, workingPublicKey,
                                                      workingIssuerName, sign);

                Rfc3280CertPathUtilities.ProcessCertBC(certPath, index, nameConstraintValidator);

                validPolicyTree = Rfc3280CertPathUtilities.ProcessCertD(certPath, index,
                                                                        acceptablePolicies, validPolicyTree, policyNodes, inhibitAnyPolicy);

                validPolicyTree = Rfc3280CertPathUtilities.ProcessCertE(certPath, index, validPolicyTree);

                Rfc3280CertPathUtilities.ProcessCertF(certPath, index, validPolicyTree, explicitPolicy);

                //
                // 6.1.4
                //

                if (i != n)
                {
                    if (cert != null && cert.Version == 1)
                    {
                        throw new PkixCertPathValidatorException(
                                  "Version 1 certificates can't be used as CA ones.", null, certPath, index);
                    }

                    Rfc3280CertPathUtilities.PrepareNextCertA(certPath, index);

                    validPolicyTree = Rfc3280CertPathUtilities.PrepareCertB(certPath, index, policyNodes,
                                                                            validPolicyTree, policyMapping);

                    Rfc3280CertPathUtilities.PrepareNextCertG(certPath, index, nameConstraintValidator);

                    // (h)
                    explicitPolicy   = Rfc3280CertPathUtilities.PrepareNextCertH1(certPath, index, explicitPolicy);
                    policyMapping    = Rfc3280CertPathUtilities.PrepareNextCertH2(certPath, index, policyMapping);
                    inhibitAnyPolicy = Rfc3280CertPathUtilities.PrepareNextCertH3(certPath, index, inhibitAnyPolicy);

                    //
                    // (i)
                    //
                    explicitPolicy = Rfc3280CertPathUtilities.PrepareNextCertI1(certPath, index, explicitPolicy);
                    policyMapping  = Rfc3280CertPathUtilities.PrepareNextCertI2(certPath, index, policyMapping);

                    // (j)
                    inhibitAnyPolicy = Rfc3280CertPathUtilities.PrepareNextCertJ(certPath, index, inhibitAnyPolicy);

                    // (k)
                    Rfc3280CertPathUtilities.PrepareNextCertK(certPath, index);

                    // (l)
                    maxPathLength = Rfc3280CertPathUtilities.PrepareNextCertL(certPath, index, maxPathLength);

                    // (m)
                    maxPathLength = Rfc3280CertPathUtilities.PrepareNextCertM(certPath, index, maxPathLength);

                    // (n)
                    Rfc3280CertPathUtilities.PrepareNextCertN(certPath, index);

                    ISet criticalExtensions1 = cert.GetCriticalExtensionOids();

                    if (criticalExtensions1 != null)
                    {
                        criticalExtensions1 = new HashSet(criticalExtensions1);

                        // these extensions are handled by the algorithm
                        criticalExtensions1.Remove(X509Extensions.KeyUsage.Id);
                        criticalExtensions1.Remove(X509Extensions.CertificatePolicies.Id);
                        criticalExtensions1.Remove(X509Extensions.PolicyMappings.Id);
                        criticalExtensions1.Remove(X509Extensions.InhibitAnyPolicy.Id);
                        criticalExtensions1.Remove(X509Extensions.IssuingDistributionPoint.Id);
                        criticalExtensions1.Remove(X509Extensions.DeltaCrlIndicator.Id);
                        criticalExtensions1.Remove(X509Extensions.PolicyConstraints.Id);
                        criticalExtensions1.Remove(X509Extensions.BasicConstraints.Id);
                        criticalExtensions1.Remove(X509Extensions.SubjectAlternativeName.Id);
                        criticalExtensions1.Remove(X509Extensions.NameConstraints.Id);
                    }
                    else
                    {
                        criticalExtensions1 = new HashSet();
                    }

                    // (o)
                    Rfc3280CertPathUtilities.PrepareNextCertO(certPath, index, criticalExtensions1, pathCheckers);

                    // set signing certificate for next round
                    sign = cert;

                    // (c)
                    workingIssuerName = sign.SubjectDN;

                    // (d)
                    try
                    {
                        workingPublicKey = PkixCertPathValidatorUtilities.GetNextWorkingKey(certPath.Certificates, index);
                    }
                    catch (PkixCertPathValidatorException e)
                    {
                        throw new PkixCertPathValidatorException("Next working key could not be retrieved.", e, certPath, index);
                    }

                    workingAlgId = PkixCertPathValidatorUtilities.GetAlgorithmIdentifier(workingPublicKey);
                    // (f)
//                    workingPublicKeyAlgorithm = workingAlgId.Algorithm;
                    // (e)
//                    workingPublicKeyParameters = workingAlgId.Parameters;
                }
            }

            //
            // 6.1.5 Wrap-up procedure
            //

            explicitPolicy = Rfc3280CertPathUtilities.WrapupCertA(explicitPolicy, cert);

            explicitPolicy = Rfc3280CertPathUtilities.WrapupCertB(certPath, index + 1, explicitPolicy);

            //
            // (c) (d) and (e) are already done
            //

            //
            // (f)
            //
            ISet criticalExtensions = cert.GetCriticalExtensionOids();

            if (criticalExtensions != null)
            {
                criticalExtensions = new HashSet(criticalExtensions);

                // Requires .Id
                // these extensions are handled by the algorithm
                criticalExtensions.Remove(X509Extensions.KeyUsage.Id);
                criticalExtensions.Remove(X509Extensions.CertificatePolicies.Id);
                criticalExtensions.Remove(X509Extensions.PolicyMappings.Id);
                criticalExtensions.Remove(X509Extensions.InhibitAnyPolicy.Id);
                criticalExtensions.Remove(X509Extensions.IssuingDistributionPoint.Id);
                criticalExtensions.Remove(X509Extensions.DeltaCrlIndicator.Id);
                criticalExtensions.Remove(X509Extensions.PolicyConstraints.Id);
                criticalExtensions.Remove(X509Extensions.BasicConstraints.Id);
                criticalExtensions.Remove(X509Extensions.SubjectAlternativeName.Id);
                criticalExtensions.Remove(X509Extensions.NameConstraints.Id);
                criticalExtensions.Remove(X509Extensions.CrlDistributionPoints.Id);
            }
            else
            {
                criticalExtensions = new HashSet();
            }

            Rfc3280CertPathUtilities.WrapupCertF(certPath, index + 1, pathCheckers, criticalExtensions);

            PkixPolicyNode intersection = Rfc3280CertPathUtilities.WrapupCertG(certPath, paramsPkix, userInitialPolicySet,
                                                                               index + 1, policyNodes, validPolicyTree, acceptablePolicies);

            if ((explicitPolicy > 0) || (intersection != null))
            {
                return(new PkixCertPathValidatorResult(trust, intersection, cert.GetPublicKey()));
            }

            throw new PkixCertPathValidatorException("Path processing failed on policy.", null, certPath, index);
        }
コード例 #42
0
ファイル: CrlIdentifier.cs プロジェクト: woutersmit/NBitcoin
		public CrlIdentifier(
			X509Name	crlIssuer,
			DateTime	crlIssuedTime)
			: this(crlIssuer, crlIssuedTime, null)
		{
		}
コード例 #43
0
        /// <summary>
        /// Instantiate a Pkcs10CertificationRequest object with the necessary credentials.
        /// </summary>
        ///<param name="signatureAlgorithm">Name of Sig Alg.</param>
        /// <param name="subject">X509Name of subject eg OU="My unit." O="My Organisatioin" C="au" </param>
        /// <param name="publicKey">Public Key to be included in cert reqest.</param>
        /// <param name="attributes">ASN1Set of Attributes.</param>
        /// <param name="signingKey">Matching Private key for nominated (above) public key to be used to sign the request.</param>
        public Pkcs10CertificationRequest(
            string signatureAlgorithm,
            X509Name subject,
            AsymmetricKeyParameter publicKey,
            Asn1Set attributes,
            AsymmetricKeyParameter signingKey)
        {
            if (signatureAlgorithm == null)
            {
                throw new ArgumentNullException("signatureAlgorithm");
            }
            if (subject == null)
            {
                throw new ArgumentNullException("subject");
            }
            if (publicKey == null)
            {
                throw new ArgumentNullException("publicKey");
            }
            if (publicKey.IsPrivate)
            {
                throw new ArgumentException("expected public key", "publicKey");
            }
            if (!signingKey.IsPrivate)
            {
                throw new ArgumentException("key for signing must be private", "signingKey");
            }

//			DerObjectIdentifier sigOid = SignerUtilities.GetObjectIdentifier(signatureAlgorithm);
            string algorithmName       = signatureAlgorithm.ToUpperInvariant();
            DerObjectIdentifier sigOid = (DerObjectIdentifier)algorithms[algorithmName];

            if (sigOid == null)
            {
                try
                {
                    sigOid = new DerObjectIdentifier(algorithmName);
                }
                catch (Exception e)
                {
                    throw new ArgumentException("Unknown signature type requested", e);
                }
            }

            if (noParams.Contains(sigOid))
            {
                this.sigAlgId = new AlgorithmIdentifier(sigOid);
            }
            else if (exParams.Contains(algorithmName))
            {
                this.sigAlgId = new AlgorithmIdentifier(sigOid, (Asn1Encodable)exParams[algorithmName]);
            }
            else
            {
                this.sigAlgId = new AlgorithmIdentifier(sigOid, DerNull.Instance);
            }

            SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);

            this.reqInfo = new CertificationRequestInfo(subject, pubInfo, attributes);

            ISigner sig = SignerUtilities.GetSigner(signatureAlgorithm);

            sig.Init(true, signingKey);

            try
            {
                // Encode.
                byte[] b = reqInfo.GetDerEncoded();
                sig.BlockUpdate(b, 0, b.Length);
            }
            catch (Exception e)
            {
                throw new ArgumentException("exception encoding TBS cert request", e);
            }

            // Generate Signature.
            sigBits = new DerBitString(sig.GenerateSignature());
        }
コード例 #44
0
        /**
         * Add the CRL issuers from the cRLIssuer field of the distribution point or
         * from the certificate if not given to the issuer criterion of the
         * <code>selector</code>.
         * <p>
         * The <code>issuerPrincipals</code> are a collection with a single
         * <code>X500Principal</code> for <code>X509Certificate</code>s. For
         * {@link X509AttributeCertificate}s the issuer may contain more than one
         * <code>X500Principal</code>.
         * </p>
         *
         * @param dp The distribution point.
         * @param issuerPrincipals The issuers of the certificate or attribute
         *            certificate which contains the distribution point.
         * @param selector The CRL selector.
         * @param pkixParams The PKIX parameters containing the cert stores.
         * @throws Exception if an exception occurs while processing.
         * @throws ClassCastException if <code>issuerPrincipals</code> does not
         * contain only <code>X500Principal</code>s.
         */
        internal static void GetCrlIssuersFromDistributionPoint(
            DistributionPoint dp,
            ICollection issuerPrincipals,
            X509CrlStoreSelector selector,
            PkixParameters pkixParams)
        {
            IList issuers = Platform.CreateArrayList();

            // indirect CRL
            if (dp.CrlIssuer != null)
            {
                GeneralName[] genNames = dp.CrlIssuer.GetNames();
                // look for a DN
                for (int j = 0; j < genNames.Length; j++)
                {
                    if (genNames[j].TagNo == GeneralName.DirectoryName)
                    {
                        try
                        {
                            issuers.Add(X509Name.GetInstance(genNames[j].Name.ToAsn1Object()));
                        }
                        catch (IOException e)
                        {
                            throw new Exception(
                                      "CRL issuer information from distribution point cannot be decoded.",
                                      e);
                        }
                    }
                }
            }
            else
            {
                /*
                 * certificate issuer is CRL issuer, distributionPoint field MUST be
                 * present.
                 */
                if (dp.DistributionPointName == null)
                {
                    throw new Exception(
                              "CRL issuer is omitted from distribution point but no distributionPoint field present.");
                }

                // add and check issuer principals
                for (IEnumerator it = issuerPrincipals.GetEnumerator(); it.MoveNext();)
                {
                    issuers.Add((X509Name)it.Current);
                }
            }
            // TODO: is not found although this should correctly add the rel name. selector of Sun is buggy here or PKI test case is invalid
            // distributionPoint
            //        if (dp.getDistributionPoint() != null)
            //        {
            //            // look for nameRelativeToCRLIssuer
            //            if (dp.getDistributionPoint().getType() == DistributionPointName.NAME_RELATIVE_TO_CRL_ISSUER)
            //            {
            //                // append fragment to issuer, only one
            //                // issuer can be there, if this is given
            //                if (issuers.size() != 1)
            //                {
            //                    throw new AnnotatedException(
            //                        "nameRelativeToCRLIssuer field is given but more than one CRL issuer is given.");
            //                }
            //                DEREncodable relName = dp.getDistributionPoint().getName();
            //                Iterator it = issuers.iterator();
            //                List issuersTemp = new ArrayList(issuers.size());
            //                while (it.hasNext())
            //                {
            //                    Enumeration e = null;
            //                    try
            //                    {
            //                        e = ASN1Sequence.getInstance(
            //                            new ASN1InputStream(((X500Principal) it.next())
            //                                .getEncoded()).readObject()).getObjects();
            //                    }
            //                    catch (IOException ex)
            //                    {
            //                        throw new AnnotatedException(
            //                            "Cannot decode CRL issuer information.", ex);
            //                    }
            //                    ASN1EncodableVector v = new ASN1EncodableVector();
            //                    while (e.hasMoreElements())
            //                    {
            //                        v.add((DEREncodable) e.nextElement());
            //                    }
            //                    v.add(relName);
            //                    issuersTemp.add(new X500Principal(new DERSequence(v)
            //                        .getDEREncoded()));
            //                }
            //                issuers.clear();
            //                issuers.addAll(issuersTemp);
            //            }
            //        }

            selector.Issuers = issuers;
        }
コード例 #45
0
		public void CanGetAndSetProperties()
		{
			int serial = 101;
			X509Name subject = new X509Name("CN=localhost");
			X509Name issuer = new X509Name("CN=Root");
			DateTime start = DateTime.Now;
			DateTime end = start + TimeSpan.FromMinutes(10);

			CryptoKey key = new CryptoKey(new DSA(true));
			int bits = key.Bits;

			X509Name saveIssuer = null;
			X509Name saveSubject = null;
			CryptoKey savePublicKey = null;
			CryptoKey savePrivateKey = null;
			using (X509Certificate cert = new X509Certificate()) {
				cert.Subject = subject;
				cert.Issuer = issuer;
				cert.SerialNumber = serial;
				cert.NotBefore = start;
				cert.NotAfter = end;
				cert.PublicKey = key;
				cert.PrivateKey = key;

				Assert.AreEqual(subject, cert.Subject);
				Assert.AreEqual(issuer, cert.Issuer);
				Assert.AreEqual(serial, cert.SerialNumber);

				Assert.AreEqual(key, cert.PublicKey);
				Assert.AreEqual(key, cert.PrivateKey);

				// If the original key gets disposed before the internal private key,
				// make sure that memory is correctly managed
				key.Dispose();

				// If the internal private key has already been disposed, this will blowup
				Assert.AreEqual(bits, cert.PublicKey.Bits);
				Assert.AreEqual(bits, cert.PrivateKey.Bits);

				// We compare short date/time strings here because the wrapper can't handle milliseconds
				Assert.AreEqual(start.ToShortDateString(), cert.NotBefore.ToShortDateString());
				Assert.AreEqual(start.ToShortTimeString(), cert.NotBefore.ToShortTimeString());

				saveSubject = cert.Subject;
				saveIssuer = cert.Issuer;
				savePublicKey = cert.PublicKey;
				savePrivateKey = cert.PrivateKey;
			}

			// make sure that a property torn-off from the cert is still valid
			Assert.AreEqual(subject, saveSubject);
			Assert.AreEqual(issuer, saveIssuer);
			Assert.AreEqual(bits, savePublicKey.Bits);
			Assert.AreEqual(bits, savePrivateKey.Bits);
		}
コード例 #46
0
ファイル: ServiceLocator.cs プロジェクト: woutersmit/NBitcoin
		public ServiceLocator(
			X509Name	issuer)
			: this(issuer, null)
		{
		}
コード例 #47
0
		/// <summary>
		/// Factory method that creates a X509CertificateAuthority instance with
		/// an internal self signed certificate
		/// </summary>
		/// <param name="cfg"></param>
		/// <param name="seq"></param>
		/// <param name="key"></param>
		/// <param name="digest"></param>
		/// <param name="subject"></param>
		/// <param name="start"></param>
		/// <param name="validity"></param>
		/// <returns></returns>
		public static X509CertificateAuthority SelfSigned(
			Configuration cfg,
			ISequenceNumber seq,
			CryptoKey key,
			MessageDigest digest,
			X509Name subject,
			DateTime start,
			TimeSpan validity)
		{
			var cert = new X509Certificate(
				           seq.Next(),
				           subject,
				           subject,
				           key,
				           start,
				           start + validity);

			if (cfg != null)
				cfg.ApplyExtensions("v3_ca", cert, cert, null);

			cert.Sign(key, digest);

			return new X509CertificateAuthority(cert, key, seq);
		}
コード例 #48
0
 public IssuerAndSerialNumber(
     Asn1Sequence seq)
 {
     this.name         = X509Name.GetInstance(seq[0]);
     this.serialNumber = (DerInteger)seq[1];
 }
コード例 #49
0
        // Only the ctor should be calling with isAuthority = true
        // if isAuthority, value for isMachineCert doesn't matter
        private X509CertificateContainer CreateCertificate(bool isAuthority, bool isMachineCert, X509Certificate signingCertificate, CertificateCreationSettings certificateCreationSettings)
        {
            if (certificateCreationSettings == null)
            {
                if (isAuthority)
                {
                    certificateCreationSettings = new CertificateCreationSettings();
                }
                else
                {
                    throw new Exception("Parameter certificateCreationSettings cannot be null when isAuthority is false");
                }
            }

            // Set to default cert creation settings if not set
            if (certificateCreationSettings.ValidityNotBefore == default(DateTime))
            {
                certificateCreationSettings.ValidityNotBefore = _defaultValidityNotBefore;
            }
            if (certificateCreationSettings.ValidityNotAfter == default(DateTime))
            {
                certificateCreationSettings.ValidityNotAfter = _defaultValidityNotAfter;
            }

            if (!isAuthority ^ (signingCertificate != null))
            {
                throw new ArgumentException("Either isAuthority == true or signingCertificate is not null");
            }
            string subject = certificateCreationSettings.Subject;

            // If certificateCreationSettings.SubjectAlternativeNames == null, then we should add exactly one SubjectAlternativeName == Subject
            // so that the default certificate generated is compatible with mainline scenarios
            // However, if certificateCreationSettings.SubjectAlternativeNames == string[0], then allow this as this is a legit scenario we want to test out
            if (certificateCreationSettings.SubjectAlternativeNames == null)
            {
                certificateCreationSettings.SubjectAlternativeNames = new string[1] {
                    subject
                };
            }

            string[] subjectAlternativeNames = certificateCreationSettings.SubjectAlternativeNames;

            if (!isAuthority && string.IsNullOrWhiteSpace(subject))
            {
                throw new ArgumentException("Certificate Subject must not be an empty string or only whitespace", "creationSettings.Subject");
            }

            EnsureInitialized();

            s_certGenerator.Reset();
            s_certGenerator.SetSignatureAlgorithm(_signatureAlthorithm);

            X509Name authorityX509Name = CreateX509Name(_authorityCanonicalName);
            var      serialNum         = new BigInteger(64 /*sizeInBits*/, _random).Abs();

            var keyPair = isAuthority ? _authorityKeyPair : _keyPairGenerator.GenerateKeyPair();

            if (isAuthority)
            {
                s_certGenerator.SetIssuerDN(authorityX509Name);
                s_certGenerator.SetSubjectDN(authorityX509Name);

                var authorityKeyIdentifier = new AuthorityKeyIdentifier(
                    SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(_authorityKeyPair.Public),
                    new GeneralNames(new GeneralName(authorityX509Name)),
                    serialNum);

                s_certGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, authorityKeyIdentifier);
                s_certGenerator.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(X509KeyUsage.DigitalSignature | X509KeyUsage.KeyAgreement | X509KeyUsage.KeyCertSign | X509KeyUsage.KeyEncipherment | X509KeyUsage.CrlSign));
            }
            else
            {
                X509Name subjectName = CreateX509Name(subject);
                s_certGenerator.SetIssuerDN(PrincipalUtilities.GetSubjectX509Principal(signingCertificate));
                s_certGenerator.SetSubjectDN(subjectName);

                s_certGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(_authorityKeyPair.Public));
                s_certGenerator.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(X509KeyUsage.DigitalSignature | X509KeyUsage.KeyAgreement | X509KeyUsage.KeyEncipherment));
            }

            s_certGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.Public));

            s_certGenerator.SetSerialNumber(serialNum);
            s_certGenerator.SetNotBefore(certificateCreationSettings.ValidityNotBefore);
            s_certGenerator.SetNotAfter(certificateCreationSettings.ValidityNotAfter);
            s_certGenerator.SetPublicKey(keyPair.Public);

            s_certGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(isAuthority));
            s_certGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPClientAuth));

            if (!isAuthority)
            {
                if (isMachineCert)
                {
                    List <Asn1Encodable> subjectAlternativeNamesAsAsn1EncodableList = new List <Asn1Encodable>();

                    // All endpoints should also be in the Subject Alt Names
                    for (int i = 0; i < subjectAlternativeNames.Length; i++)
                    {
                        if (!string.IsNullOrWhiteSpace(subjectAlternativeNames[i]))
                        {
                            // Machine certs can have additional DNS names
                            subjectAlternativeNamesAsAsn1EncodableList.Add(new GeneralName(GeneralName.DnsName, subjectAlternativeNames[i]));
                        }
                    }

                    s_certGenerator.AddExtension(X509Extensions.SubjectAlternativeName, true, new DerSequence(subjectAlternativeNamesAsAsn1EncodableList.ToArray()));
                }
                else
                {
                    if (subjectAlternativeNames.Length > 1)
                    {
                        var subjectAlternativeNamesAsAsn1EncodableList = new Asn1EncodableVector();

                        // Only add a SAN for the user if there are any
                        for (int i = 1; i < subjectAlternativeNames.Length; i++)
                        {
                            if (!string.IsNullOrWhiteSpace(subjectAlternativeNames[i]))
                            {
                                Asn1EncodableVector otherNames = new Asn1EncodableVector();
                                otherNames.Add(new DerObjectIdentifier(_upnObjectId));
                                otherNames.Add(new DerTaggedObject(true, 0, new DerUtf8String(subjectAlternativeNames[i])));

                                Asn1Object genName = new DerTaggedObject(false, 0, new DerSequence(otherNames));

                                subjectAlternativeNamesAsAsn1EncodableList.Add(genName);
                            }
                        }
                        s_certGenerator.AddExtension(X509Extensions.SubjectAlternativeName, true, new DerSequence(subjectAlternativeNamesAsAsn1EncodableList));
                    }
                }
            }

            // Our CRL Distribution Point has the serial number in the query string to fool Windows into doing a fresh query
            // rather than using a cached copy of the CRL in the case where the CRL has been previously accessed before
            var crlDistributionPoints = new DistributionPoint[2] {
                new DistributionPoint(new DistributionPointName(
                                          new GeneralNames(new GeneralName(
                                                               GeneralName.UniformResourceIdentifier, string.Format("{0}?serialNum={1}", _crlUri, serialNum.ToString(radix: 16))))),
                                      null,
                                      null),
                new DistributionPoint(new DistributionPointName(
                                          new GeneralNames(new GeneralName(
                                                               GeneralName.UniformResourceIdentifier, string.Format("{0}?serialNum={1}", _crlUri, serialNum.ToString(radix: 16))))),
                                      null,
                                      new GeneralNames(new GeneralName(authorityX509Name)))
            };
            var revocationListExtension = new CrlDistPoint(crlDistributionPoints);

            s_certGenerator.AddExtension(X509Extensions.CrlDistributionPoints, false, revocationListExtension);

            X509Certificate cert = s_certGenerator.Generate(_authorityKeyPair.Private, _random);

            switch (certificateCreationSettings.ValidityType)
            {
            case CertificateValidityType.Revoked:
                RevokeCertificateBySerialNumber(serialNum.ToString(radix: 16));
                break;

            case CertificateValidityType.Expired:
                break;

            default:
                EnsureCertificateIsValid(cert);
                break;
            }

            // For now, given that we don't know what format to return it in, preserve the formats so we have
            // the flexibility to do what we need to

            X509CertificateContainer container = new X509CertificateContainer();

            X509CertificateEntry[] chain = new X509CertificateEntry[1];
            chain[0] = new X509CertificateEntry(cert);

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

            store.SetKeyEntry(
                certificateCreationSettings.FriendlyName != null ? certificateCreationSettings.FriendlyName : string.Empty,
                new AsymmetricKeyEntry(keyPair.Private),
                chain);

            using (MemoryStream stream = new MemoryStream())
            {
                store.Save(stream, _password.ToCharArray(), _random);
                container.Pfx = stream.ToArray();
            }

            X509Certificate2 outputCert;

            if (isAuthority)
            {
                // don't hand out the private key for the cert when it's the authority
                outputCert = new X509Certificate2(cert.GetEncoded());
            }
            else
            {
                // Otherwise, allow encode with the private key. note that X509Certificate2.RawData will not provide the private key
                // you will have to re-export this cert if needed
                outputCert = new X509Certificate2(container.Pfx, _password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
            }

            container.Subject             = subject;
            container.InternalCertificate = cert;
            container.Certificate         = outputCert;
            container.Thumbprint          = outputCert.Thumbprint;

            Trace.WriteLine("[CertificateGenerator] generated a certificate:");
            Trace.WriteLine(string.Format("    {0} = {1}", "isAuthority", isAuthority));
            if (!isAuthority)
            {
                Trace.WriteLine(string.Format("    {0} = {1}", "Signed by", signingCertificate.SubjectDN));
                Trace.WriteLine(string.Format("    {0} = {1}", "Subject (CN) ", subject));
                Trace.WriteLine(string.Format("    {0} = {1}", "Subject Alt names ", string.Join(", ", subjectAlternativeNames)));
                Trace.WriteLine(string.Format("    {0} = {1}", "Friendly Name ", certificateCreationSettings.FriendlyName));
            }
            Trace.WriteLine(string.Format("    {0} = {1}", "HasPrivateKey:", outputCert.HasPrivateKey));
            Trace.WriteLine(string.Format("    {0} = {1}", "Thumbprint", outputCert.Thumbprint));
            Trace.WriteLine(string.Format("    {0} = {1}", "CertificateValidityType", certificateCreationSettings.ValidityType));

            return(container);
        }
コード例 #50
0
        /// <summary>
        /// Search the given Set of TrustAnchor's for one that is the
        /// issuer of the given X509 certificate.
        /// </summary>
        /// <param name="cert">the X509 certificate</param>
        /// <param name="trustAnchors">a Set of TrustAnchor's</param>
        /// <returns>the <code>TrustAnchor</code> object if found or
        /// <code>null</code> if not.
        /// </returns>
        /// @exception
        internal static TrustAnchor FindTrustAnchor(
            X509Certificate cert,
            ISet trustAnchors)
        {
            IEnumerator            iter           = trustAnchors.GetEnumerator();
            TrustAnchor            trust          = null;
            AsymmetricKeyParameter trustPublicKey = null;
            Exception invalidKeyEx = null;

            X509CertStoreSelector certSelectX509 = new X509CertStoreSelector();

            try
            {
                certSelectX509.Subject = GetIssuerPrincipal(cert);
            }
            catch (IOException ex)
            {
                throw new Exception("Cannot set subject search criteria for trust anchor.", ex);
            }

            while (iter.MoveNext() && trust == null)
            {
                trust = (TrustAnchor)iter.Current;
                if (trust.TrustedCert != null)
                {
                    if (certSelectX509.Match(trust.TrustedCert))
                    {
                        trustPublicKey = trust.TrustedCert.GetPublicKey();
                    }
                    else
                    {
                        trust = null;
                    }
                }
                else if (trust.CAName != null && trust.CAPublicKey != null)
                {
                    try
                    {
                        X509Name certIssuer = GetIssuerPrincipal(cert);
                        X509Name caName     = new X509Name(trust.CAName);

                        if (certIssuer.Equivalent(caName, true))
                        {
                            trustPublicKey = trust.CAPublicKey;
                        }
                        else
                        {
                            trust = null;
                        }
                    }
                    catch (InvalidParameterException)
                    {
                        trust = null;
                    }
                }
                else
                {
                    trust = null;
                }

                if (trustPublicKey != null)
                {
                    try
                    {
                        cert.Verify(trustPublicKey);
                    }
                    catch (Exception ex)
                    {
                        invalidKeyEx = ex;
                        trust        = null;
                    }
                }
            }

            if (trust == null && invalidKeyEx != null)
            {
                throw new Exception("TrustAnchor found but certificate validation failed.", invalidKeyEx);
            }

            return(trust);
        }
コード例 #51
0
		/// <summary>
		/// Factory method which creates a X509CertifiateAuthority where
		/// the internal certificate is self-signed
		/// </summary>
		/// <param name="cfg"></param>
		/// <param name="seq"></param>
		/// <param name="subject"></param>
		/// <param name="start"></param>
		/// <param name="validity"></param>
		/// <returns></returns>
		public static X509CertificateAuthority SelfSigned(
			Configuration cfg,
			ISequenceNumber seq,
			X509Name subject,
			DateTime start,
			TimeSpan validity)
		{
			CryptoKey key;
			using (var dsa = new DSA(true))
			{
				key = new CryptoKey(dsa);
				// Dispose the DSA key, the CryptoKey assignment increments the reference count
			}

			var cert = new X509Certificate(
				           seq.Next(),
				           subject,
				           subject,
				           key,
				           start,
				           start + validity);

			if (cfg != null)
				cfg.ApplyExtensions("v3_ca", cert, cert, null);

			cert.Sign(key, MessageDigest.DSS1);

			return new X509CertificateAuthority(cert, key, seq);
		}
コード例 #52
0
        private Csr GenerateCsr(CsrDetails csrDetails, RsaPrivateKey rsaKeyPair, string messageDigest = "SHA256")
        {
            var rsaKeys = CryptoKey.FromPrivateKey(rsaKeyPair.Pem, null);

            // Translate from our external form to our OpenSSL internal form
            // Ref:  https://www.openssl.org/docs/manmaster/crypto/X509_NAME_new.html
            var xn = new X509Name();

            if (!string.IsNullOrEmpty(csrDetails.CommonName /**/))
            {
                xn.Common = csrDetails.CommonName;                                                                  // CN;
            }
            if (!string.IsNullOrEmpty(csrDetails.Country /**/))
            {
                xn.Country = csrDetails.Country;                                                                     // C;
            }
            if (!string.IsNullOrEmpty(csrDetails.StateOrProvince /**/))
            {
                xn.StateOrProvince = csrDetails.StateOrProvince;                                                             // ST;
            }
            if (!string.IsNullOrEmpty(csrDetails.Locality /**/))
            {
                xn.Locality = csrDetails.Locality;                                                                    // L;
            }
            if (!string.IsNullOrEmpty(csrDetails.Organization /**/))
            {
                xn.Organization = csrDetails.Organization;                                                                // O;
            }
            if (!string.IsNullOrEmpty(csrDetails.OrganizationUnit /**/))
            {
                xn.OrganizationUnit = csrDetails.OrganizationUnit;                                                            // OU;
            }
            if (!string.IsNullOrEmpty(csrDetails.Description /**/))
            {
                xn.Description = csrDetails.Description;                                                                 // D;
            }
            if (!string.IsNullOrEmpty(csrDetails.Surname /**/))
            {
                xn.Surname = csrDetails.Surname;                                                                     // S;
            }
            if (!string.IsNullOrEmpty(csrDetails.GivenName /**/))
            {
                xn.Given = csrDetails.GivenName;                                                                   // G;
            }
            if (!string.IsNullOrEmpty(csrDetails.Initials /**/))
            {
                xn.Initials = csrDetails.Initials;                                                                    // I;
            }
            if (!string.IsNullOrEmpty(csrDetails.Title /**/))
            {
                xn.Title = csrDetails.Title;                                                                       // T;
            }
            if (!string.IsNullOrEmpty(csrDetails.SerialNumber /**/))
            {
                xn.SerialNumber = csrDetails.SerialNumber;                                                                // SN;
            }
            if (!string.IsNullOrEmpty(csrDetails.UniqueIdentifier /**/))
            {
                xn.UniqueIdentifier = csrDetails.UniqueIdentifier;                                                            // UID;
            }
            var xr = new X509Request(0, xn, rsaKeys);

            if (csrDetails.AlternativeNames.Count > 0)
            {
                OpenSSL.Core.Stack <X509Extension> extensions = new OpenSSL.Core.Stack <X509Extension>();
                // Add the common name as the first alternate
                string altNames = "DNS:" + xn.Common;
                foreach (var name in csrDetails.AlternativeNames)
                {
                    altNames += ", DNS:" + name;
                }
                extensions.Add(new X509Extension(xr, "subjectAltName", false, altNames));

                xr.AddExtensions(extensions);
            }
            var md = MessageDigest.CreateByName(messageDigest);

            xr.Sign(rsaKeys, md);
            using (var bio = BIO.MemoryBuffer())
            {
                xr.Write(bio);
                return(new Csr(bio.ReadString()));
            }
        }
コード例 #53
0
		/// <summary>
		/// Factory method that creates a X509CertificateAuthority instance with
		/// an internal self signed certificate. This method allows creation without
		/// the need for the Configuration file, X509V3Extensions may be added
		/// with the X509V3ExtensionList parameter
		/// </summary>
		/// <param name="seq"></param>
		/// <param name="key"></param>
		/// <param name="digest"></param>
		/// <param name="subject"></param>
		/// <param name="start"></param>
		/// <param name="validity"></param>
		/// <param name="extensions"></param>
		/// <returns></returns>
		public static X509CertificateAuthority SelfSigned(
			ISequenceNumber seq,
			CryptoKey key,
			MessageDigest digest,
			X509Name subject,
			DateTime start,
			TimeSpan validity,
			IEnumerable<X509V3ExtensionValue> extensions)
		{
			var cert = new X509Certificate(
				           seq.Next(),
				           subject,
				           subject,
				           key,
				           start,
				           start + validity);

			if (extensions != null)
			{
				foreach (var extValue in extensions)
				{
					using (var ext = new X509Extension(cert, cert, extValue.Name, extValue.IsCritical, extValue.Value))
					{
						cert.AddExtension(ext);
					}
				}
			}

			cert.Sign(key, digest);

			return new X509CertificateAuthority(cert, key, seq);
		}
コード例 #54
0
        private GeneralNames GenerateGeneralNames(
            X509Name principal)
        {
//			return GeneralNames.GetInstance(new DerSequence(new GeneralName(principal)));
            return(new GeneralNames(new GeneralName(principal)));
        }
コード例 #55
0
        public static X509Certificate2 GenerateSelfSignedCertificate(string subjectName, string issuerName, int keyStrength)
        {
            try
            {
                // Generating Random Numbers
                var randomGenerator = new VmpcRandomGenerator();
                var random          = new SecureRandom(randomGenerator);

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

                // Serial Number
                var serialNumber = BigInteger.ProbablePrime(128, new Random());
                certificateGenerator.SetSerialNumber(serialNumber);

                // Signature Algorithm
                var signatureAlgorithm = "SHA512WithRSA";
                certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);

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

                // Valid For
                var notBefore = DateTime.UtcNow.Date.AddYears(-1);
                var notAfter  = notBefore.AddYears(10);
                certificateGenerator.SetNotBefore(notBefore);
                certificateGenerator.SetNotAfter(notAfter);

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

                if (userKeyPair == null)
                {
                    userKeyPair = keyPairGenerator.GenerateKeyPair();
                }

                certificateGenerator.SetPublicKey(userKeyPair.Public);

                //Extented
                certificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false,
                                                  new SubjectKeyIdentifierStructure(userKeyPair.Public));
                certificateGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false,
                                                  new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory
                                                                             .CreateSubjectPublicKeyInfo(userKeyPair.Public)));
                var valueData = Encoding.ASCII.GetBytes("Client");
                certificateGenerator.AddExtension("1.3.6.1.5.5.7.13.3", false, valueData);

                // Generating the Certificate
                var issuerKeyPair = userKeyPair;

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

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

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

                var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.ParsePrivateKey().GetDerEncoded());
                if (seq.Count != 9)
                {
                    throw new Exception("malformed sequence in RSA private key");
                }

                var rsa       = RsaPrivateKeyStructure.GetInstance(seq);
                var rsaparams = new RsaPrivateCrtKeyParameters(rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent,
                                                               rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2,
                                                               rsa.Coefficient);
#if NETCOREAPP2_0 || NETCOREAPP2_1
                x509 = x509.CopyWithPrivateKey(PemUtils.ToRSA(rsaparams));
#endif
                return(x509);
            }
            catch (Exception ex)
            {
                logger.Error(ex, $"The Method \"{nameof(GenerateSelfSignedCertificate)}\" has failed.");
                return(null);
            }
        }
コード例 #56
0
ファイル: TimeStampToken.cs プロジェクト: EnergonV/BestCS
        /**
         * Validate the time stamp token.
         * <p>
         * To be valid the token must be signed by the passed in certificate and
         * the certificate must be the one referred to by the SigningCertificate
         * attribute included in the hashed attributes of the token. The
         * certificate must also have the ExtendedKeyUsageExtension with only
         * KeyPurposeID.IdKPTimeStamping and have been valid at the time the
         * timestamp was created.
         * </p>
         * <p>
         * A successful call to validate means all the above are true.
         * </p>
         */
        public void Validate(
            X509Certificate cert)
        {
            try
            {
                byte[] hash = DigestUtilities.CalculateDigest(
                    certID.GetHashAlgorithmName(), cert.GetEncoded());

                if (!Arrays.ConstantTimeAreEqual(certID.GetCertHash(), hash))
                {
                    throw new TspValidationException("certificate hash does not match certID hash.");
                }

                if (certID.IssuerSerial != null)
                {
                    if (!certID.IssuerSerial.Serial.Value.Equals(cert.SerialNumber))
                    {
                        throw new TspValidationException("certificate serial number does not match certID for signature.");
                    }

                    GeneralName[] names     = certID.IssuerSerial.Issuer.GetNames();
                    X509Name      principal = PrincipalUtilities.GetIssuerX509Principal(cert);
                    bool          found     = false;

                    for (int i = 0; i != names.Length; i++)
                    {
                        if (names[i].TagNo == 4 &&
                            X509Name.GetInstance(names[i].Name).Equivalent(principal))
                        {
                            found = true;
                            break;
                        }
                    }

                    if (!found)
                    {
                        throw new TspValidationException("certificate name does not match certID for signature. ");
                    }
                }

                TspUtil.ValidateCertificate(cert);

                cert.CheckValidity(tstInfo.GenTime);

                if (!tsaSignerInfo.Verify(cert))
                {
                    throw new TspValidationException("signature not created by certificate.");
                }
            }
            catch (CmsException e)
            {
                if (e.InnerException != null)
                {
                    throw new TspException(e.Message, e.InnerException);
                }

                throw new TspException("CMS exception: " + e, e);
            }
            catch (CertificateEncodingException e)
            {
                throw new TspException("problem processing certificate: " + e, e);
            }
            catch (SecurityUtilityException e)
            {
                throw new TspException("cannot find algorithm: " + e.Message, e);
            }
        }
コード例 #57
0
 /// <summary>
 /// Initialize the Subject property with the Certificate Authority subject information.
 /// </summary>
 public void SetupSubjectInformation()
 {
     this.Subject = GetCertificateAuthoritySubject();
 }
コード例 #58
0
 public RespID(
     X509Name name)
 {
     this.id = new ResponderID(name);
 }
コード例 #59
0
ファイル: TestServer.cs プロジェクト: challal/scallion
			protected X509Certificate clientCertificateSelectionCallback(object sender, string targetHost, X509List localCerts, X509Certificate remoteCert, string[] acceptableIssuers) {
				X509Certificate retCert = null;

				// check target host?

				for (int i = 0; i < acceptableIssuers.GetLength(0); i++) {
					X509Name name = new X509Name(acceptableIssuers[i]);

					foreach (X509Certificate cert in localCerts) {
						if (cert.Issuer.CompareTo(name) == 0) {
							retCert = cert;
							break;
						}
						cert.Dispose();
					}
					name.Dispose();
				}
				return retCert;
			}
コード例 #60
0
        private bool saveAs(bool Signed)
        {
            //SaveFileDialog dialog;

            mSubjectItemsOIDs.Add(X509Name.C);
            mSubjectItemsOIDs.Add(X509Name.OU);
            mSubjectItemsOIDs.Add(X509Name.CN);
            mSubjectItemsOIDs.Add(X509Name.TelephoneNumber);

            mSubjectItems.Add(CountryCodeTB.Text.Trim());
            mSubjectItems.Add(OrganizationalUnitTB.Text.Trim());
            mSubjectItems.Add(CommonNameTB.Text.Trim());
            mSubjectItems.Add(PhoneNumberTB.Text.Trim());

            mExtItemsOIDs.Add(X509Extensions.SubjectAlternativeName);
            mExtItems.Add(new X509Extension(false,
                                            new DerOctetString(new GeneralNames(new GeneralName(GeneralName.Rfc822Name, EmailTB.Text)))));


            string mKeyUsageDescription = "digitalSignature, nonRepudiation";

            int key_usage_bit_map = 0;

            key_usage_bit_map |= KeyUsage.DigitalSignature;
            key_usage_bit_map |= KeyUsage.NonRepudiation;

            KeyUsage mKeyUsage = new KeyUsage(key_usage_bit_map);

            mExtItemsOIDs.Add(X509Extensions.KeyUsage);
            mExtItems.Add(new X509Extension(true, new DerOctetString(mKeyUsage)));

            try
            {
                /* dialog = new SaveFileDialog();
                *  dialog.Filter = "CSR files (*.pem)|*.pem|All files (*.*)|*.*";
                *  dialog.RestoreDirectory = true;*/

                //if (dialog.ShowDialog() == DialogResult.OK)
                //{
                X509Name subject            = new X509Name(mSubjectItemsOIDs, mSubjectItems);
                string   signatureAlgorithm = "SHA256withECDSA";

                DerSet attributes = new DerSet();
                if (mExtItemsOIDs.Count > 0)
                {
                    attributes.AddObject(new AttributePkcs(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, new DerSet(
                                                               new X509Extensions(mExtItemsOIDs, mExtItems)))); // mExtItemsOIDs.Zip(mExtItems, (k, v) => new { Key = k, Value = v })
                                                                                                                //              .ToDictionary(x => x.Key, x => x.Value)
                }

                AsymmetricKeyParameter local_pub_key;

                if (Signed)
                {
                    local_pub_key = mPublicKey;
                }
                else
                {
                    local_pub_key = new RsaKeyParameters(false, BigInteger.One, BigInteger.One); // DUMMY RSA public key - for templates
                }
                Pkcs10CertificationRequestDelaySigned csr_ds =
                    new Pkcs10CertificationRequestDelaySigned(signatureAlgorithm, subject, local_pub_key, attributes);

                byte[] dataToSign = csr_ds.GetDataToSign();
                byte[] toSave;
                string header_footer;

                if (Signed)
                {
                    byte[] SignedData = uFRSigner(dataToSign);
                    // Rest of the input parameters needed (here accessible directly from UI):
                    //      - digest_alg, signature_cipher, card_key_index
                    csr_ds.SignRequest(SignedData);

                    toSave        = csr_ds.GetDerEncoded();
                    header_footer = "CERTIFICATE REQUEST";
                }
                else
                {
                    toSave        = dataToSign;
                    header_footer = "TBS CERTIFICATE REQUEST";
                }

                var file_extension = Path.GetExtension("CSR.pem");
                if (file_extension.Equals(".pem"))
                {
                    //var textWriter = new StreamWriter(dialog.FileName);
                    var textWriter = new StreamWriter("CSR.pem");

                    textWriter.Write(der2pem(toSave, header_footer));
                    textWriter.Flush();
                    textWriter.Close();
                }

                /* else
                 * {
                 *   using (var fs = new FileStream(dialog.FileName, FileMode.Create, FileAccess.Write))
                 *   {
                 *       fs.Write(toSave, 0, toSave.Length);
                 *       fs.Flush();
                 *       fs.Close();
                 *   }
                 * }*/
                // }
                //else
                //return false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            return(true);
        }