public override void PerformTest()
		{
			string pseudonym = "pseudonym";
			DirectoryString surname = new DirectoryString("surname");
			Asn1Sequence givenName = new DerSequence(new DirectoryString("givenName"));

			NameOrPseudonym id = new NameOrPseudonym(pseudonym);

			checkConstruction(id, pseudonym, null, null);

			id = new NameOrPseudonym(surname, givenName);

			checkConstruction(id, null, surname, givenName);

			id = NameOrPseudonym.GetInstance(null);

			if (id != null)
			{
				Fail("null GetInstance() failed.");
			}

			try
			{
				NameOrPseudonym.GetInstance(new Object());

				Fail("GetInstance() failed to detect bad object.");
			}
			catch (ArgumentException)
			{
				// expected
			}
		}
		public override void PerformTest()
		{
			GeneralName name = new GeneralName(new X509Name("CN=hello world"));
			Asn1Sequence admissions = new DerSequence(
				new Admissions(name,
				new NamingAuthority(new DerObjectIdentifier("1.2.3"), "url", new DirectoryString("fred")),
				new ProfessionInfo[0]));
			AdmissionSyntax syntax = new AdmissionSyntax(name, admissions);

			checkConstruction(syntax, name, admissions);

			syntax = AdmissionSyntax.GetInstance(null);

			if (syntax != null)
			{
				Fail("null GetInstance() failed.");
			}

			try
			{
				AdmissionSyntax.GetInstance(new Object());

				Fail("GetInstance() failed to detect bad object.");
			}
			catch (ArgumentException)
			{
				// expected
			}
		}
        public TbsCertificateStructure GenerateTbsCertificate()
        {
            if ((serialNumber == null) || (signature == null)
                || (issuer == null) || (startDate == null) || (endDate == null)
                || (subject == null && !altNamePresentAndCritical)
                || (subjectPublicKeyInfo == null))
            {
                throw new InvalidOperationException("not all mandatory fields set in V3 TBScertificate generator");
            }

            DerSequence validity = new DerSequence(startDate, endDate); // before and after dates

            Asn1EncodableVector v = new Asn1EncodableVector(
                version, serialNumber, signature, issuer, validity);

            if (subject != null)
            {
                v.Add(subject);
            }
            else
            {
                v.Add(DerSequence.Empty);
            }

            v.Add(subjectPublicKeyInfo);

            if (issuerUniqueID != null)
            {
                v.Add(new DerTaggedObject(false, 1, issuerUniqueID));
            }

            if (subjectUniqueID != null)
            {
                v.Add(new DerTaggedObject(false, 2, subjectUniqueID));
            }

            if (extensions != null)
            {
                v.Add(new DerTaggedObject(3, extensions));
            }

            return new TbsCertificateStructure(new DerSequence(v));
        }
		public DeclarationOfMajority(
			bool	fullAge,
			string	country)
		{
			if (country.Length > 2)
				throw new ArgumentException("country can only be 2 characters");

			DerPrintableString countryString = new DerPrintableString(country, true);

			DerSequence seq;
			if (fullAge)
			{
				seq = new DerSequence(countryString);
			}
			else
			{
				seq = new DerSequence(DerBoolean.False, countryString);
			}

			this.declaration = new DerTaggedObject(false, 1, seq);
		}
Esempio n. 5
0
        public void Save(
            Stream stream,
            char[]                      password,
            SecureRandom random)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            if (random == null)
            {
                throw new ArgumentNullException("random");
            }

            //
            // handle the keys
            //
            Asn1EncodableVector keyBags = new Asn1EncodableVector();

            foreach (string name in keys.Keys)
            {
                byte[] kSalt = new byte[SaltSize];
                random.NextBytes(kSalt);

                AsymmetricKeyEntry privKey = (AsymmetricKeyEntry)keys[name];

                DerObjectIdentifier bagOid;
                Asn1Encodable       bagData;

                if (password == null)
                {
                    bagOid  = PkcsObjectIdentifiers.KeyBag;
                    bagData = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privKey.Key);
                }
                else
                {
                    bagOid  = PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag;
                    bagData = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(
                        keyAlgorithm, password, kSalt, MinIterations, privKey.Key);
                }

                Asn1EncodableVector kName = new Asn1EncodableVector();

                foreach (string oid in privKey.BagAttributeKeys)
                {
                    Asn1Encodable entry = privKey[oid];

                    // NB: Ignore any existing FriendlyName
                    if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id))
                    {
                        continue;
                    }

                    kName.Add(
                        new DerSequence(
                            new DerObjectIdentifier(oid),
                            new DerSet(entry)));
                }

                //
                // make sure we are using the local alias on store
                //
                // NB: We always set the FriendlyName based on 'name'
                //if (privKey[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null)
                {
                    kName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtFriendlyName,
                            new DerSet(new DerBmpString(name))));
                }

                //
                // make sure we have a local key-id
                //
                if (privKey[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null)
                {
                    X509CertificateEntry   ct           = GetCertificate(name);
                    AsymmetricKeyParameter pubKey       = ct.Certificate.GetPublicKey();
                    SubjectKeyIdentifier   subjectKeyID = CreateSubjectKeyID(pubKey);

                    kName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtLocalKeyID,
                            new DerSet(subjectKeyID)));
                }

                keyBags.Add(new SafeBag(bagOid, bagData.ToAsn1Object(), new DerSet(kName)));
            }

            byte[]      keyBagsEncoding = new DerSequence(keyBags).GetDerEncoded();
            ContentInfo keysInfo        = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(keyBagsEncoding));

            //
            // certificate processing
            //
            byte[] cSalt = new byte[SaltSize];

            random.NextBytes(cSalt);

            Asn1EncodableVector certBags = new Asn1EncodableVector();
            Pkcs12PbeParams     cParams  = new Pkcs12PbeParams(cSalt, MinIterations);
            AlgorithmIdentifier cAlgId   = new AlgorithmIdentifier(certAlgorithm, cParams.ToAsn1Object());
            ISet doneCerts = new HashSet();

            foreach (string name in keys.Keys)
            {
                X509CertificateEntry certEntry = GetCertificate(name);
                CertBag cBag = new CertBag(
                    PkcsObjectIdentifiers.X509Certificate,
                    new DerOctetString(certEntry.Certificate.GetEncoded()));

                Asn1EncodableVector fName = new Asn1EncodableVector();

                foreach (string oid in certEntry.BagAttributeKeys)
                {
                    Asn1Encodable entry = certEntry[oid];

                    // NB: Ignore any existing FriendlyName
                    if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id))
                    {
                        continue;
                    }

                    fName.Add(
                        new DerSequence(
                            new DerObjectIdentifier(oid),
                            new DerSet(entry)));
                }

                //
                // make sure we are using the local alias on store
                //
                // NB: We always set the FriendlyName based on 'name'
                //if (certEntry[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null)
                {
                    fName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtFriendlyName,
                            new DerSet(new DerBmpString(name))));
                }

                //
                // make sure we have a local key-id
                //
                if (certEntry[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null)
                {
                    AsymmetricKeyParameter pubKey       = certEntry.Certificate.GetPublicKey();
                    SubjectKeyIdentifier   subjectKeyID = CreateSubjectKeyID(pubKey);

                    fName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtLocalKeyID,
                            new DerSet(subjectKeyID)));
                }

                certBags.Add(new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)));

                doneCerts.Add(certEntry.Certificate);
            }

            foreach (string certId in certs.Keys)
            {
                X509CertificateEntry cert = (X509CertificateEntry)certs[certId];

                if (keys[certId] != null)
                {
                    continue;
                }

                CertBag cBag = new CertBag(
                    PkcsObjectIdentifiers.X509Certificate,
                    new DerOctetString(cert.Certificate.GetEncoded()));

                Asn1EncodableVector fName = new Asn1EncodableVector();

                foreach (string oid in cert.BagAttributeKeys)
                {
                    // a certificate not immediately linked to a key doesn't require
                    // a localKeyID and will confuse some PKCS12 implementations.
                    //
                    // If we find one, we'll prune it out.
                    if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Id))
                    {
                        continue;
                    }

                    Asn1Encodable entry = cert[oid];

                    // NB: Ignore any existing FriendlyName
                    if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id))
                    {
                        continue;
                    }

                    fName.Add(
                        new DerSequence(
                            new DerObjectIdentifier(oid),
                            new DerSet(entry)));
                }

                //
                // make sure we are using the local alias on store
                //
                // NB: We always set the FriendlyName based on 'certId'
                //if (cert[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null)
                {
                    fName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtFriendlyName,
                            new DerSet(new DerBmpString(certId))));
                }

                certBags.Add(new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)));

                doneCerts.Add(cert.Certificate);
            }

            foreach (CertId certId in chainCerts.Keys)
            {
                X509CertificateEntry cert = (X509CertificateEntry)chainCerts[certId];

                if (doneCerts.Contains(cert.Certificate))
                {
                    continue;
                }

                CertBag cBag = new CertBag(
                    PkcsObjectIdentifiers.X509Certificate,
                    new DerOctetString(cert.Certificate.GetEncoded()));

                Asn1EncodableVector fName = new Asn1EncodableVector();

                foreach (string oid in cert.BagAttributeKeys)
                {
                    // a certificate not immediately linked to a key doesn't require
                    // a localKeyID and will confuse some PKCS12 implementations.
                    //
                    // If we find one, we'll prune it out.
                    if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Id))
                    {
                        continue;
                    }

                    fName.Add(
                        new DerSequence(
                            new DerObjectIdentifier(oid),
                            new DerSet(cert[oid])));
                }

                certBags.Add(new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)));
            }

            byte[] certBagsEncoding = new DerSequence(certBags).GetDerEncoded();

            ContentInfo certsInfo;

            if (password == null)
            {
                certsInfo = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(certBagsEncoding));
            }
            else
            {
                byte[]        certBytes = CryptPbeData(true, cAlgId, password, false, certBagsEncoding);
                EncryptedData cInfo     = new EncryptedData(PkcsObjectIdentifiers.Data, cAlgId, new BerOctetString(certBytes));
                certsInfo = new ContentInfo(PkcsObjectIdentifiers.EncryptedData, cInfo.ToAsn1Object());
            }

            ContentInfo[] info = new ContentInfo[] { keysInfo, certsInfo };

            byte[] data = new AuthenticatedSafe(info).GetEncoded(
                useDerEncoding ? Asn1Encodable.Der : Asn1Encodable.Ber);

            ContentInfo mainInfo = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(data));

            //
            // create the mac
            //
            MacData macData = null;

            if (password != null)
            {
                byte[] mSalt = new byte[20];
                random.NextBytes(mSalt);

                byte[] mac = CalculatePbeMac(OiwObjectIdentifiers.IdSha1,
                                             mSalt, MinIterations, password, false, data);

                AlgorithmIdentifier algId = new AlgorithmIdentifier(
                    OiwObjectIdentifiers.IdSha1, DerNull.Instance);
                DigestInfo dInfo = new DigestInfo(algId, mac);

                macData = new MacData(dInfo, mSalt, MinIterations);
            }

            //
            // output the Pfx
            //
            Pfx pfx = new Pfx(mainInfo, macData);

            DerOutputStream derOut;

            if (useDerEncoding)
            {
                derOut = new DerOutputStream(stream);
            }
            else
            {
                derOut = new BerOutputStream(stream);
            }

            derOut.WriteObject(pfx);
        }
