Пример #1
0
        public override void PerformTest()
        {
            byte[] data = { 0, 1, 0, 1, 0, 0, 1 };

            Asn1Object[] values =
            {
                new BerOctetString(data),
                new BerSequence(new DerPrintableString("hello world")),
                new BerSet(new DerPrintableString("hello world")),
                new BerTaggedObject(0,                                 new DerPrintableString("hello world")),
                new DerApplicationSpecific(0,                          data),
                new DerBitString(data),
                new DerBmpString("hello world"),
                DerBoolean.True,
                DerBoolean.False,
                new DerEnumerated(100),
                new DerGeneralizedTime("20070315173729Z"),
                new DerGeneralString("hello world"),
                new DerIA5String("hello"),
                new DerInteger(1000),
                DerNull.Instance,
                new DerNumericString("123456"),
                new DerObjectIdentifier("1.1.1.10000.1"),
                new DerOctetString(data),
                new DerPrintableString("hello world"),
                new DerSequence(new DerPrintableString("hello world")),
                new DerSet(new DerPrintableString("hello world")),
                new DerT61String("hello world"),
                new DerTaggedObject(0,                                 new DerPrintableString("hello world")),
                new DerUniversalString(data),
                new DerUnknownTag(true,                                                                    500,data),
                new DerUtcTime(new DateTime()),
                new DerUtf8String("hello world"),
                new DerVisibleString("hello world")
            };

            MemoryStream     bOut = new MemoryStream();
            Asn1OutputStream aOut = new Asn1OutputStream(bOut);

            for (int i = 0; i != values.Length; i++)
            {
                aOut.WriteObject(values[i]);
            }

            Asn1InputStream aIn = new Asn1InputStream(bOut.ToArray());

            for (int i = 0; i != values.Length; i++)
            {
                Asn1Object o = aIn.ReadObject();
                if (!o.Equals(values[i]))
                {
                    Fail("Failed equality test for " + o.GetType().Name);
                }

                if (o.GetHashCode() != values[i].GetHashCode())
                {
                    Fail("Failed hashCode test for " + o.GetType().Name);
                }
            }
        }
Пример #2
0
        public void FromReader(DataReader reader, DataFrames.DataKey root, Utils.Logger logger)
        {
            Asn1InputStream input = new Asn1InputStream(reader.GetStream());
            Asn1Object      obj   = input.ReadObject();

            if (obj == null)
            {
                throw new EndOfStreamException();
            }

            while (obj != null)
            {
                AddAsn1Object(obj.GetType().Name, root, obj, 0, logger);

                obj = input.ReadObject();
            }
        }
