Наследование: Asn1TaggedObject
Пример #1
0
        public static string GetAuthorityKeyFromCertificate(X509Certificate2 certificate)
        {
            try
            {
                foreach (var extension in certificate.Extensions.Cast<X509Extension>()
                .Where(extension => extension.Oid.Value.Equals(AuthorityKeyOid)))
                {
                    using (var asnStream = new Asn1InputStream(extension.RawData))
                    {
                        var asnObject = asnStream.ReadObject();
                        var taggedObject = new DerTaggedObject(0, asnObject);

                        var authorityKey = AuthorityKeyIdentifier.GetInstance(taggedObject, true);
                        var octetString = new DerOctetString(authorityKey.GetKeyIdentifier());
                        return NormalizeOctetString(octetString.ToString());
                    }
                }

                return "";
            }
            catch (Exception e)
            {
                Log.WarnFormat("An issue occurred while attempting to extract the authority key from a certificate: {0}", e.Message);
                return "";
            }
        }
Пример #2
0
        public DerExternal(
            Asn1EncodableVector vector)
        {
            int        offset = 0;
            Asn1Object enc    = GetObjFromVector(vector, offset);

            if (enc is DerObjectIdentifier)
            {
                directReference = (DerObjectIdentifier)enc;
                offset++;
                enc = GetObjFromVector(vector, offset);
            }
            if (enc is DerInteger)
            {
                indirectReference = (DerInteger)enc;
                offset++;
                enc = GetObjFromVector(vector, offset);
            }
            if (!(enc is DerTaggedObject))
            {
                dataValueDescriptor = (Asn1Object)enc;
                offset++;
                enc = GetObjFromVector(vector, offset);
            }
            if (!(enc is DerTaggedObject))
            {
                throw new InvalidOperationException(
                          "No tagged object found in vector. Structure doesn't seem to be of type External");
            }

            if (vector.Count != offset + 1)
            {
                throw new ArgumentException("input vector too large", "vector");
            }

            if (!(enc is DerTaggedObject))
            {
                throw new ArgumentException("No tagged object found in vector. Structure doesn't seem to be of type External", "vector");
            }

            DerTaggedObject obj = (DerTaggedObject)enc;

            // Use property accessor to include check on value
            Encoding = obj.TagNo;

            if (encoding < 0 || encoding > 2)
            {
                throw new InvalidOperationException("invalid encoding value");
            }

            externalContent = obj.GetObject();
        }
Пример #3
0
        public DerExternal(Asn1EncodableVector vector)
        {
            int        num           = 0;
            Asn1Object objFromVector = GetObjFromVector(vector, num);

            if (objFromVector is DerObjectIdentifier)
            {
                directReference = (DerObjectIdentifier)objFromVector;
                num++;
                objFromVector = GetObjFromVector(vector, num);
            }
            if (objFromVector is DerInteger)
            {
                indirectReference = (DerInteger)objFromVector;
                num++;
                objFromVector = GetObjFromVector(vector, num);
            }
            if (!(objFromVector is DerTaggedObject))
            {
                dataValueDescriptor = objFromVector;
                num++;
                objFromVector = GetObjFromVector(vector, num);
            }
            if (!(objFromVector is DerTaggedObject))
            {
                throw new InvalidOperationException("No tagged object found in vector. Structure doesn't seem to be of type External");
            }
            if (vector.Count != num + 1)
            {
                throw new ArgumentException("input vector too large", "vector");
            }
            if (!(objFromVector is DerTaggedObject))
            {
                throw new ArgumentException("No tagged object found in vector. Structure doesn't seem to be of type External", "vector");
            }
            DerTaggedObject derTaggedObject = (DerTaggedObject)objFromVector;

            Encoding = derTaggedObject.TagNo;
            if (encoding < 0 || encoding > 2)
            {
                throw new InvalidOperationException("invalid encoding value");
            }
            externalContent = derTaggedObject.GetObject();
        }