Esempio n. 6
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);
        }
        internal static void PrepareNextCertB1(
            int i,
            IList[] policyNodes,
            string id_p,
            IDictionary m_idp,
            X509Certificate cert)
        {
            bool        idp_found = false;
            IEnumerator nodes_i   = policyNodes[i].GetEnumerator();

            while (nodes_i.MoveNext())
            {
                PkixPolicyNode node = (PkixPolicyNode)nodes_i.Current;
                if (node.ValidPolicy.Equals(id_p))
                {
                    idp_found             = true;
                    node.ExpectedPolicies = (ISet)m_idp[id_p];
                    break;
                }
            }

            if (!idp_found)
            {
                nodes_i = policyNodes[i].GetEnumerator();
                while (nodes_i.MoveNext())
                {
                    PkixPolicyNode node = (PkixPolicyNode)nodes_i.Current;
                    if (ANY_POLICY.Equals(node.ValidPolicy))
                    {
                        ISet         pq       = null;
                        Asn1Sequence policies = null;
                        try
                        {
                            policies = DerSequence.GetInstance(GetExtensionValue(cert, X509Extensions.CertificatePolicies));
                        }
                        catch (Exception e)
                        {
                            throw new Exception("Certificate policies cannot be decoded.", e);
                        }

                        IEnumerator enm = policies.GetEnumerator();
                        while (enm.MoveNext())
                        {
                            PolicyInformation pinfo = null;

                            try
                            {
                                pinfo = PolicyInformation.GetInstance(enm.Current);
                            }
                            catch (Exception ex)
                            {
                                throw new Exception("Policy information cannot be decoded.", ex);
                            }

                            if (ANY_POLICY.Equals(pinfo.PolicyIdentifier.Id))
                            {
                                try
                                {
                                    pq = GetQualifierSet(pinfo.PolicyQualifiers);
                                }
                                catch (PkixCertPathValidatorException ex)
                                {
                                    throw new PkixCertPathValidatorException(
                                              "Policy qualifier info set could not be built.", ex);
                                }
                                break;
                            }
                        }
                        bool ci          = false;
                        ISet critExtOids = cert.GetCriticalExtensionOids();
                        if (critExtOids != null)
                        {
                            ci = critExtOids.Contains(X509Extensions.CertificatePolicies.Id);
                        }

                        PkixPolicyNode p_node = (PkixPolicyNode)node.Parent;
                        if (ANY_POLICY.Equals(p_node.ValidPolicy))
                        {
                            PkixPolicyNode c_node = new PkixPolicyNode(
                                BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(), i,
                                (ISet)m_idp[id_p],
                                p_node, pq, id_p, ci);
                            p_node.AddChild(c_node);
                            policyNodes[i].Add(c_node);
                        }
                        break;
                    }
                }
            }
        }
        /// <summary>
        /// Create a CSR and submit it to the Acme server for signing. Returns the certificate chain.
        /// </summary>
        /// <param name="domains">The list of domains that this certificate will be for. The first domain listed will be the CommonName.</param>
        /// <param name="keyPair">The RSA key pair for signing the certificate request, this is the key that will be used in conjunction with the certificate.</param>
        /// <returns>A tuple whose first value is the private key data and whose second value is a list of certificates. Everything is encoded in DER format, the first certificate is the signed certificate.</returns>
        public Tuple <byte[], List <byte[]> > GetCertificate(ICollection <string> domains)
        {
            //
            // Generate a new key for the certificate.
            //
            var generator = new RsaKeyPairGenerator();

            generator.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
            var keyPair = generator.GenerateKeyPair();
            var sig     = new Asn1SignatureFactory("SHA256WITHRSA", keyPair.Private);

            var commonName = new X509Name(new DerObjectIdentifier[] { X509Name.CN }, new string[] { domains.First() });

            //
            // Generate the list of subject alternative names.
            //
            List <GeneralName> names = new List <GeneralName>();

            foreach (var domain in domains)
            {
                names.Add(new GeneralName(GeneralName.DnsName, domain));
            }
            var sanOctect    = new DerOctetString(new GeneralNames(names.ToArray()));
            var sanSequence  = new DerSequence(X509Extensions.SubjectAlternativeName, sanOctect);
            var extensionSet = new DerSet(new DerSequence(sanSequence));
            var attributes   = new DerSet(new DerSequence(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, extensionSet));

            //
            // Generate the CSR from all the data.
            //
            var csr = new Pkcs10CertificationRequest(sig, commonName, keyPair.Public, attributes, keyPair.Private);

            var payload = new
            {
                resource = "new-cert",
                csr      = UrlBase64Encode(csr.GetDerEncoded())
            };

            var certificates = new List <X509Certificate>();
            var certParser   = new X509CertificateParser();

            byte[] certData;

            //
            // Send the request and fetch the certificate data.
            //
            certData = SendMessage <byte[]>(Directory.NewCert, payload, GetNonce(), out WebHeaderCollection headers);
            certificates.Add(certParser.ReadCertificate(certData));

            //
            // Fetch all the certificates in the chain.
            //
            foreach (var link in headers.GetValues("Link"))
            {
                var match = System.Text.RegularExpressions.Regex.Match(link, "\\<(.*)\\>;rel=\"(.*)\"");
                if (match.Success && match.Groups[2].Value == "up")
                {
                    certData = GetRequest <byte[]>(match.Groups[1].Value);
                    certificates.Add(certParser.ReadCertificate(certData));
                }
            }

            var privateKeyData  = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private).ToAsn1Object().GetDerEncoded();
            var certificateData = certificates.Select(c => c.GetEncoded()).ToList();

            return(new Tuple <byte[], List <byte[]> >(privateKeyData, certificateData));
        }
        /// <summary>
        /// Generate a self signed certificate.
        /// </summary>
        /// <param name="subjectName"><see cref="Uri"/> object the subject name</param>
        /// <param name="issuerName"> The name of the issuer </param>
        /// <param name="issuerPrivKey"><see cref="AsymmetricKeyParameter"/> object of the issuer private key</param>
        /// <param name="keyStrength">
        /// The strength of thet key.
        /// Default: 2048
        /// </param>
        /// <returns>
        /// Returns a <see cref="X509Certificate2"/>instance of the certificate.
        /// </returns>
        private static X509Certificate2 GenerateSelfSignedCertificate(Uri subjectName, string issuerName, AsymmetricKeyParameter issuerPrivKey, int keyStrength = 2048)
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

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

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

            certificateGenerator.SetSerialNumber(serialNumber);

            // Signature Algorithm
            const string signatureAlgorithm = "SHA256WithRSA";

            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);

            // Issuer and Subject Name
            var subjectDN = new X509Name($"CN=*.{subjectName.DnsSafeHost}, O={issuerName}, OU=Created by http://httplogger.net");
            var issuerDN  = new X509Name($"CN={issuerName}, O={issuerName}, OU=Created by http://httplogger.net");

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            var subjectAlternativeNames = new Asn1Encodable[]
            {
                new GeneralName(GeneralName.DnsName, $"{subjectName.DnsSafeHost}"),
                new GeneralName(GeneralName.DnsName, $"*.{subjectName.DnsSafeHost}"),
            };
            var subjectAlternativeNamesExtension = new DerSequence(subjectAlternativeNames);

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

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

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

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

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

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Generating the Certificate
            var issuerKeyPair = subjectKeyPair;

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

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


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

            var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded());

            if (seq.Count != 9)
            {
                throw new PemException("malformed sequence in RSA private key");
            }

            var rsa = new RsaPrivateKeyStructure(seq);

            var rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams);

            AddCertificateToStore(x509, StoreName.My, StoreLocation.CurrentUser);
            return(x509);
        }
Esempio n. 10
0
        private BasicOcspResp GenerateResponse(
            ISignatureFactory signatureCalculator,
            X509Certificate[]               chain,
            DateTime producedAt)
        {
            AlgorithmIdentifier signingAlgID     = (AlgorithmIdentifier)signatureCalculator.AlgorithmDetails;
            DerObjectIdentifier signingAlgorithm = signingAlgID.Algorithm;

            Asn1EncodableVector responses = new Asn1EncodableVector();

            foreach (ResponseObject respObj in list)
            {
                try
                {
                    responses.Add(respObj.ToResponse());
                }
                catch (Exception e)
                {
                    throw new OcspException("exception creating Request", e);
                }
            }

            ResponseData tbsResp = new ResponseData(responderID.ToAsn1Object(), new DerGeneralizedTime(producedAt), new DerSequence(responses), responseExtensions);
            DerBitString bitSig  = null;

            try
            {
                IStreamCalculator streamCalculator = signatureCalculator.CreateCalculator();

                byte[] encoded = tbsResp.GetDerEncoded();

                streamCalculator.Stream.Write(encoded, 0, encoded.Length);

                Platform.Dispose(streamCalculator.Stream);

                bitSig = new DerBitString(((IBlockResult)streamCalculator.GetResult()).Collect());
            }
            catch (Exception e)
            {
                throw new OcspException("exception processing TBSRequest: " + e, e);
            }

            AlgorithmIdentifier sigAlgId = OcspUtilities.GetSigAlgID(signingAlgorithm);

            DerSequence chainSeq = null;

            if (chain != null && chain.Length > 0)
            {
                Asn1EncodableVector v = new Asn1EncodableVector();
                try
                {
                    for (int i = 0; i != chain.Length; i++)
                    {
                        v.Add(
                            X509CertificateStructure.GetInstance(
                                Asn1Object.FromByteArray(chain[i].GetEncoded())));
                    }
                }
                catch (IOException e)
                {
                    throw new OcspException("error processing certs", e);
                }
                catch (CertificateEncodingException e)
                {
                    throw new OcspException("error encoding certs", e);
                }

                chainSeq = new DerSequence(v);
            }

            return(new BasicOcspResp(new BasicOcspResponse(tbsResp, sigAlgId, bitSig, chainSeq)));
        }
Esempio n. 11
0
        public void WriteObject(
            object obj)
        {
            if (obj == null)
            {
                throw new ArgumentNullException("obj");
            }

            string type;

            byte[] encoding;

            if (obj is X509Certificate)
            {
                // TODO Should we prefer "X509 CERTIFICATE" here?
                type = "CERTIFICATE";
                try
                {
                    encoding = ((X509Certificate)obj).GetEncoded();
                }
                catch (CertificateEncodingException e)
                {
                    throw new IOException("Cannot Encode object: " + e.ToString());
                }
            }
            else if (obj is X509Crl)
            {
                type = "X509 CRL";
                try
                {
                    encoding = ((X509Crl)obj).GetEncoded();
                }
                catch (CrlException e)
                {
                    throw new IOException("Cannot Encode object: " + e.ToString());
                }
            }
            else if (obj is AsymmetricCipherKeyPair)
            {
                WriteObject(((AsymmetricCipherKeyPair)obj).Private);
                return;
            }
            else if (obj is AsymmetricKeyParameter)
            {
                AsymmetricKeyParameter akp = (AsymmetricKeyParameter)obj;
                if (akp.IsPrivate)
                {
                    PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(akp);

                    if (obj is RsaKeyParameters)
                    {
                        type = "RSA PRIVATE KEY";

                        encoding = info.PrivateKey.GetEncoded();
                    }
                    else if (obj is DsaPrivateKeyParameters)
                    {
                        type = "DSA PRIVATE KEY";

                        DsaParameter p = DsaParameter.GetInstance(info.AlgorithmID.Parameters);

                        BigInteger x = ((DsaPrivateKeyParameters)obj).X;
                        BigInteger y = p.G.ModPow(x, p.P);

                        // TODO Create an ASN1 object somewhere for this?
                        encoding = new DerSequence(
                            new DerInteger(0),
                            new DerInteger(p.P),
                            new DerInteger(p.Q),
                            new DerInteger(p.G),
                            new DerInteger(y),
                            new DerInteger(x)).GetEncoded();
                    }
                    else
                    {
                        throw new IOException("Cannot identify private key");
                    }
                }
                else
                {
                    type = "PUBLIC KEY";

                    encoding = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(akp).GetDerEncoded();
                }
            }
            else if (obj is IX509AttributeCertificate)
            {
                type     = "ATTRIBUTE CERTIFICATE";
                encoding = ((X509V2AttributeCertificate)obj).GetEncoded();
            }
            else if (obj is Pkcs10CertificationRequest)
            {
                type     = "CERTIFICATE REQUEST";
                encoding = ((Pkcs10CertificationRequest)obj).GetEncoded();
            }
            else if (obj is Asn1.Cms.ContentInfo)
            {
                type     = "PKCS7";
                encoding = ((Asn1.Cms.ContentInfo)obj).GetEncoded();
            }
            else
            {
                throw new ArgumentException("Object type not supported: " + obj.GetType().FullName, "obj");
            }

            WriteHeader(type);
            WriteBase64Encoded(encoding);
            WriteFooter(type);
        }
Esempio n. 12
0
            internal RecipientInfo ToRecipientInfo(
                KeyParameter key,
                SecureRandom random)
            {
                byte[] keyBytes = key.GetKey();

                if (pubKey != null)
                {
                    IWrapper keyWrapper = Helper.CreateWrapper(keyEncAlg.ObjectID.Id);

                    keyWrapper.Init(true, new ParametersWithRandom(pubKey, random));

                    Asn1OctetString encKey = new DerOctetString(
                        keyWrapper.Wrap(keyBytes, 0, keyBytes.Length));

                    RecipientIdentifier recipId;
                    if (cert != null)
                    {
                        TbsCertificateStructure tbs = TbsCertificateStructure.GetInstance(
                            Asn1Object.FromByteArray(cert.GetTbsCertificate()));

                        Asn1.Cms.IssuerAndSerialNumber encSid = new Asn1.Cms.IssuerAndSerialNumber(
                            tbs.Issuer, tbs.SerialNumber.Value);

                        recipId = new RecipientIdentifier(encSid);
                    }
                    else
                    {
                        recipId = new RecipientIdentifier(subKeyId);
                    }

                    return(new RecipientInfo(new KeyTransRecipientInfo(recipId, keyEncAlg, encKey)));
                }
                else if (originator != null)
                {
                    IWrapper keyWrapper = Helper.CreateWrapper(
                        DerObjectIdentifier.GetInstance(
                            Asn1Sequence.GetInstance(keyEncAlg.Parameters)[0]).Id);

                    keyWrapper.Init(true, new ParametersWithRandom(secKey, random));

                    Asn1OctetString encKey = new DerOctetString(
                        keyWrapper.Wrap(keyBytes, 0, keyBytes.Length));

                    RecipientEncryptedKey rKey = new RecipientEncryptedKey(
                        new KeyAgreeRecipientIdentifier(
                            new Asn1.Cms.IssuerAndSerialNumber(
                                PrincipalUtilities.GetIssuerX509Principal(cert),
                                cert.SerialNumber)),
                        encKey);

                    return(new RecipientInfo(
                               new KeyAgreeRecipientInfo(originator, ukm, keyEncAlg, new DerSequence(rKey))));
                }
                else if (derivationAlg != null)
                {
                    string   rfc3211WrapperName = Helper.GetRfc3211WrapperName(secKeyAlgorithm);
                    IWrapper keyWrapper         = Helper.CreateWrapper(rfc3211WrapperName);


                    // Note: In Java build, the IV is automatically generated in JCE layer
                    int    ivLength = rfc3211WrapperName.StartsWith("DESEDE") ? 8 : 16;
                    byte[] iv       = new byte[ivLength];
                    random.NextBytes(iv);


                    ICipherParameters parameters = new ParametersWithIV(secKey, iv);
                    keyWrapper.Init(true, new ParametersWithRandom(parameters, random));

                    Asn1OctetString encKey = new DerOctetString(
                        keyWrapper.Wrap(keyBytes, 0, keyBytes.Length));

//					byte[] iv = keyWrapper.GetIV();

                    DerSequence seq = new DerSequence(
                        new DerObjectIdentifier(secKeyAlgorithm),
                        new DerOctetString(iv));

                    keyEncAlg = new AlgorithmIdentifier(PkcsObjectIdentifiers.IdAlgPwriKek, seq);

                    return(new RecipientInfo(new PasswordRecipientInfo(derivationAlg, keyEncAlg, encKey)));
                }
                else
                {
                    IWrapper keyWrapper = Helper.CreateWrapper(keyEncAlg.ObjectID.Id);

                    keyWrapper.Init(true, new ParametersWithRandom(secKey, random));

                    Asn1OctetString encKey = new DerOctetString(
                        keyWrapper.Wrap(keyBytes, 0, keyBytes.Length));

                    return(new RecipientInfo(new KekRecipientInfo(secKeyId, keyEncAlg, encKey)));
                }
            }