Пример #3
0
        private void AddAsn1Object(string name, DataKey root, Asn1Object obj, int level, Logger logger)
        {
            Asn1Sequence     seq      = obj as Asn1Sequence;
            Asn1Set          set      = obj as Asn1Set;
            Asn1TaggedObject tag      = obj as Asn1TaggedObject;
            string           currName = name ?? obj.GetType().Name;

            System.Diagnostics.Trace.WriteLine(String.Format("{0} {1}", currName, obj.GetType()));

            if (seq != null)
            {
                if (!Config.IgnoreSequences)
                {
                    DataKey key = new Asn1SequenceKey(currName, Config.NoVerify);

                    foreach (Asn1Object o in seq)
                    {
                        AddAsn1Object(null, key, o, level + 1, logger);
                    }

                    root.AddSubNode(key);
                }
                else
                {
                    root.AddValue(currName, obj.GetDerEncoded());
                }
            }
            else if (set != null)
            {
                if (!Config.IgnoreSets)
                {
                    DataKey key = new Asn1SetKey(currName, Config.NoVerify);

                    foreach (Asn1Object o in set)
                    {
                        AddAsn1Object(null, key, o, level + 1, logger);
                    }

                    root.AddSubNode(key);
                }
                else
                {
                    root.AddValue(currName, obj.GetDerEncoded());
                }
            }
            else if (tag != null)
            {
                if (!Config.IgnoreTaggedObjects)
                {
                    DataKey key = new Asn1TaggedObjectKey(currName, tag.TagNo, Config.NoVerify);

                    root.AddSubNode(key);

                    Asn1Object     o   = tag.GetObject();
                    DerOctetString oct = o as DerOctetString;

                    AddAsn1Object("Object", key, tag.GetObject(), level + 1, logger);

                    //if (oct != null)
                    //{
                    //    Asn1InputStream input = new Asn1InputStream(oct.GetOctetStream());

                    //    try
                    //    {
                    //        Asn1Object next = input.ReadObject();
                    //        if (next == null)
                    //        {
                    //            AddAsn1Object("Object", key, o, logger);
                    //        }
                    //        else
                    //        {
                    //            Asn1OctetStringObject newRoot = new Asn1OctetStringObject("Object");

                    //            while (next != null)
                    //            {
                    //                AddAsn1Object(next.GetType().Name, newRoot, next, logger);

                    //                next = input.ReadObject();
                    //            }

                    //            key.AddSubNode(newRoot);
                    //        }
                    //    }
                    //    catch (IOException)
                    //    {
                    //        AddAsn1Object("Object", key, o, logger);
                    //    }
                    //}
                    //else
                    //{
                    //    AddAsn1Object("Object", key, tag.GetObject(), logger);
                    //}
                }
                else
                {
                    root.AddValue(currName, obj.GetDerEncoded());
                }
            }
            else
            {
                if (!Config.NoDecode)
                {
                    DerStringBase          str  = obj as DerStringBase;
                    DerObjectIdentifier    oid  = obj as DerObjectIdentifier;
                    DerInteger             i    = obj as DerInteger;
                    DerOctetString         oct  = obj as DerOctetString;
                    DerBitString           bits = obj as DerBitString;
                    DerBoolean             boo  = obj as DerBoolean;
                    DerNull                n    = obj as DerNull;
                    DerUtcTime             time = obj as DerUtcTime;
                    DerGeneralizedTime     gt   = obj as DerGeneralizedTime;
                    DerApplicationSpecific app  = obj as DerApplicationSpecific;

                    if (oct != null)
                    {
                        root.AddValue(new Asn1OctetStringValue(currName, oct.GetOctets()));
                    }
                    else if (bits != null)
                    {
                        root.AddSubNode(new Asn1BitStringKey(currName, bits.PadBits, bits.GetBytes()));
                    }
                    else if (str != null)
                    {
                        Type stringType = typeof(Asn1StringValue <>).MakeGenericType(str.GetType());

                        root.AddValue((DataValue)Activator.CreateInstance(stringType, currName, str.GetString()));
                    }
                    else if (oid != null)
                    {
                        root.AddValue(new Asn1ObjectIdentifierValue(currName, oid.Id));
                    }
                    else if (i != null)
                    {
                        root.AddValue(new Asn1IntegerValue(currName, i.Value.ToByteArray()));
                    }
                    else if (boo != null)
                    {
                        root.AddValue(new Asn1BooleanValue(currName, boo.IsTrue));
                    }
                    else if (n != null)
                    {
                        root.AddValue(new Asn1NullValue(currName));
                    }
                    else if (time != null)
                    {
                        root.AddValue(new Asn1DateTimeValue(currName, time.ToDateTime()));
                    }
                    else if (gt != null)
                    {
                        root.AddValue(new Asn1GeneralizedTimeValue(currName, gt.ToDateTime()));
                    }
                    else if (app != null)
                    {
                        root.AddSubNode(new Asn1ApplicationSpecificValue(currName, app.ApplicationTag, app.GetContents()));
                    }
                    else
                    {
                        logger.LogError("Cannot convert type {0} to a class", obj.GetType().Name);
                        root.AddValue(currName, obj.GetDerEncoded());
                    }
                }
                else
                {
                    root.AddValue(currName, obj.GetDerEncoded());
                }
            }
        }
Пример #4
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);
        }