Пример #4
0
        private string GetResponderName(ResponderID responderId, ref bool byKey)
        {
            Org.BouncyCastle.Asn1.DerTaggedObject dt = (Org.BouncyCastle.Asn1.DerTaggedObject)responderId.ToAsn1Object();

            if (dt.TagNo == 1)
            {
                Org.BouncyCastle.Asn1.X509.X509Name name = Org.BouncyCastle.Asn1.X509.X509Name.GetInstance(dt.GetObject());
                byKey = false;

                return(name.ToString());
            }
            else if (dt.TagNo == 2)
            {
                Asn1TaggedObject tagger  = (Asn1TaggedObject)responderId.ToAsn1Object();
                Asn1OctetString  pubInfo = (Asn1OctetString)tagger.GetObject();
                byKey = true;

                return(Convert.ToBase64String(pubInfo.GetOctets()));
            }
            else
            {
                return(null);
            }
        }
Пример #5
0
 public DerExternal(DerObjectIdentifier directReference, DerInteger indirectReference, Asn1Object dataValueDescriptor, DerTaggedObject externalData) : this(directReference, indirectReference, dataValueDescriptor, externalData.TagNo, externalData.ToAsn1Object())
 {
 }
Пример #6
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;
            }

            string[] subjects = certificateCreationSettings.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", "creationSettings.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(certificateCreationSettings.ValidityNotBefore);
            _certGenerator.SetNotAfter(certificateCreationSettings.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);
            if (certificateCreationSettings.IsValidCert)
            {
                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;
        }