Esempio n. 13
0
        public X9Curve(
            X9FieldID fieldID,
            BigInteger order,
            BigInteger cofactor,
            Asn1Sequence seq)
        {
            if (fieldID == null)
            {
                throw new ArgumentNullException("fieldID");
            }
            if (seq == null)
            {
                throw new ArgumentNullException("seq");
            }

            this.fieldIdentifier = fieldID.Identifier;

            if (fieldIdentifier.Equals(X9ObjectIdentifiers.PrimeField))
            {
                BigInteger p = ((DerInteger)fieldID.Parameters).Value;
                BigInteger A = new BigInteger(1, Asn1OctetString.GetInstance(seq[0]).GetOctets());
                BigInteger B = new BigInteger(1, Asn1OctetString.GetInstance(seq[1]).GetOctets());
                curve = new FpCurve(p, A, B, order, cofactor);
            }
            else if (fieldIdentifier.Equals(X9ObjectIdentifiers.CharacteristicTwoField))
            {
                // Characteristic two field
                DerSequence         parameters     = (DerSequence)fieldID.Parameters;
                int                 m              = ((DerInteger)parameters[0]).IntValueExact;
                DerObjectIdentifier representation = (DerObjectIdentifier)parameters[1];

                int k1 = 0;
                int k2 = 0;
                int k3 = 0;
                if (representation.Equals(X9ObjectIdentifiers.TPBasis))
                {
                    // Trinomial basis representation
                    k1 = ((DerInteger)parameters[2]).IntValueExact;
                }
                else
                {
                    // Pentanomial basis representation
                    DerSequence pentanomial = (DerSequence)parameters[2];
                    k1 = ((DerInteger)pentanomial[0]).IntValueExact;
                    k2 = ((DerInteger)pentanomial[1]).IntValueExact;
                    k3 = ((DerInteger)pentanomial[2]).IntValueExact;
                }
                BigInteger A = new BigInteger(1, Asn1OctetString.GetInstance(seq[0]).GetOctets());
                BigInteger B = new BigInteger(1, Asn1OctetString.GetInstance(seq[1]).GetOctets());
                curve = new F2mCurve(m, k1, k2, k3, A, B, order, cofactor);
            }
            else
            {
                throw new ArgumentException("This type of ECCurve is not implemented");
            }

            if (seq.Count == 3)
            {
                seed = ((DerBitString)seq[2]).GetBytes();
            }
        }
Esempio n. 14
0
        public TbsCertificateStructure GenerateTbsCertificate()
        {
            if (this.serialNumber == null || this.signature == null || this.issuer == null || this.startDate == null || this.endDate == null || (this.subject == null && !this.altNamePresentAndCritical) || this.subjectPublicKeyInfo == null)
            {
                throw new InvalidOperationException("not all mandatory fields set in V3 TBScertificate generator");
            }
            DerSequence derSequence = new DerSequence(new Asn1Encodable[]
            {
                this.startDate,
                this.endDate
            });
            Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector(new Asn1Encodable[]
            {
                this.version,
                this.serialNumber,
                this.signature,
                this.issuer,
                derSequence
            });

            if (this.subject != null)
            {
                asn1EncodableVector.Add(new Asn1Encodable[]
                {
                    this.subject
                });
            }
            else
            {
                asn1EncodableVector.Add(new Asn1Encodable[]
                {
                    DerSequence.Empty
                });
            }
            asn1EncodableVector.Add(new Asn1Encodable[]
            {
                this.subjectPublicKeyInfo
            });
            if (this.issuerUniqueID != null)
            {
                asn1EncodableVector.Add(new Asn1Encodable[]
                {
                    new DerTaggedObject(false, 1, this.issuerUniqueID)
                });
            }
            if (this.subjectUniqueID != null)
            {
                asn1EncodableVector.Add(new Asn1Encodable[]
                {
                    new DerTaggedObject(false, 2, this.subjectUniqueID)
                });
            }
            if (this.extensions != null)
            {
                asn1EncodableVector.Add(new Asn1Encodable[]
                {
                    new DerTaggedObject(3, this.extensions)
                });
            }
            return(new TbsCertificateStructure(new DerSequence(asn1EncodableVector)));
        }
        public override void PerformTest()
        {
            DerUtf8String countryName = new DerUtf8String("Australia");

            SignerLocation sl = new SignerLocation(countryName, null, null);

            CheckConstruction(sl, DirectoryString.GetInstance(countryName), null, null);

            DerUtf8String localityName = new DerUtf8String("Melbourne");

            sl = new SignerLocation(null, localityName, null);

            CheckConstruction(sl, null, DirectoryString.GetInstance(localityName), null);

            sl = new SignerLocation(countryName, localityName, null);

            CheckConstruction(sl, DirectoryString.GetInstance(countryName), DirectoryString.GetInstance(localityName), null);

            Asn1Sequence postalAddress = new DerSequence(
                new DerUtf8String("line 1"),
                new DerUtf8String("line 2"));

            sl = new SignerLocation(null, null, postalAddress);

            CheckConstruction(sl, null, null, postalAddress);

            sl = new SignerLocation(countryName, null, postalAddress);

            CheckConstruction(sl, DirectoryString.GetInstance(countryName), null, postalAddress);

            sl = new SignerLocation(countryName, localityName, postalAddress);

            CheckConstruction(sl, DirectoryString.GetInstance(countryName), DirectoryString.GetInstance(localityName), postalAddress);

            sl = SignerLocation.GetInstance(null);

            if (sl != null)
            {
                Fail("null GetInstance() failed.");
            }

            try
            {
                SignerLocation.GetInstance(new object());

                Fail("GetInstance() failed to detect bad object.");
            }
            catch (ArgumentException)
            {
                // expected
            }

            //
            // out of range postal address
            //
            postalAddress = new DerSequence(
                new DerUtf8String("line 1"),
                new DerUtf8String("line 2"),
                new DerUtf8String("line 3"),
                new DerUtf8String("line 4"),
                new DerUtf8String("line 5"),
                new DerUtf8String("line 6"),
                new DerUtf8String("line 7"));

            try
            {
                new SignerLocation(null, null, postalAddress);

                Fail("constructor failed to detect bad postalAddress.");
            }
            catch (ArgumentException)
            {
                // expected
            }

            try
            {
                new SignerLocation(new DerSequence(new DerTaggedObject(2, postalAddress)));

                Fail("sequence constructor failed to detect bad postalAddress.");
            }
            catch (ArgumentException)
            {
                // expected
            }

            try
            {
                new SignerLocation(new DerSequence(new DerTaggedObject(5, postalAddress)));

                Fail("sequence constructor failed to detect bad tag.");
            }
            catch (ArgumentException)
            {
                // expected
            }
        }
        public static MyPolicy getHashPolitica(string PolicyUriSource, string PolicyIdentifier = "2.16.76.1.7.1.2.2.3", string PolicyDigestAlgorithm = "SHA-256", string FileName = "LPA_CAdES.der")
        {
            MyPolicy Retorno = new MyPolicy();

            Retorno.PolicyIdentifier      = PolicyIdentifier;
            Retorno.PolicyDigestAlgorithm = PolicyDigestAlgorithm;
            Retorno.URLPolicy             = PolicyUriSource;

            Stream St;

            try
            {
                St = Helper.FileHelper.MSReadFileURL(PolicyUriSource);
            }
            catch (Exception ex)
            {
                //FileStream File = Helper.FileHelper.FSReadFile(System.AppDomain.CurrentDomain.BaseDirectory + FileName);
                //St = File;
                St = new MemoryStream(Properties.Resources.LPA_CAdES);
            }
            DerSequence privKeyObj = (DerSequence)Asn1Object.FromStream(St);

            var objCollection = privKeyObj.GetEnumerator();

            objCollection.MoveNext();


            Org.BouncyCastle.Asn1.Asn1Sequence objPrincipal = (Org.BouncyCastle.Asn1.Asn1Sequence)objCollection.Current;
            var Politicas = objPrincipal.GetObjects();



            while (Politicas.MoveNext())
            {
                Org.BouncyCastle.Asn1.Asn1Sequence Politica = (Org.BouncyCastle.Asn1.Asn1Sequence)Politicas.Current;
                var Itens = Politica.GetObjects();
                Itens.MoveNext();
                string item1 = Itens.Current.ToString();
                Itens.MoveNext();
                string item2 = Itens.Current.ToString();
                if (item2.Contains(PolicyIdentifier))
                {
                    Itens.MoveNext();
                    string item3 = Itens.Current.ToString();
                    Retorno.SubURLPolicy = item3.Replace("[", "").Replace("]", "");

                    Itens.MoveNext();
                    Org.BouncyCastle.Asn1.Asn1Sequence item4 = (Org.BouncyCastle.Asn1.Asn1Sequence)Itens.Current;

                    var Item4d = item4.GetObjects();
                    Item4d.MoveNext();
                    Retorno.SubPolicyIdentifier = Item4d.Current.ToString().Replace("[", "").Replace("]", "");


                    Item4d.MoveNext();
                    Retorno.Hash = Item4d.Current.ToString();
                }
            }
            St.Close();
            return(Retorno);
        }
Esempio n. 17
0
 public void Setup()
 {
     var sec1Key = keyProvider.GetPkcs8PrivateKeyAsSec1((IEcKey)keyPair.PrivateKey);
     convertedKey = keyProvider.GetSec1PrivateKeyAsPkcs8(sec1Key.Content);
     keySequence = (DerSequence)Asn1Object.FromByteArray(convertedKey.Content);
 }
Esempio n. 18
0
        private BasicOcspResp GenerateResponse(
            string signatureName,
            AsymmetricKeyParameter privateKey,
            X509Certificate[]               chain,
            DateTime producedAt,
            SecureRandom random)
        {
            DerObjectIdentifier signingAlgorithm;

            try
            {
                signingAlgorithm = OcspUtilities.GetAlgorithmOid(signatureName);
            }
            catch (Exception e)
            {
                throw new ArgumentException("unknown signing algorithm specified", e);
            }

            Asn1EncodableVector responses = new Asn1EncodableVector();

            foreach (ResponseObject respObj in list)
            {
                try
                {
                    responses.Add(respObj.ToResponse());
                }
                catch (Exception e)
                {
                    throw new OcspException("exception creating Request", e);
                }
            }

            ResponseData tbsResp = new ResponseData(responderID.ToAsn1Object(), new DerGeneralizedTime(producedAt), new DerSequence(responses), responseExtensions);

            ISigner sig = null;

            try
            {
                sig = SignerUtilities.GetSigner(signatureName);

                if (random != null)
                {
                    sig.Init(true, new ParametersWithRandom(privateKey, random));
                }
                else
                {
                    sig.Init(true, privateKey);
                }
            }
            catch (Exception e)
            {
                throw new OcspException("exception creating signature: " + e, e);
            }

            DerBitString bitSig = null;

            try
            {
                byte[] encoded = tbsResp.GetDerEncoded();
                sig.BlockUpdate(encoded, 0, encoded.Length);

                bitSig = new DerBitString(sig.GenerateSignature());
            }
            catch (Exception e)
            {
                throw new OcspException("exception processing TBSRequest: " + e, e);
            }

            AlgorithmIdentifier sigAlgId = OcspUtilities.GetSigAlgID(signingAlgorithm);

            DerSequence chainSeq = null;

            if (chain != null && chain.Length > 0)
            {
                Asn1EncodableVector v = new Asn1EncodableVector();
                try
                {
                    for (int i = 0; i != chain.Length; i++)
                    {
                        v.Add(
                            X509CertificateStructure.GetInstance(
                                Asn1Object.FromByteArray(chain[i].GetEncoded())));
                    }
                }
                catch (IOException e)
                {
                    throw new OcspException("error processing certs", e);
                }
                catch (CertificateEncodingException e)
                {
                    throw new OcspException("error encoding certs", e);
                }

                chainSeq = new DerSequence(v);
            }

            return(new BasicOcspResp(new BasicOcspResponse(tbsResp, sigAlgId, bitSig, chainSeq)));
        }
        static internal RIoTDeviceInfo Decode(X509Certificate2 aliasCert)
        {
            AsnEncodedData altNames = null;

            foreach (var ext in aliasCert.Extensions)
            {
                if (ext.Oid.Value != RIoTOid)
                {
                    continue;
                }
                altNames = new AsnEncodedData(ext.Oid, ext.RawData);
            }
            // an AltName is mandatory
            if (altNames == null)
            {
                Helpers.Notify("Certificate does not have an altName field", true);
                return(null);
            }
            // parse the extension: this is a collection of nested thus -

            /*
             *  DER Sequence
             *      ObjectIdentifier(1.2.3.4.5.6)                               <- RIoT Composite ID OID
             *      DER Sequence
             *          Integer(1)                                              <- Version number
             *          DER Sequence                                            <- DeviceID public key
             *              DER Sequence                                            (same encoding as in DeviceID cert)
             *                  ObjectIdentifier(1.2.840.10045.2.1)                 EC pubkey
             *                  ObjectIdentifier(1.2.840.10045.3.1.7)               prime256
             *              DER Bit String[65, 0]                                   key value
             *          DER Sequence                                            <-  Encoded FWID
             *              ObjectIdentifier(2.16.840.1.101.3.4.2.1)                sha256
             *              DER Octet String[32]                                    FWID hash value
             *
             *
             * */

            try
            {
                DerSequence seq = (DerSequence)DerSequence.FromByteArray(altNames.RawData);
                //DerTaggedObject obj = (DerTaggedObject)seq[0];
                //DerSequence obj2 = (DerSequence)obj.GetObject();
                //var oid = (DerObjectIdentifier)obj2[0];
                //if (oid.Id != RIoTOid) return ParseError("Incorrect RIoT OID");


                var versionNumber = (DerInteger)seq[0];
                if (versionNumber.PositiveValue.IntValue != 1)
                {
                    return(ParseError("Wrong version number"));
                }

                DerSequence obj4    = (DerSequence)seq[1];
                DerSequence obj5    = (DerSequence)obj4[0];
                var         keyAlg1 = (DerObjectIdentifier)obj5[0];
                var         keyAlg2 = (DerObjectIdentifier)obj5[1];
                if (keyAlg1.Id != ecPubKeyOID)
                {
                    return(ParseError("Bad ECPubKey OID"));
                }
                if (keyAlg2.Id != prime256v1Oid)
                {
                    return(ParseError("Bad curve OID"));
                }
                var key     = (DerBitString)obj4[1];
                var obj4b   = (DerSequence)seq[2];
                var hashAlg = (DerObjectIdentifier)obj4b[0];
                if (hashAlg.Id != sha256Oid)
                {
                    return(ParseError("Bad fwid hash OID"));
                }
                var            hash       = (DerOctetString)obj4b[1];
                RIoTDeviceInfo deviceInfo = new RIoTDeviceInfo()
                {
                    FirmwareID         = hash.GetOctets(),
                    EncodedDeviceIDKey = key.GetBytes(),
                    Cert = aliasCert
                };

                return(deviceInfo);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
                return(null);
            }
        }
Esempio n. 20
0
        public static byte[] HandleKey(byte[] key, byte[] secretKey)
        {
            Asn1InputStream inputStream = new Asn1InputStream(key);
            Asn1Object      o1          = inputStream.ReadObject();
            DerSequence     seq         = o1 as DerSequence;

            DerInteger x = seq[2] as DerInteger;
            DerInteger y = seq[3] as DerInteger;

            X9ECParameters     p = CustomNamedCurves.GetByName("secp521r1");
            ECDomainParameters domainParameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H);

            ECPoint point = p.Curve.CreatePoint(x.Value, y.Value);
            ECPublicKeyParameters publicKeyParameters = new ECPublicKeyParameters(point, domainParameters);

            ECKeyPairGenerator generator = new ECKeyPairGenerator();

            generator.Init(new ECKeyGenerationParameters(publicKeyParameters.Parameters, new SecureRandom()));
            AsymmetricCipherKeyPair keyPair = generator.GenerateKeyPair();

            ECDHBasicAgreement basicAgreement = new ECDHBasicAgreement();

            basicAgreement.Init(keyPair.Private);
            BigInteger agreement = basicAgreement.CalculateAgreement(publicKeyParameters);

            byte[] agreementBytes = agreement.ToByteArray();
            if (agreementBytes.Length == 65)
            {
                byte[] newAgreement = new byte[66];
                Array.Copy(agreementBytes, 0, newAgreement, 1, 65);
                agreementBytes = newAgreement;
            }

            Sha512Digest sha512 = new Sha512Digest();

            byte[] hash = new byte[sha512.GetDigestSize()];
            sha512.BlockUpdate(agreementBytes, 0, agreementBytes.Length);
            sha512.DoFinal(hash, 0);

            byte[] secret = new byte[secretKey.Length];
            for (int i = 0; i < secret.Length; i++)
            {
                secret[i]  = secretKey[i];
                secret[i] ^= hash[i];
            }

            ECPublicKeyParameters publicKey = keyPair.Public as ECPublicKeyParameters;

            MemoryStream         keyStream = new MemoryStream();
            DerSequenceGenerator gen2      = new DerSequenceGenerator(keyStream);

            gen2.AddObject(new DerBitString(new byte[] { 0x00 }, 7));
            gen2.AddObject(new DerInteger(new byte[] { 0x41 }));
            gen2.AddObject(new DerInteger(publicKey.Q.XCoord.ToBigInteger()));
            gen2.AddObject(new DerInteger(publicKey.Q.YCoord.ToBigInteger()));
            gen2.Close();

            MemoryStream memoryStream = new MemoryStream();

            DerSequenceGenerator gen1 = new DerSequenceGenerator(memoryStream);

            gen1.AddObject(new DerObjectIdentifier("2.16.840.1.101.3.4.2.3"));
            gen1.AddObject(new DerOctetString(keyStream.ToArray()));
            gen1.AddObject(new DerOctetString(secret));
            gen1.Close();

            byte[] result = memoryStream.ToArray();

            memoryStream.Close();
            keyStream.Close();

            return(result);
        }
        private BasicOcspResp GenerateResponse(ISignatureFactory signatureCalculator, X509Certificate[] chain, global::System.DateTime producedAt)
        {
            //IL_016c: Expected O, but got Unknown
            AlgorithmIdentifier algorithmIdentifier = (AlgorithmIdentifier)signatureCalculator.AlgorithmDetails;
            DerObjectIdentifier algorithm           = algorithmIdentifier.Algorithm;
            Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector();

            global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)list).GetEnumerator();
            try
            {
                while (enumerator.MoveNext())
                {
                    ResponseObject responseObject = (ResponseObject)enumerator.get_Current();
                    try
                    {
                        asn1EncodableVector.Add(responseObject.ToResponse());
                    }
                    catch (global::System.Exception e)
                    {
                        throw new OcspException("exception creating Request", e);
                    }
                }
            }
            finally
            {
                global::System.IDisposable disposable = enumerator as global::System.IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
            ResponseData responseData = new ResponseData(responderID.ToAsn1Object(), new DerGeneralizedTime(producedAt), new DerSequence(asn1EncodableVector), responseExtensions);
            DerBitString derBitString = null;

            try
            {
                IStreamCalculator streamCalculator = signatureCalculator.CreateCalculator();
                byte[]            derEncoded       = responseData.GetDerEncoded();
                streamCalculator.Stream.Write(derEncoded, 0, derEncoded.Length);
                Platform.Dispose(streamCalculator.Stream);
                derBitString = new DerBitString(((IBlockResult)streamCalculator.GetResult()).Collect());
            }
            catch (global::System.Exception ex)
            {
                throw new OcspException(string.Concat((object)"exception processing TBSRequest: ", (object)ex), ex);
            }
            AlgorithmIdentifier sigAlgID = OcspUtilities.GetSigAlgID(algorithm);
            DerSequence         certs    = null;

            if (chain != null && chain.Length > 0)
            {
                Asn1EncodableVector asn1EncodableVector2 = new Asn1EncodableVector();
                try
                {
                    for (int i = 0; i != chain.Length; i++)
                    {
                        asn1EncodableVector2.Add(X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(chain[i].GetEncoded())));
                    }
                }
                catch (IOException val)
                {
                    IOException e2 = val;
                    throw new OcspException("error processing certs", (global::System.Exception)(object) e2);
                }
                catch (CertificateEncodingException e3)
                {
                    throw new OcspException("error encoding certs", e3);
                }
                certs = new DerSequence(asn1EncodableVector2);
            }
            return(new BasicOcspResp(new BasicOcspResponse(responseData, sigAlgID, derBitString, certs)));
        }
Esempio n. 22
0
        public override void PerformTest()
        {
            Asn1Sequence obj = (Asn1Sequence)Asn1Object.FromByteArray(pkcs12);

            Pfx                 bag   = new Pfx(obj);
            ContentInfo         info  = bag.AuthSafe;
            MacData             mData = bag.MacData;
            DigestInfo          dInfo = mData.Mac;
            AlgorithmIdentifier algId = dInfo.AlgorithmID;

            byte[] salt    = mData.GetSalt();
            int    itCount = mData.IterationCount.IntValue;

            byte[]            octets   = ((Asn1OctetString)info.Content).GetOctets();
            AuthenticatedSafe authSafe = new AuthenticatedSafe(
                (Asn1Sequence)Asn1Object.FromByteArray(octets));

            ContentInfo[] c = authSafe.GetContentInfo();

            //
            // private key section
            //
            if (!c[0].ContentType.Equals(PkcsObjectIdentifiers.Data))
            {
                Fail("Failed comparison data test");
            }

            octets = ((Asn1OctetString)c[0].Content).GetOctets();
            Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(octets);

            SafeBag b = new SafeBag((Asn1Sequence)seq[0]);

            if (!b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag))
            {
                Fail("Failed comparison shroudedKeyBag test");
            }

            EncryptedPrivateKeyInfo encInfo = EncryptedPrivateKeyInfo.GetInstance(b.BagValue);

            encInfo = new EncryptedPrivateKeyInfo(encInfo.EncryptionAlgorithm, encInfo.GetEncryptedData());

            b = new SafeBag(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag, encInfo.ToAsn1Object(), b.BagAttributes);

            byte[] encodedBytes = new DerSequence(b).GetEncoded();

            c[0] = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(encodedBytes));

            //
            // certificates
            //
            if (!c[1].ContentType.Equals(PkcsObjectIdentifiers.EncryptedData))
            {
                Fail("Failed comparison encryptedData test");
            }

            EncryptedData eData = EncryptedData.GetInstance(c[1].Content);

            c[1] = new ContentInfo(PkcsObjectIdentifiers.EncryptedData, eData);

            //
            // create an octet stream to represent the BER encoding of authSafe
            //
            authSafe = new AuthenticatedSafe(c);

            info = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(authSafe.GetEncoded()));

            mData = new MacData(new DigestInfo(algId, dInfo.GetDigest()), salt, itCount);

            bag = new Pfx(info, mData);

            //
            // comparison test
            //
            if (!Arrays.AreEqual(bag.GetEncoded(), pkcs12))
            {
                Fail("Failed comparison test");
            }
        }