Пример #7
0
        public static List <CertSimples> ListaCertificado(X509Certificate2Collection Certificados)
        {
            List <CertSimples> oLista = new List <CertSimples>();

            for (int i = 0; i < Certificados.Count; i++)
            {
                X509Certificate2 oCertificado = Certificados[i];

                CertSimples oCert = new CertSimples();
                oCert.SerialNumber = oCertificado.SerialNumber;
                oCert.Subject      = oCertificado.Subject;

                try
                {
                    string[] DadosSubject = oCertificado.Subject.Split(',');
                    if (DadosSubject[0].IndexOf(":") > -1)
                    {
                        oCert.Nome = DadosSubject[0].Substring(3, DadosSubject[0].IndexOf(":") - 3);
                    }
                    else
                    {
                        oCert.Nome = DadosSubject[0].Substring(3);
                    }
                }
                catch (Exception ex)
                {
                    oCert.Nome = oCert.Subject;
                }



                foreach (var obj in oCertificado.Extensions)
                {
                    if (obj.Oid.Value == "2.5.29.17") //otherName
                    {
                        byte[] Dados = obj.RawData;
                        Stream sm    = new MemoryStream(Dados);
                        // StreamReader oSr = new StreamReader(sm);

                        //string teste = System.Text.Encoding.ASCII.GetString(Dados);
                        DerSequence otherName     = (DerSequence)Asn1Object.FromStream(sm);
                        var         objCollection = otherName.GetEnumerator();
                        while (objCollection.MoveNext())
                        {
                            Org.BouncyCastle.Asn1.DerTaggedObject iSub = (Org.BouncyCastle.Asn1.DerTaggedObject)objCollection.Current;
                            Asn1Object derObject = iSub.GetObject();
                            if (derObject.GetType().Name.Contains("DerSequence"))
                            {
                                var            objSubCollection = ((DerSequence)derObject).GetEnumerator();
                                byte           count            = 0;
                                string         strOID           = "";
                                DerOctetString strOctet;// = (DerOctetString)derObject;
                                string         strTexto = "";

                                while (objSubCollection.MoveNext())
                                {
                                    var Conteudo = objSubCollection.Current;
                                    if (count == 0)
                                    {
                                        strOID = Conteudo.ToString();
                                    }
                                    else
                                    {
                                        Org.BouncyCastle.Asn1.DerTaggedObject subCampos = (Org.BouncyCastle.Asn1.DerTaggedObject)Conteudo;
                                        Asn1Object derSub = subCampos.GetObject();
                                        try
                                        {
                                            if (derSub.GetType().Name.Contains("DerOctetString"))
                                            {
                                                strOctet = (DerOctetString)derSub;
                                                byte[] Texto = strOctet.GetOctets();
                                                strTexto = System.Text.Encoding.ASCII.GetString(Texto);
                                            }
                                            else
                                            {
                                                DerPrintableString strPtrString = (DerPrintableString)derSub;
                                                strTexto = strPtrString.GetString();
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            strTexto = derSub.ToString();
                                        }
                                    }
                                    count++;
                                }


                                if (strOID == "2.16.76.1.3.1") //PESSOA FÍSICA
                                {
                                    //i· OID = 2.16.76.1.3.1 e conteúdo = nas primeiras 8(oito) posições, a data de nascimento do titular, no formato ddmmaaaa; nas 11(onze) posições subseqüentes, o Cadastro de Pessoa Física(CPF) do titular; nas 11(onze) posições subseqüentes, o Número de Identificação Social – NIS(PIS, PASEP ou CI); nas 15(quinze) posições subseqüentes, o número do Registro Geral(RG) do titular; nas 10(dez) posições subseqüentes, as siglas do órgão expedidor do RG e respectiva unidade da federação;
                                    try
                                    {
                                        oCert.DataNascimento = strTexto.Substring(0, 8);
                                        oCert.CPF            = strTexto.Substring(8, 11);
                                        oCert.NIS            = strTexto.Substring(19, 11);
                                        oCert.RG             = strTexto.Substring(30, 15);
                                        oCert.OrgaoExpedidor = strTexto.Substring(45);
                                        oCert.Tipo           = "F";
                                    }
                                    catch (Exception ex)
                                    {
                                        throw new Exception("Erro na leitura da OID=2.16.76.1.3.1:" + ex.Message, ex);
                                    }
                                }
                                else if (strOID == "2.16.76.1.3.6") //PESSOA FÍSICA
                                {
                                    //ii· OID = 2.16.76.1.3.6 e conteúdo = nas 12 (doze) posições o número do Cadastro Específico do INSS (CEI) da pessoa física titular do certificado;
                                }
                                else if (strOID == "2.16.76.1.3.6") //PESSOA FÍSICA
                                {
                                    try
                                    {
                                        //iii· OID = 2.16.76.1.3.5 e conteúdo nas primeiras 12(doze) posições, o número de inscrição do Título de Eleitor; nas 3(três) posições subseqüentes, a Zona Eleitoral; nas 4(quatro) posições seguintes, a Seção; nas 22(vinte e duas) posições subseqüentes, o município e a UF do Título de Eleitor.
                                        oCert.TituloEleitor      = strTexto.Substring(0, 12);
                                        oCert.ZonaEleitoral      = strTexto.Substring(12, 3);
                                        oCert.SecaoEleitoral     = strTexto.Substring(15, 4);
                                        oCert.MunicipioEleitoral = strTexto.Substring(19, 22);
                                    }
                                    catch (Exception ex)
                                    {
                                        throw new Exception("Erro na leitura da OID=2.16.76.1.3.6:" + ex.Message, ex);
                                    }
                                }
                                else if (strOID == "2.16.76.1.4.2.1.1")
                                {
                                    try
                                    {
                                        oCert.OAB = strTexto;
                                    }
                                    catch (Exception ex)
                                    {
                                        throw new Exception("Erro na leitura da OID=2.16.76.1.4.2.1.1:" + ex.Message, ex);
                                    }
                                }
                                else if (strOID == "2.16.76.1.3.4")    //PESSOA JURÍDICA
                                {
                                    try
                                    {
                                        oCert.Tipo = "J";
                                        //i· OID = 2.16.76.1.3.4 e conteúdo = nas primeiras 8(oito) posições, a data de nascimento do responsável pelo certificado, no formato ddmmaaaa; nas 11(onze) posições subseqüentes, o Cadastro de Pessoa Física(CPF) do responsável; nas 11(onze) posições subseqüentes, o Número de Identificação Social – NIS(PIS, PASEP ou CI); nas 15(quinze) posições subseqüentes, o número do Registro Geral(RG) do responsável; nas 10(dez) posições subseqüentes, as siglas do órgão expedidor do RG e respectiva Unidade da Federação;
                                        oCert.DataNascimento = strTexto.Substring(0, 8);
                                        oCert.CPF            = strTexto.Substring(8, 11);
                                        try
                                        {
                                            oCert.NIS            = strTexto.Substring(19, 11);
                                            oCert.RG             = strTexto.Substring(30, 15);
                                            oCert.OrgaoExpedidor = strTexto.Substring(45, 10);
                                        }
                                        catch (Exception ex)
                                        { }
                                    }
                                    catch (Exception ex)
                                    {
                                        throw new Exception("Erro na leitura da OID=2.16.76.1.3.4:" + strTexto + "." + ex.Message, ex);
                                    }
                                }
                                else if (strOID == "2.16.76.1.3.2")    //PESSOA JURÍDICA
                                {
                                    //ii· OID = 2.16.76.1.3.2 e conteúdo = nome do responsável pelo certificado;
                                    try
                                    {
                                        oCert.NomeResponsavel = strTexto;
                                    }
                                    catch (Exception ex)
                                    {
                                        throw new Exception("Erro na leitura da OID=2.16.76.1.3.2:" + ex.Message, ex);
                                    }
                                }
                                else if (strOID == "2.16.76.1.3.3")    //PESSOA JURÍDICA
                                {
                                    //iii· OID = 2.16.76.1.3.3 e conteúdo = nas 14(quatorze) posições o número do Cadastro Nacional de Pessoa Jurídica(CNPJ) da pessoa jurídica titular do certificado;
                                    try
                                    {
                                        oCert.CNPJ = strTexto;
                                    }
                                    catch (Exception ex)
                                    {
                                        throw new Exception("Erro na leitura da OID=2.16.76.1.3.3:" + ex.Message, ex);
                                    }
                                }
                                else if (strOID == "2.16.76.1.3.7")    //PESSOA JURÍDICA
                                {
                                    //iv. OID = 2.16.76.1.3.7 e conteúdo = nas 12 (doze) posições o número do Cadastro Específico do INSS (CEI) da pessoa jurídica titular do certificado.
                                }

                                count = 0;
                            }
                            else
                            {
                                //i. rfc822Name contendo o endereço e-mail do titular do certificado.
                                if (derObject.GetType().Name == "DerOctetString")
                                {
                                    DerOctetString strOctet = (DerOctetString)derObject;
                                    byte[]         Texto    = strOctet.GetOctets();
                                    string         strTexto = System.Text.Encoding.ASCII.GetString(Texto);
                                    oCert.Email = strTexto;
                                }
                                else
                                {
                                    string texto = derObject.GetType().Name;
                                }
                            }
                        }
                        sm.Close();
                    }
                }
                oCert.Certificado = oCertificado;
                oLista.Add(oCert);
            }

            return(oLista);
        }
Пример #8
0
		/**
		* Creates a new instance of DerExternal
		* See X.690 for more informations about the meaning of these parameters
		* @param directReference The direct reference or <code>null</code> if not set.
		* @param indirectReference The indirect reference or <code>null</code> if not set.
		* @param dataValueDescriptor The data value descriptor or <code>null</code> if not set.
		* @param externalData The external data in its encoded form.
		*/
		public DerExternal(DerObjectIdentifier directReference, DerInteger indirectReference, Asn1Object dataValueDescriptor, DerTaggedObject externalData)
			: this(directReference, indirectReference, dataValueDescriptor, externalData.TagNo, externalData.ToAsn1Object())
		{
		}