Esempio n. 23
0
		private static Asn1Sequence MakeGeneralInfoSeq(
			InfoTypeAndValue[] generalInfos)
		{
			Asn1Sequence genInfoSeq = null;
			if (generalInfos != null)
			{
				Asn1EncodableVector v = new Asn1EncodableVector();
				for (int i = 0; i < generalInfos.Length; ++i)
				{
					v.Add(generalInfos[i]);
				}
				genInfoSeq = new DerSequence(v);
			}
			return genInfoSeq;
		}
        public async Task <bool> LoginSecurity(string id, string pw)
        {
            try
            {
                HttpResponseMessage response = await client.GetAsync(new Uri(Constants.Constants.Url_LoginSecurity));

                if (response.IsSuccessStatusCode)
                {
                    string res = await response.Content.ReadAsStringAsync();

                    string key   = JObject.Parse(res)["publicKey"].ToString();
                    string value = Newtonsoft.Json.JsonConvert.SerializeObject(new { loginId  = id,
                                                                                     loginPwd = pw, storeIdYn = "N" });


                    Asn1Object obj = Asn1Object.FromByteArray(Convert.FromBase64String(key));

                    DerSequence publicKeySequence = (DerSequence)obj;

                    DerBitString encodedPublicKey = (DerBitString)publicKeySequence[1];
                    DerSequence  publicKey        = (DerSequence)Asn1Object.FromByteArray(encodedPublicKey.GetBytes());

                    var modulus  = publicKey[0];
                    var exponent = publicKey[1];

                    RsaKeyParameters keyParameters = new RsaKeyParameters(false, ((DerInteger)modulus).PositiveValue, ((DerInteger)exponent).PositiveValue);
                    RSAParameters    parameters    = DotNetUtilities.ToRSAParameters(keyParameters);


                    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                    rsa.ImportParameters(parameters);

                    //암호화할 문자열을 UFT8인코딩
                    byte[] inbuf = (new UTF8Encoding()).GetBytes(value);

                    //암호화
                    byte[] encbuf = rsa.Encrypt(inbuf, false);

                    //암호화된 문자열 Base64인코딩
                    string token = System.Convert.ToBase64String(encbuf);

                    string content = Newtonsoft.Json.JsonConvert.SerializeObject(new
                    {
                        loginToken     = token,
                        redirectUrl    = "",
                        redirectTabUrl = "",
                    });

                    HttpResponseMessage response2 = await client.PostAsync(new Uri(Constants.Constants.Url_LoginConfirm),
                                                                           new StringContent(content, Encoding.UTF8, "application/json"));

                    try
                    {
                        if (response2.IsSuccessStatusCode)
                        {
                            string res2 = await response2.Content.ReadAsStringAsync();

                            if (JObject.Parse(res2)["errorCount"].ToString() == "0")
                            {
                                Uri uri = new Uri("https://klas.kw.ac.kr");
                                IEnumerable <Cookie> responseCookies = cookies.GetCookies(uri).Cast <Cookie>();

                                CookieContainer cookieContainer = new CookieContainer();

                                foreach (Cookie cookie in responseCookies)
                                {
                                    Console.WriteLine(cookie.Name + ": " + cookie.Value);
                                    cookieContainer.Add(cookie);
                                }

                                UserInfo.CookieContainer = cookieContainer;


                                return(true);
                            }
                            else
                            {
                                return(false);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(@"\tERROR {0}", e.Message);
                        return(false);
                    }
                }
            } catch (Exception e)
            {
                Debug.WriteLine(@"\tERROR {0}", e.Message);
                return(false);
            }
            return(false);
        }
Esempio n. 25
0
        /// <summary>
        /// Generates the certificate.
        /// </summary>
        /// <param name="subjectName">Name of the subject.</param>
        /// <param name="issuerName">Name of the issuer.</param>
        /// <param name="validFrom">The valid from.</param>
        /// <param name="validTo">The valid to.</param>
        /// <param name="keyStrength">The key strength.</param>
        /// <param name="signatureAlgorithm">The signature algorithm.</param>
        /// <param name="issuerPrivateKey">The issuer private key.</param>
        /// <param name="hostName">The host name</param>
        /// <returns>X509Certificate2 instance.</returns>
        /// <exception cref="PemException">Malformed sequence in RSA private key</exception>
        private static X509Certificate2 GenerateCertificate(string hostName,
                                                            string subjectName,
                                                            string issuerName, DateTime validFrom,
                                                            DateTime validTo, int keyStrength       = 2048,
                                                            string signatureAlgorithm               = "SHA256WithRSA",
                                                            AsymmetricKeyParameter issuerPrivateKey = null)
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var secureRandom    = new SecureRandom(randomGenerator);

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

            // Serial Number
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), secureRandom);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            var subjectDn = new X509Name(subjectName);
            var issuerDn  = new X509Name(issuerName);

            certificateGenerator.SetIssuerDN(issuerDn);
            certificateGenerator.SetSubjectDN(subjectDn);

            certificateGenerator.SetNotBefore(validFrom);
            certificateGenerator.SetNotAfter(validTo);

            if (hostName != null)
            {
                //add subject alternative names
                var subjectAlternativeNames = new Asn1Encodable[] { new GeneralName(GeneralName.DnsName, hostName), };

                var subjectAlternativeNamesExtension = new DerSequence(subjectAlternativeNames);
                certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName.Id, false, subjectAlternativeNamesExtension);
            }
            // Subject Public Key
            var keyGenerationParameters = new KeyGenerationParameters(secureRandom, keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

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

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Set certificate intended purposes to only Server Authentication
            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id, false, new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth));

            var signatureFactory = new Asn1SignatureFactory(signatureAlgorithm, issuerPrivateKey ?? subjectKeyPair.Private, secureRandom);

            // Self-sign the certificate
            var certificate = certificateGenerator.Generate(signatureFactory);

            // Corresponding private key
            var privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);

            var seq = (Asn1Sequence)Asn1Object.FromByteArray(privateKeyInfo.ParsePrivateKey().GetDerEncoded());

            if (seq.Count != 9)
            {
                throw new PemException("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);

            var x509Certificate = WithPrivateKey(certificate, rsaparams);

            x509Certificate.FriendlyName = subjectName;
            return(x509Certificate);
        }
        /// <summary>
        ///     Generates the certificate.
        /// </summary>
        /// <param name="subjectName">Name of the subject.</param>
        /// <param name="issuerName">Name of the issuer.</param>
        /// <param name="validFrom">The valid from.</param>
        /// <param name="validTo">The valid to.</param>
        /// <param name="keyStrength">The key strength.</param>
        /// <param name="signatureAlgorithm">The signature algorithm.</param>
        /// <param name="issuerPrivateKey">The issuer private key.</param>
        /// <param name="hostName">The host name</param>
        /// <returns>X509Certificate2 instance.</returns>
        /// <exception cref="PemException">Malformed sequence in RSA private key</exception>
        private static X509Certificate2 generateCertificate(string hostName,
                                                            string subjectName,
                                                            string issuerName, System.DateTime validFrom,
                                                            System.DateTime validTo, int keyStrength = 2048,
                                                            string signatureAlgorithm = "SHA256WithRSA",
                                                            AsymmetricKeyParameter issuerPrivateKey = null)
        {
            // Generating Random Numbers
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom             secureRandom    = new SecureRandom(randomGenerator);

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

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

            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            X509Name subjectDn = new X509Name(subjectName);
            X509Name issuerDn  = new X509Name(issuerName);

            certificateGenerator.SetIssuerDN(issuerDn);
            certificateGenerator.SetSubjectDN(subjectDn);

            certificateGenerator.SetNotBefore(validFrom);
            certificateGenerator.SetNotAfter(validTo);

            if (hostName != null)
            {
                // add subject alternative names
                Asn1Encodable[] subjectAlternativeNames = new Asn1Encodable[] { new GeneralName(GeneralName.DnsName, hostName) };

                DerSequence subjectAlternativeNamesExtension = new DerSequence(subjectAlternativeNames);
                certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName.Id, false,
                                                  subjectAlternativeNamesExtension);
            }

            // Subject Public Key
            KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(secureRandom, keyStrength);
            RsaKeyPairGenerator     keyPairGenerator        = new RsaKeyPairGenerator();

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

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Set certificate intended purposes to only Server Authentication
            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id, false,
                                              new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth));

            if (issuerPrivateKey == null)
            {
                certificateGenerator.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(true));
            }

            Asn1SignatureFactory signatureFactory = new Asn1SignatureFactory(signatureAlgorithm,
                                                                             issuerPrivateKey ?? subjectKeyPair.Private, secureRandom);

            // Self-sign the certificate
            X509Certificate certificate = certificateGenerator.Generate(signatureFactory);

            // Corresponding private key
            PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);

            Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(privateKeyInfo.ParsePrivateKey().GetDerEncoded());

            if (seq.Count != 9)
            {
                throw new PemException("Malformed sequence in RSA private key");
            }

            RsaPrivateKeyStructure     rsa       = RsaPrivateKeyStructure.GetInstance(seq);
            RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent,
                                                                                  rsa.Prime1, rsa.Prime2, rsa.Exponent1,
                                                                                  rsa.Exponent2, rsa.Coefficient);

#if NET45
            // Set private key onto certificate instance
            X509Certificate2 x509Certificate = new X509Certificate2(certificate.GetEncoded());
            x509Certificate.PrivateKey = DotNetUtilities.ToRSA(rsaparams);
#else
            X509Certificate2 x509Certificate = withPrivateKey(certificate, rsaparams);
            if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                x509Certificate.FriendlyName = subjectName;
            }
#endif

            doNotSetFriendlyName = false;

            if (!doNotSetFriendlyName)
            {
                try
                {
                    x509Certificate.FriendlyName = ProxyConstants.CNRemoverRegex.Replace(subjectName, string.Empty);
                }
                catch (System.PlatformNotSupportedException)
                {
                    doNotSetFriendlyName = true;
                }
            }

            return(x509Certificate);
        }
Esempio n. 27
0
        public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random)
        {
            byte[] keyBytes = contentEncryptionKey.GetKey();

            AsymmetricKeyParameter senderPublicKey     = senderKeyPair.Public;
            ICipherParameters      senderPrivateParams = senderKeyPair.Private;


            OriginatorIdentifierOrKey originator;

            try
            {
                originator = new OriginatorIdentifierOrKey(
                    CreateOriginatorPublicKey(senderPublicKey));
            }
            catch (IOException e)
            {
                throw new InvalidKeyException("cannot extract originator public key: " + e);
            }


            Asn1OctetString ukm = null;

            if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
            {
                try
                {
                    IAsymmetricCipherKeyPairGenerator ephemKPG =
                        GeneratorUtilities.GetKeyPairGenerator(keyAgreementOID);
                    ephemKPG.Init(
                        ((ECPublicKeyParameters)senderPublicKey).CreateKeyGenerationParameters(random));

                    AsymmetricCipherKeyPair ephemKP = ephemKPG.GenerateKeyPair();

                    ukm = new DerOctetString(
                        new MQVuserKeyingMaterial(
                            CreateOriginatorPublicKey(ephemKP.Public), null));

                    senderPrivateParams = new MqvPrivateParameters(
                        (ECPrivateKeyParameters)senderPrivateParams,
                        (ECPrivateKeyParameters)ephemKP.Private,
                        (ECPublicKeyParameters)ephemKP.Public);
                }
                catch (IOException e)
                {
                    throw new InvalidKeyException("cannot extract MQV ephemeral public key: " + e);
                }
                catch (SecurityUtilityException e)
                {
                    throw new InvalidKeyException("cannot determine MQV ephemeral key pair parameters from public key: " + e);
                }
            }


            DerSequence paramSeq = new DerSequence(
                keyEncryptionOID,
                DerNull.Instance);
            AlgorithmIdentifier keyEncAlg = new AlgorithmIdentifier(keyAgreementOID, paramSeq);


            Asn1EncodableVector recipientEncryptedKeys = new Asn1EncodableVector();

            foreach (X509Certificate recipientCert in recipientCerts)
            {
                TbsCertificateStructure tbsCert;
                try
                {
                    tbsCert = TbsCertificateStructure.GetInstance(
                        Asn1Object.FromByteArray(recipientCert.GetTbsCertificate()));
                }
                catch (Exception)
                {
                    throw new ArgumentException("can't extract TBS structure from certificate");
                }

                // TODO Should there be a SubjectKeyIdentifier-based alternative?
                IssuerAndSerialNumber issuerSerial = new IssuerAndSerialNumber(
                    tbsCert.Issuer, tbsCert.SerialNumber.Value);
                KeyAgreeRecipientIdentifier karid = new KeyAgreeRecipientIdentifier(issuerSerial);

                ICipherParameters recipientPublicParams = recipientCert.GetPublicKey();
                if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
                {
                    recipientPublicParams = new MqvPublicParameters(
                        (ECPublicKeyParameters)recipientPublicParams,
                        (ECPublicKeyParameters)recipientPublicParams);
                }

                // Use key agreement to choose a wrap key for this recipient
                IBasicAgreement keyAgreement = AgreementUtilities.GetBasicAgreementWithKdf(
                    keyAgreementOID, keyEncryptionOID.Id);
                keyAgreement.Init(new ParametersWithRandom(senderPrivateParams, random));
                BigInteger agreedValue = keyAgreement.CalculateAgreement(recipientPublicParams);

                int          keyEncryptionKeySize  = GeneratorUtilities.GetDefaultKeySize(keyEncryptionOID) / 8;
                byte[]       keyEncryptionKeyBytes = X9IntegerConverter.IntegerToBytes(agreedValue, keyEncryptionKeySize);
                KeyParameter keyEncryptionKey      = ParameterUtilities.CreateKeyParameter(
                    keyEncryptionOID, keyEncryptionKeyBytes);

                // Wrap the content encryption key with the agreement key
                IWrapper keyWrapper = Helper.CreateWrapper(keyEncryptionOID.Id);
                keyWrapper.Init(true, new ParametersWithRandom(keyEncryptionKey, random));
                byte[] encryptedKeyBytes = keyWrapper.Wrap(keyBytes, 0, keyBytes.Length);

                Asn1OctetString encryptedKey = new DerOctetString(encryptedKeyBytes);

                recipientEncryptedKeys.Add(new RecipientEncryptedKey(karid, encryptedKey));
            }

            return(new RecipientInfo(new KeyAgreeRecipientInfo(originator, ukm, keyEncAlg,
                                                               new DerSequence(recipientEncryptedKeys))));
        }
Esempio n. 28
0
        public virtual int GenerateBytes(byte[] outBytes, int outOff, int len)
        {
            if ((outBytes.Length - len) < outOff)
            {
                throw new DataLengthException("output buffer too small");
            }

            long oBytes = len;
            int  outLen = digest.GetDigestSize();

            //
            // this is at odds with the standard implementation, the
            // maximum value should be hBits * (2^32 - 1) where hBits
            // is the digest output size in bits. We can't have an
            // array with a long index at the moment...
            //
            if (oBytes > ((2L << 32) - 1))
            {
                throw new ArgumentException("Output length too large");
            }

            int cThreshold = (int)((oBytes + outLen - 1) / outLen);

            byte[] dig = new byte[digest.GetDigestSize()];

            uint counter = 1;

            for (int i = 0; i < cThreshold; i++)
            {
                digest.BlockUpdate(z, 0, z.Length);

                // KeySpecificInfo
                DerSequence keyInfo = new DerSequence(
                    algorithm,
                    new DerOctetString(Pack.UInt32_To_BE(counter)));

                // OtherInfo
                Asn1EncodableVector v1 = new Asn1EncodableVector(keyInfo);

                if (partyAInfo != null)
                {
                    v1.Add(new DerTaggedObject(true, 0, new DerOctetString(partyAInfo)));
                }

                v1.Add(new DerTaggedObject(true, 2, new DerOctetString(Pack.UInt32_To_BE((uint)keySize))));

                byte[] other = new DerSequence(v1).GetDerEncoded();

                digest.BlockUpdate(other, 0, other.Length);

                digest.DoFinal(dig, 0);

                if (len > outLen)
                {
                    Array.Copy(dig, 0, outBytes, outOff, outLen);
                    outOff += outLen;
                    len    -= outLen;
                }
                else
                {
                    Array.Copy(dig, 0, outBytes, outOff, len);
                }

                counter++;
            }

            digest.Reset();

            return((int)oBytes);
        }
Esempio n. 29
0
        /**
         * Gets the bytes for the PKCS7SignedData object. Optionally the authenticatedAttributes
         * in the signerInfo can also be set, OR a time-stamp-authority client
         * may be provided.
         * @param secondDigest the digest in the authenticatedAttributes
         * @param signingTime the signing time in the authenticatedAttributes
         * @param tsaClient TSAClient - null or an optional time stamp authority client
         * @return byte[] the bytes for the PKCS7SignedData object
         * @since   2.1.6
         */
        public byte[] GetEncodedPKCS7(byte[] secondDigest, DateTime signingTime, ITSAClient tsaClient, byte[] ocsp, ICollection <byte[]> crlBytes, CryptoStandard sigtype)
        {
            if (externalDigest != null)
            {
                digest = externalDigest;
                if (RSAdata != null)
                {
                    RSAdata = externalRSAdata;
                }
            }
            else if (externalRSAdata != null && RSAdata != null)
            {
                RSAdata = externalRSAdata;
                sig.BlockUpdate(RSAdata, 0, RSAdata.Length);
                digest = sig.GenerateSignature();
            }
            else
            {
                if (RSAdata != null)
                {
                    RSAdata = new byte[messageDigest.GetDigestSize()];
                    messageDigest.DoFinal(RSAdata, 0);
                    sig.BlockUpdate(RSAdata, 0, RSAdata.Length);
                }
                digest = sig.GenerateSignature();
            }

            // Create the set of Hash algorithms
            Asn1EncodableVector digestAlgorithms = new Asn1EncodableVector();

            foreach (string dal in digestalgos.Keys)
            {
                Asn1EncodableVector algos = new Asn1EncodableVector();
                algos.Add(new DerObjectIdentifier(dal));
                algos.Add(DerNull.Instance);
                digestAlgorithms.Add(new DerSequence(algos));
            }

            // Create the contentInfo.
            Asn1EncodableVector v = new Asn1EncodableVector();

            v.Add(new DerObjectIdentifier(SecurityIDs.ID_PKCS7_DATA));
            if (RSAdata != null)
            {
                v.Add(new DerTaggedObject(0, new DerOctetString(RSAdata)));
            }
            DerSequence contentinfo = new DerSequence(v);

            // Get all the certificates
            //
            v = new Asn1EncodableVector();
            foreach (X509Certificate xcert in certs)
            {
                Asn1InputStream tempstream = new Asn1InputStream(new MemoryStream(xcert.GetEncoded()));
                v.Add(tempstream.ReadObject());
            }

            DerSet dercertificates = new DerSet(v);

            // Create signerinfo structure.
            //
            Asn1EncodableVector signerinfo = new Asn1EncodableVector();

            // Add the signerInfo version
            //
            signerinfo.Add(new DerInteger(signerversion));

            v = new Asn1EncodableVector();
            v.Add(CertificateInfo.GetIssuer(signCert.GetTbsCertificate()));
            v.Add(new DerInteger(signCert.SerialNumber));
            signerinfo.Add(new DerSequence(v));

            // Add the digestAlgorithm
            v = new Asn1EncodableVector();
            v.Add(new DerObjectIdentifier(digestAlgorithmOid));
            v.Add(DerNull.Instance);
            signerinfo.Add(new DerSequence(v));

            // add the authenticated attribute if present
            if (secondDigest != null /*&& signingTime != null*/)
            {
                signerinfo.Add(new DerTaggedObject(false, 0, GetAuthenticatedAttributeSet(secondDigest, signingTime, ocsp, crlBytes, sigtype)));
            }
            // Add the digestEncryptionAlgorithm
            v = new Asn1EncodableVector();
            v.Add(new DerObjectIdentifier(digestEncryptionAlgorithmOid));
            v.Add(DerNull.Instance);
            signerinfo.Add(new DerSequence(v));

            // Add the digest
            signerinfo.Add(new DerOctetString(digest));

            // When requested, go get and add the timestamp. May throw an exception.
            // Added by Martin Brunecky, 07/12/2007 folowing Aiken Sam, 2006-11-15
            // Sam found Adobe expects time-stamped SHA1-1 of the encrypted digest
            if (tsaClient != null)
            {
                byte[] tsImprint = DigestAlgorithms.Digest(tsaClient.GetMessageDigest(), digest);
                byte[] tsToken   = tsaClient.GetTimeStampToken(tsImprint);
                if (tsToken != null)
                {
                    Asn1EncodableVector unauthAttributes = BuildUnauthenticatedAttributes(tsToken);
                    if (unauthAttributes != null)
                    {
                        signerinfo.Add(new DerTaggedObject(false, 1, new DerSet(unauthAttributes)));
                    }
                }
            }

            // Finally build the body out of all the components above
            Asn1EncodableVector body = new Asn1EncodableVector();

            body.Add(new DerInteger(version));
            body.Add(new DerSet(digestAlgorithms));
            body.Add(contentinfo);
            body.Add(new DerTaggedObject(false, 0, dercertificates));

            // Only allow one signerInfo
            body.Add(new DerSet(new DerSequence(signerinfo)));

            // Now we have the body, wrap it in it's PKCS7Signed shell
            // and return it
            //
            Asn1EncodableVector whole = new Asn1EncodableVector();

            whole.Add(new DerObjectIdentifier(SecurityIDs.ID_PKCS7_SIGNED_DATA));
            whole.Add(new DerTaggedObject(0, new DerSequence(body)));

            MemoryStream bOut = new MemoryStream();

            Asn1OutputStream dout = new Asn1OutputStream(bOut);

            dout.WriteObject(new DerSequence(whole));
            dout.Close();

            return(bOut.ToArray());
        }
Esempio n. 30
0
        public void TestSignRequest()
        {
            var agentClient = new TestAgentClient();
            var data        = Encoding.UTF8.GetBytes("Data to be signed");

            foreach (var key in allKeys)
            {
                agentClient.Agent.AddKey(key);
                var signature = agentClient.SignRequest(key, data);
                switch (key.Version)
                {
                case SshVersion.SSH1:
                    using (MD5 md5 = MD5.Create()) {
                        var md5Buffer = new byte[48];
                        data.CopyTo(md5Buffer, 0);
                        agentClient.SessionId.CopyTo(md5Buffer, 32);
                        var expctedSignature = md5.ComputeHash(md5Buffer);
                        Assert.That(signature, Is.EqualTo(expctedSignature));
                    }
                    break;

                case SshVersion.SSH2:
                    BlobParser signatureParser = new BlobParser(signature);
                    var        algorithm       = signatureParser.ReadString();
                    Assert.That(algorithm, Is.EqualTo(key.Algorithm.GetIdentifierString()));
                    signature = signatureParser.ReadBlob();
                    if (key.Algorithm == PublicKeyAlgorithm.SSH_RSA)
                    {
                        Assert.That(signature.Length == key.Size / 8);
                    }
                    else if (key.Algorithm == PublicKeyAlgorithm.SSH_DSS)
                    {
                        Assert.That(signature.Length, Is.EqualTo(40));
                        var r   = new BigInteger(1, signature, 0, 20);
                        var s   = new BigInteger(1, signature, 20, 20);
                        var seq = new DerSequence(new DerInteger(r), new DerInteger(s));
                        signature = seq.GetDerEncoded();
                    }
                    else if (key.Algorithm == PublicKeyAlgorithm.ECDSA_SHA2_NISTP256 ||
                             key.Algorithm == PublicKeyAlgorithm.ECDSA_SHA2_NISTP384 ||
                             key.Algorithm == PublicKeyAlgorithm.ECDSA_SHA2_NISTP521)
                    {
                        Assert.That(signature.Length, Is.AtLeast(key.Size / 4 + 8));
                        Assert.That(signature.Length, Is.AtMost(key.Size / 4 + 10));
                        BlobParser parser = new BlobParser(signature);
                        var        r      = new BigInteger(parser.ReadBlob());
                        var        s      = new BigInteger(parser.ReadBlob());
                        var        seq    = new DerSequence(new DerInteger(r), new DerInteger(s));
                        signature = seq.GetDerEncoded();
                    }
                    var signer = key.GetSigner();
                    signer.Init(false, key.GetPublicKeyParameters());
                    signer.BlockUpdate(data, 0, data.Length);
                    var valid = signer.VerifySignature(signature);
                    Assert.That(valid, Is.True);
                    break;

                default:
                    Assert.Fail("Unexpected Ssh Version");
                    break;
                }
            }
        }
Esempio n. 31
0
        static void Main(string[] args)
        {
            PolicyInformation[] certPolicies = new PolicyInformation[2];
            certPolicies[0] = new PolicyInformation(new DerObjectIdentifier("2.16.840.1.101.2.1.11.5"));
            certPolicies[1] = new PolicyInformation(new DerObjectIdentifier("2.16.840.1.101.2.1.11.18"));

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

            certificateGenerator.SetSerialNumber(serialNumber);
            // sig alg

            const string signatureAlgorithm = "SHA1WithRSA";

            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);

            // Subjects
            //   Time x = new Time();
            var subjectDN = new X509Name("CN=localhost, O=Arsslensoft, C=TN,surname=Idadi,givenname=Arsslen, uniqueidentifier=15002060,businesscategory=Production,initials=Hello, gender=male, placeofbirth=El Manar, pseudonym=Arsslinko, postaladdress=2076, countryofcitizenship=TN, countryofresidence=TN,telephonenumber=53299093");
            var issuerDN  = subjectDN;

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Validity
            var notBefore = DateTime.UtcNow.Date.Subtract(new TimeSpan(5, 0, 0));
            var notAfter  = notBefore.AddYears(2);

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

            // PKEY
            const int strength = 512;
            var       keyGenerationParameters = new KeyGenerationParameters(random, strength);

            //  var x=    new Al.Security.Crypto.Generators.DsaKeyPairGenerator();
            // X9ECParameters ecP = NistNamedCurves.GetByName("B-571");
            // ECDomainParameters ecSpec = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed());
            // ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator("ECDSA");
            // //ECPA par = new DsaParametersGenerator();
            // //par.Init(2048, 100, random);
            // //ECKeyGenerationParameters pa = new ECKeyGenerationParameters(random, par.GenerateParameters());
            ////  var keyPairGenerator = new DHKeyPairGenerator();
            //  //DsaParametersGenerator par = new DsaParametersGenerator();
            //  //par.Init(2048, 100, random);
            //  //DsaKeyGenerationParameters pa = new DsaKeyGenerationParameters(random, par.GenerateParameters());
            // // keyPairGenerator.Init(pa);
            // keyPairGenerator.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom()));
            //var keyPairGenerator = new DsaKeyPairGenerator();
            //DsaParametersGenerator par = new DsaParametersGenerator();
            //par.Init(1024, 100, random);
            //DsaKeyGenerationParameters pa = new DsaKeyGenerationParameters(random, par.GenerateParameters());
            //keyPairGenerator.Init(pa);
            //   KeyPair = keyPairGenerator.GenerateKeyPair();

            var keyPairGenerator = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            StreamReader            str     = new StreamReader("D:\\test.key");
            PemReader               pem     = new PemReader(str);
            AsymmetricCipherKeyPair keypair = (AsymmetricCipherKeyPair)pem.ReadObject();
            var subjectKeyPair = keypair;

            str.Close();
            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // ext
            X509Extensions

            certificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false,
                                              new SubjectKeyIdentifierStructure(subjectKeyPair.Public));

            certificateGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(subjectKeyPair.Public));
            certificateGenerator.AddExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(false));
            // key usage
            certificateGenerator.AddExtension(
                X509Extensions.KeyUsage,
                true,
                new KeyUsage(KeyUsage.KeyAgreement | KeyUsage.DataEncipherment | KeyUsage.DigitalSignature));
            // extended key usage
            var usages = new[] { KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPClientAuth };
            ExtendedKeyUsage extendedKeyUsage = new ExtendedKeyUsage(usages);

            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, false, extendedKeyUsage);
            // Test Policy

            DerSequence seq = CreatePolicyInformationsSequence("http://www.arsslensoft.com", "Arsslensoft", "1.3.6.1.4.1.23823.1.1.1", "Test Notice");

            //  certificateGenerator.AddExtension(X509Extensions.CertificatePolicies, false, new DerSequence(certPolicies));

            // Authority access
            List <GeneralSubtree> ees = new List <GeneralSubtree>();

            ees.Add(new GeneralSubtree(new GeneralName(GeneralName.UniformResourceIdentifier, "http://www.google.com")));
            certificateGenerator.AddExtension(X509Extensions.NameConstraints, true, new NameConstraints(null, ees));

            certificateGenerator.AddExtension(X509Extensions.NetscapeComment, true, new DerVisibleString("NS COMMENT"));
            certificateGenerator.AddExtension(X509Extensions.NetscapeBaseUrl, true, new DerIA5String("http://www.google.com"));
            certificateGenerator.AddExtension(X509Extensions.InhibitAnyPolicy, true, new DerInteger(12));
// Policy constraints
            byte inhibit   = 12;
            byte explicitc = 12;

            //   certificateGenerator.AddExtension(X509Extensions.PolicyConstraints, false, new DerOctetSequence(new byte[] { 128, 1, explicitc, 129, 1, inhibit }));
            certificateGenerator.AddExtension(X509Extensions.NetscapeCertUsage, false, new KeyUsage(KeyUsage.KeyAgreement));

            certificateGenerator.AddExtension(X509Extensions.AuthorityInfoAccess, false, CreateAuthorityAccessInformationSequence("http://www.arsslensoft.com", null));
            // Subhect Issuer Alternative name
            GeneralName  altName        = new GeneralName(GeneralName.DnsName, "localhost");
            GeneralNames subjectAltName = new GeneralNames(altName);

            certificateGenerator.AddExtension(X509Extensions.IssuerAlternativeName, false, subjectAltName);
            certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false, subjectAltName);
            //   certificateGenerator.AddExtension(new DerObjectIdentifier("2.16.840.1.11730.29.53"), false, subjectAltName);
            //

            GeneralNames s;

            //CRL Distribution Points
            DistributionPointName distPointOne = new DistributionPointName(new GeneralNames(
                                                                               new GeneralName(GeneralName.UniformResourceIdentifier, "http://crl.somewebsite.com/master.crl")));
            GeneralNames gns = new GeneralNames(new GeneralName[] {
                new GeneralName(GeneralName.UniformResourceIdentifier, "ldap://crl.somewebsite.com/cn%3dSecureCA%2cou%3dPKI%2co%3dCyberdyne%2cc%3dUS?certificaterevocationlist;binary"), new GeneralName(GeneralName.Rfc822Name, "Arslen")
            });
            DistributionPointName distPointTwo = new DistributionPointName(gns);

            DistributionPoint[] distPoints = new DistributionPoint[2];
            distPoints[0] = new DistributionPoint(distPointOne, null, null);
            distPoints[1] = new DistributionPoint(distPointTwo, null, gns);

            IssuingDistributionPoint iss = new IssuingDistributionPoint(distPointOne, false, true, null, false, false);

            certificateGenerator.AddExtension(X509Extensions.IssuingDistributionPoint, false, iss);

            certificateGenerator.AddExtension(X509Extensions.CrlDistributionPoints, false, new CrlDistPoint(distPoints));

            // Biometric
            Asn1EncodableVector v = new Asn1EncodableVector();

            BiometricData bdat = new BiometricData(new TypeOfBiometricData(TypeOfBiometricData.HandwrittenSignature), new AlgorithmIdentifier(new DerObjectIdentifier("1.3.14.3.2.26")), new DerOctetString(new byte[] { 169, 74, 143, 229, 204, 177, 155, 166, 28, 76, 8, 115, 211, 145, 233, 135, 152, 47, 187, 211 }), new DerIA5String("http://www.google.com"));

            v.Add(bdat);
            v.Add(new BiometricData(new TypeOfBiometricData(TypeOfBiometricData.HandwrittenSignature), new AlgorithmIdentifier(new DerObjectIdentifier("1.3.14.3.2.26")), new DerOctetString(new byte[] { 169, 74, 143, 229, 204, 177, 155, 166, 28, 76, 8, 115, 211, 145, 233, 135, 152, 47, 187, 211 }), new DerIA5String("http://www.google.co")));
            certificateGenerator.AddExtension(X509Extensions.BiometricInfo, false, new DerSequenceOf(v));

            QCStatement st = new QCStatement(Rfc3739QCObjectIdentifiers.IdQcs);

            certificateGenerator.AddExtension(X509Extensions.QCStatements, false, st);
            //Al.Security.Pkcs.Pkcs10CertificationRequest c = new Al.Security.Pkcs.Pkcs10CertificationRequest(
            //certificateGenerator.AddExtension(X509Extensions.ReasonCode, false, ce);
            // test done
            certificateGenerator.AddExtension(X509Extensions.SubjectInfoAccess, false, CreateAuthorityAccessInformationSequence("http://www.arsslensoft.com", null));
            //// 2
            //TargetInformation ti = new Al.Security.Asn1.X509.TargetInformation(new Target[] { new Target(Target.Choice.Name, new GeneralName(GeneralName.UniformResourceIdentifier, "http://www.go.com")) });
            //certificateGenerator.AddExtension(X509Extensions.TargetInformation, false, new DerSequence(ti));
            // 3
            PrivateKeyUsagePeriod kup = new PrivateKeyUsagePeriod(DateTime.Now, DateTime.Now.AddYears(2));

            certificateGenerator.AddExtension(X509Extensions.PrivateKeyUsagePeriod, false, new DerSequence(kup));


            //generate
            var issuerKeyPair = subjectKeyPair;
            var certificate   = certificateGenerator.Generate(issuerKeyPair.Private, random);


            StreamWriter wstr      = new StreamWriter(Path.ChangeExtension("D:\\test.crt", ".pem"), false);
            PemWriter    pemWriter = new PemWriter(wstr);

            pemWriter.WriteObject(certificate);
            pemWriter.WriteObject(issuerKeyPair.Private);

            wstr.Flush();
            wstr.Close();

            //   System.Security.Cryptography.X509Certificates.X509Certificate x509_ = DotNetUtilities.ToX509Certificate(certificate.CertificateStructure);

            //File.WriteAllBytes(@"D:\\test.crt",   x509_.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs12));
        }
        public static CngKey Import(Byte[] blob,
                                    Int32 offset = 0)
        {
            Boolean isPrivateKey = false;
            Byte    keyLength    = 0;

            Byte[] keyCurveX = null, keyCurveY = null, keyScalar = null;
            Byte[] inBlob    = blob;

            // Apply offset to incoming data.
            if (offset > 0)
            {
                var blobLength = blob.Length - (offset);
                inBlob = new Byte[blobLength];
                Array.Copy(blob, offset, inBlob, 0, blobLength);
            }
            System.IO.File.WriteAllBytes("Key.key", inBlob);

            DerSequence der = (DerSequence)DerSequence.FromByteArray(inBlob);

            try {             /*to read directly*/
                isPrivateKey = ((DerBitString)der[0]).IntValue != 0;
            } catch {
                der = (DerSequence)DerSequence.FromByteArray(((DerOctetString)der[1]).GetOctets());
                System.IO.File.WriteAllBytes("KeyDer.key", der.GetEncoded());
            }

            // Read Data from Key.
            isPrivateKey = ((DerBitString)der[0]).IntValue != 0;
            keyLength    = (Byte)((DerInteger)der[1]).PositiveValue.IntValue;
            keyCurveX    = ((DerInteger)der[2]).PositiveValue.ToByteArrayUnsigned();
            keyCurveY    = ((DerInteger)der[3]).PositiveValue.ToByteArrayUnsigned();
            if (isPrivateKey)
            {
                keyScalar = ((DerInteger)der[4]).PositiveValue.ToByteArrayUnsigned();
            }

            // Validate data.
            if (keyLength == 0)
            {
                throw new IndexOutOfRangeException("Length of key is 0.");
            }
            if (keyCurveX == null || keyCurveY == null)
            {
                throw new IndexOutOfRangeException("Key Curve is not set.");
            }

            // Construct a readable key out of this data.
            Byte[] newBlob = new Byte[8 + (keyLength * (2 + (isPrivateKey ? 1 : 0)))];

            // Write Key Header for ECCPrivateBlob or ECCPublicBlob.
            newBlob[0]  = (Byte)0x45;            // E
            newBlob[1]  = (Byte)0x43;            // C
            newBlob[2]  = (Byte)0x4B;            // K
            newBlob[3]  = (Byte)(keyLength == 32 ? 0x31 : (keyLength == 48 ? 0x33 : (keyLength == 64 ? 0x35 : 0x00)));
            newBlob[3] += (Byte)(isPrivateKey ? 0x01 : 0x00);
            newBlob[4]  = (Byte)keyLength;

            Array.Copy(keyCurveX, 0, newBlob, 8, keyCurveX.Length);
            Array.Copy(keyCurveY, 0, newBlob, 8 + keyLength, keyCurveY.Length);
            if (isPrivateKey)
            {
                Array.Copy(keyScalar, 0, newBlob, 8 + keyLength * 2, keyScalar.Length);
            }

            // Now return a valid Key.
            if (isPrivateKey)
            {
                return(CngKey.Import(newBlob, CngKeyBlobFormat.EccPrivateBlob));
            }
            else
            {
                return(CngKey.Import(newBlob, CngKeyBlobFormat.EccPublicBlob));
            }
        }
Esempio n. 33
0
		public override void PerformTest()
		{
			Asn1Sequence obj = (Asn1Sequence) Asn1Object.FromByteArray(pkcs12);

			Pfx                 bag = new Pfx(obj);
			ContentInfo         info = bag.AuthSafe;
			MacData             mData = bag.MacData;
			DigestInfo          dInfo = mData.Mac;
			AlgorithmIdentifier algId = dInfo.AlgorithmID;
			byte[]              salt = mData.GetSalt();
			int                 itCount = mData.IterationCount.IntValue;

			byte[] octets = ((Asn1OctetString) info.Content).GetOctets();
			AuthenticatedSafe authSafe = new AuthenticatedSafe(
				(Asn1Sequence) Asn1Object.FromByteArray(octets));
			ContentInfo[] c = authSafe.GetContentInfo();

			//
			// private key section
			//
			if (!c[0].ContentType.Equals(PkcsObjectIdentifiers.Data))
			{
				Fail("Failed comparison data test");
			}

			octets = ((Asn1OctetString)c[0].Content).GetOctets();
			Asn1Sequence seq = (Asn1Sequence) Asn1Object.FromByteArray(octets);

			SafeBag b = new SafeBag((Asn1Sequence)seq[0]);
			if (!b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag))
			{
				Fail("Failed comparison shroudedKeyBag test");
			}

			EncryptedPrivateKeyInfo encInfo = EncryptedPrivateKeyInfo.GetInstance(b.BagValue);

			encInfo = new EncryptedPrivateKeyInfo(encInfo.EncryptionAlgorithm, encInfo.GetEncryptedData());

			b = new SafeBag(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag, encInfo.ToAsn1Object(), b.BagAttributes);

			byte[] encodedBytes = new DerSequence(b).GetEncoded();

			c[0] = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(encodedBytes));

			//
			// certificates
			//
			if (!c[1].ContentType.Equals(PkcsObjectIdentifiers.EncryptedData))
			{
				Fail("Failed comparison encryptedData test");
			}

			EncryptedData eData = EncryptedData.GetInstance(c[1].Content);

			c[1] = new ContentInfo(PkcsObjectIdentifiers.EncryptedData, eData);

			//
			// create an octet stream to represent the BER encoding of authSafe
			//
			authSafe = new AuthenticatedSafe(c);

			info = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(authSafe.GetEncoded()));

			mData = new MacData(new DigestInfo(algId, dInfo.GetDigest()), salt, itCount);

			bag = new Pfx(info, mData);

			//
			// comparison test
			//
			if (!Arrays.AreEqual(bag.GetEncoded(), pkcs12))
			{
				Fail("Failed comparison test");
			}
		}
Esempio n. 34
0
        public byte[] GetPrivateKeyBlob(IntPtr context, KeyDerivation derive)
        {
            bool result, shouldFree = false;

            NativeMethods.KeySpec addInfo = 0;

            IntPtr hProv = IntPtr.Zero, hExportKey = IntPtr.Zero,
                   phSessionKey = IntPtr.Zero, userKey = IntPtr.Zero;

            try {
                result = NativeMethods.CryptAcquireCertificatePrivateKey(context, 0, IntPtr.Zero, ref hProv, ref addInfo, ref shouldFree);
                if (!result)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                result = NativeMethods.CryptGetUserKey(hProv, (uint)addInfo, ref userKey);
                if (!result)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                CheckPermission(userKey);

                result = NativeMethods.CryptGenKey(hProv, EphemAlgId, 0, out phSessionKey);
                if (!result)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                uint dhOIDsz = 50;
                var  dhOID   = new byte[dhOIDsz];
                result = NativeMethods.CryptGetKeyParam(phSessionKey, NativeMethods.KP_DHOID, dhOID, ref dhOIDsz, 0);
                if (!result)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
                dhOID = dhOID.Take((int)dhOIDsz - 1).ToArray();
                var dhOIDstr = Encoding.ASCII.GetString(dhOID);

                uint hashOIDsz = 50;
                var  hashOID   = new byte[hashOIDsz];
                result = NativeMethods.CryptGetKeyParam(phSessionKey, NativeMethods.KP_HASHOID, hashOID, ref hashOIDsz, 0);
                if (!result)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
                hashOID = hashOID.Take((int)hashOIDsz - 1).ToArray();
                var hashOIDstr = Encoding.ASCII.GetString(hashOID);

                uint pbdatalen = 0;
                result = NativeMethods.CryptExportKey(phSessionKey, IntPtr.Zero, NativeMethods.PUBLICKEYBLOB, 0, null, ref pbdatalen);
                if (!result)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                SessionKey = new byte[pbdatalen];
                result     = NativeMethods.CryptExportKey(phSessionKey, IntPtr.Zero, NativeMethods.PUBLICKEYBLOB, 0, SessionKey, ref pbdatalen);
                if (!result)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                var blob = new CRYPT_PUBLICKEYBLOB {
                    reserved = 0,
                    bType    = 6,
                    aiKeyAlg = (uint)KeyAlgId,
                    bVersion = 0x20,
                    Magic    = NativeMethods.GR3410_1_MAGIC,
                    BitLen   = PublicKeyLength
                };

                var dhOid   = new DerObjectIdentifier(dhOIDstr);
                var hashOid = new DerObjectIdentifier(hashOIDstr);
                var seq     = new DerSequence(dhOid, hashOid);

                var keyData = seq.GetDerEncoded();
                Array.Resize(ref keyData, 24);

                blob.KeyData1 = BitConverter.ToUInt64(keyData, 0);
                blob.KeyData2 = BitConverter.ToUInt64(keyData, 8);
                blob.KeyData3 = BitConverter.ToUInt64(keyData, 16);

                var blobData = blob.GetBytes();
                var pbdata2  = new byte[BlobLength];
                for (int i = 0; i < KeyOffset; ++i)
                {
                    pbdata2[i] = blobData[i];
                }

                derive.Init(dhOid, hashOid);
                var genkey = derive.GetPublicKeyBytes();

                for (int i = 0, j = KeyOffset; i < genkey.Length; ++i, ++j)
                {
                    pbdata2[j] = genkey[i];
                }

                result = NativeMethods.CryptImportKey(hProv, pbdata2, BlobLength, phSessionKey, 0, ref hExportKey);
                if (!result)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                result = NativeMethods.CryptSetKeyParam(hExportKey, (int)NativeMethods.KP_ALGID, BitConverter.GetBytes((uint)ExportAlgId), 0);
                if (!result)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                uint pkSize = 0;
                result = NativeMethods.CryptExportKey(userKey, hExportKey, NativeMethods.PRIVATEKEYBLOB, 0, null, ref pkSize);
                if (!result)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                var ret = new byte[pkSize];
                result = NativeMethods.CryptExportKey(userKey, hExportKey, NativeMethods.PRIVATEKEYBLOB, 0, ret, ref pkSize);
                if (!result)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                return(ret);
            } catch (Win32Exception e) {
                throw new CryptographicException(e.Message, e);
            } finally {
                if (shouldFree)
                {
                    NativeMethods.CryptReleaseContext(hProv, 0);
                }

                if (hExportKey != IntPtr.Zero)
                {
                    NativeMethods.CryptDestroyKey(hExportKey);
                }

                if (phSessionKey != IntPtr.Zero)
                {
                    NativeMethods.CryptDestroyKey(phSessionKey);
                }

                if (userKey != IntPtr.Zero)
                {
                    NativeMethods.CryptDestroyKey(userKey);
                }
            }
        }
Esempio n. 35
0
        public SelfCertificateDialog(IServiceProvider serviceProvider, CertificatesFeature feature)
            : base(serviceProvider)
        {
            InitializeComponent();
            cbStore.SelectedIndex   = 0;
            cbLength.SelectedIndex  = 3;
            cbHashing.SelectedIndex = 1;
            txtCommonName.Text      = Environment.MachineName;
            dtpFrom.Value           = DateTime.Now;
            dtpTo.Value             = dtpFrom.Value.AddYears(1);

            if (Environment.OSVersion.Version < Version.Parse("6.2"))
            {
                // IMPORTANT: WebHosting store is available since Windows 8.
                cbStore.Enabled = false;
            }

            if (!Helper.IsRunningOnMono())
            {
                NativeMethods.TryAddShieldToButton(btnOK);
            }

            var container = new CompositeDisposable();

            FormClosed += (sender, args) => container.Dispose();

            container.Add(
                Observable.FromEventPattern <EventArgs>(txtName, "TextChanged")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                btnOK.Enabled = !string.IsNullOrWhiteSpace(txtName.Text);
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnOK, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                var names = txtCommonName.Text;
                if (string.IsNullOrWhiteSpace(names))
                {
                    ShowMessage("DNS names cannot be empty.", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                    return;
                }

                var dnsNames = names.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(item => item.Trim()).ToArray();
                if (dnsNames.Length == 0)
                {
                    ShowMessage("DNS names cannot be empty.", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                    return;
                }

                // Generate certificate
                string defaultIssuer  = string.Format("CN={0}", dnsNames[0]);
                string defaultSubject = defaultIssuer;

                string subject = defaultSubject;
                string issuer  = defaultIssuer;

                if (subject == null)
                {
                    throw new Exception("Missing Subject Name");
                }

                DateTime notBefore = dtpFrom.Value;
                DateTime notAfter  = dtpTo.Value;

                var random = new SecureRandom(new CryptoApiRandomGenerator());
                var kpgen  = new RsaKeyPairGenerator();
                kpgen.Init(new KeyGenerationParameters(random, int.Parse(cbLength.Text)));
                var cerKp = kpgen.GenerateKeyPair();

                X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

                var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random);
                certGen.SetSerialNumber(serialNumber);
                certGen.SetIssuerDN(new X509Name(issuer));
                certGen.SetNotBefore(notBefore);
                certGen.SetNotAfter(notAfter);
                if (dnsNames.Length == 1)
                {
                    certGen.SetSubjectDN(new X509Name(subject));
                }

                certGen.SetPublicKey(cerKp.Public);
                certGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));

                var keyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(cerKp.Public);
                certGen.AddExtension(X509Extensions.SubjectKeyIdentifier, true, new SubjectKeyIdentifier(keyInfo));
                certGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, true, new AuthorityKeyIdentifier(keyInfo));
                certGen.AddExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth));

                if (cbGenerate.Checked)
                {
                    var subjectAlternativeNames = new List <Asn1Encodable>();
                    foreach (var item in dnsNames)
                    {
                        subjectAlternativeNames.Add(new GeneralName(GeneralName.DnsName, item));
                    }
                    var subjectAlternativeNamesExtension = new DerSequence(subjectAlternativeNames.ToArray());
                    certGen.AddExtension(X509Extensions.SubjectAlternativeName, true, subjectAlternativeNamesExtension);
                }

                string hashName = cbHashing.SelectedIndex == 0 ? "SHA1WithRSA" : "SHA256WithRSA";
                var factory     = new Asn1SignatureFactory(hashName, cerKp.Private, random);

                string p12File = Path.GetTempFileName();
                string p12pwd  = "test";

                try
                {
                    Org.BouncyCastle.X509.X509Certificate x509 = certGen.Generate(factory);
                    var store            = new Pkcs12Store();
                    var certificateEntry = new X509CertificateEntry(x509);
                    var friendlyName     = txtName.Text;
                    store.SetCertificateEntry(friendlyName, certificateEntry);
                    store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(cerKp.Private), new[] { certificateEntry });
                    var stream = new MemoryStream();
                    store.Save(stream, p12pwd.ToCharArray(), random);
                    File.WriteAllBytes(p12File, stream.ToArray());

                    Item = new X509Certificate2(p12File, p12pwd)
                    {
                        FriendlyName = friendlyName
                    };
                    Store = cbStore.SelectedIndex == 0 ? "Personal" : "WebHosting";

                    try
                    {
                        using var process = new Process();
                        // add certificate
                        var start             = process.StartInfo;
                        start.Verb            = "runas";
                        start.UseShellExecute = true;
                        start.FileName        = "cmd";
                        start.Arguments       = $"/c \"\"{CertificateInstallerLocator.FileName}\" /f:\"{p12File}\" /p:{p12pwd} /n:\"{txtName.Text}\" /s:{(cbStore.SelectedIndex == 0 ? "MY" : "WebHosting")}\"";
                        start.CreateNoWindow  = true;
                        start.WindowStyle     = ProcessWindowStyle.Hidden;
                        process.Start();
                        process.WaitForExit();
                        File.Delete(p12File);
                        if (process.ExitCode == 0)
                        {
                            DialogResult = DialogResult.OK;
                        }
                        else
                        {
                            ShowMessage(process.ExitCode.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                        }
                    }
                    catch (Win32Exception ex)
                    {
                        // elevation is cancelled.
                        if (!Microsoft.Web.Administration.NativeMethods.ErrorCancelled(ex.NativeErrorCode))
                        {
                            RollbarLocator.RollbarInstance.Error(ex, new Dictionary <string, object> {
                                { "native", ex.NativeErrorCode }
                            });
                            // throw;
                        }
                    }
                    catch (Exception ex)
                    {
                        RollbarLocator.RollbarInstance.Error(ex);
                    }
                }
                catch (Exception ex)
                {
                    RollbarLocator.RollbarInstance.Error(ex);
                    ShowError(ex, Text, false);
                    return;
                }
            }));

            container.Add(
                Observable.FromEventPattern <CancelEventArgs>(this, "HelpButtonClicked")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(EnvironmentVariableTarget =>
            {
                feature.ShowHelp();
            }));
        }
Esempio n. 36
0
        /// <summary>
        /// Constructs a new EF_SOD file.
        /// </summary>
        /// <param name="data">bytes of the EF_DG1 file</param>
        public SODFile(byte[] data)
        {
            MemoryStream      dataStream = new MemoryStream(data);
            BERTLVInputStream tlvStream  = new BERTLVInputStream(dataStream);
            int tag = tlvStream.readTag();

            if (tag != IDGFile.EF_SOD_TAG)
            {
                throw new ArgumentException("Expected EF_SOD_TAG");
            }
            int length = tlvStream.readLength();

            Asn1InputStream     sodAsn1          = new Asn1InputStream(dataStream);
            DerSequence         seq              = (DerSequence)sodAsn1.ReadObject();
            DerObjectIdentifier objectIdentifier = (DerObjectIdentifier)seq[0];

            //DerTaggedObject o = (DerTaggedObject)seq[1];
            DerSequence s2 = (DerSequence)((DerTaggedObject)seq[1]).GetObject();
            IEnumerator e  = s2.GetEnumerator();

            e.MoveNext();
            DerInteger version = (DerInteger)e.Current;

            e.MoveNext();
            Asn1Set digestAlgorithms = (Asn1Set)e.Current;

            e.MoveNext();
            ContentInfo contentInfo = ContentInfo.GetInstance(e.Current);

            Asn1Set signerInfos  = null;
            bool    certsBer     = false;
            bool    crlsBer      = false;
            Asn1Set certificates = null;
            Asn1Set crls         = null;

            while (e.MoveNext())
            {
                Object o = e.Current;
                if (o is Asn1TaggedObject)
                {
                    Asn1TaggedObject tagged = (Asn1TaggedObject)o;
                    switch (tagged.TagNo)
                    {
                    case 0:
                        certsBer     = tagged is BerTaggedObject;
                        certificates = Asn1Set.GetInstance(tagged, false);
                        break;

                    case 1:
                        crlsBer = tagged is BerTaggedObject;
                        crls    = Asn1Set.GetInstance(tagged, false);
                        break;

                    default:
                        throw new ArgumentException("unknown tag value " + tagged.TagNo);
                    }
                }
                else
                {
                    signerInfos = (Asn1Set)o;
                }
            }
            _signedData = new SignedData(digestAlgorithms, contentInfo, certificates, crls, signerInfos);
            byte[]          content  = ((DerOctetString)contentInfo.Content).GetOctets();
            Asn1InputStream inStream = new Asn1InputStream(content);

            _lds = new LdsSecurityObject((Asn1Sequence)inStream.ReadObject());
        }