Example #1
0
 public CertificatePolicies(PolicyInformation name)
 {
     policyInformation = new PolicyInformation[1]
     {
         name
     };
 }
        /// <inheritdoc />
        public override void InjectReferenceValue(X509Certificate2 value)
        {
            Certificate = value;

            Asn1Object exValue = GetExtensionValue(value);

            if (exValue == null)
            {
                if (IsRequired())
                {
                    throw new PolicyRequiredException("Extention " + ExtentionIdentifier.Display + " is marked as required by is not present.");
                }
                var emptyList = new List <string>();
                PolicyValue = new PolicyValue <IList <String> >(emptyList);
                return;
            }
            var retVal = new List <String>();
            var seq    = exValue.ToAsn1Object() as Asn1Sequence;

            if (seq != null)
            {
                var pols = seq.GetEnumerator();
                while (pols.MoveNext())
                {
                    PolicyInformation pol = PolicyInformation.GetInstance(pols.Current);
                    retVal.Add(pol.PolicyIdentifier.Id);
                }
            }
            //TODO: PolicyInformation is only storing the ID.  There other intersting info items in here that we may want
            //maybe not for rules but for when things go wrong... logging info.
            PolicyValue = new PolicyValue <IList <String> >(retVal);
        }
 internal static string GetCertificatePolicyId(X509Certificate cert, int certificatePolicyPos = 0, int policyIdentifierPos = 0)
 {
     try
     {
         byte[] extPolicyBytes = cert.GetExtensionValue(CERTIFICATE_POLICY_OID).GetOctets();
         if (extPolicyBytes == null)
         {
             return(null);
         }
         DerOctetString oct = (DerOctetString)cert.GetExtensionValue(CERTIFICATE_POLICY_OID);
         Asn1Sequence   seq = (Asn1Sequence) new Asn1InputStream(oct.GetOctets()).ReadObject();
         if (seq.Count <= (certificatePolicyPos))
         {
             return(null);
         }
         CertificatePolicies certificatePolicies = new CertificatePolicies(
             PolicyInformation.GetInstance(seq[certificatePolicyPos]));
         PolicyInformation[] policyInformation = certificatePolicies.GetPolicyInformation();
         return(policyInformation[0].PolicyIdentifier.Id);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex);
         return(null);
     }
 }
Example #4
0
        public virtual bool Check(CertificateAndContext cert)
        {
            if (cert is null)
            {
                throw new System.ArgumentNullException(nameof(cert));
            }
            Asn1OctetString certificatePolicies = cert.Certificate.GetExtensionValue(X509Extensions.CertificatePolicies);

            if (certificatePolicies != null)
            {
                DerOctetString s       = (DerOctetString)certificatePolicies;
                byte[]         content = s.GetOctets();
                using (Asn1InputStream input = new Asn1InputStream(content))
                {
                    DerSequence seq = (DerSequence)input.ReadObject();
                    for (int i = 0; i < seq.Count; i++)
                    {
                        PolicyInformation policyInfo = PolicyInformation.GetInstance(seq[i]);
                        if (policyInfo.PolicyIdentifier.Id.Equals(policyOid, System.StringComparison.OrdinalIgnoreCase))
                        {
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
Example #5
0
        // encoder (NOTE - only supports simple notices)
        private void encode()
        {
            PolicyInformation[] polinfo = new PolicyInformation[policies.Count];

            for (int i = 0; i < policies.Count; i++)
            {
                if ((policies[i].Cps != "") || (policies[i].Unotice != ""))
                {
                    Asn1EncodableVector vq = new Asn1EncodableVector();
                    if (policies[i].Cps != "")                                  // cPSuri Qualifier
                    {
                        vq.Add(new PolicyQualifierInfo(policies[i].Cps));
                    }

                    if (policies[i].Unotice != "")                              //Unotice Qualifier
                    {
                        Asn1EncodableVector vn = new Asn1EncodableVector(new DerIA5String(policies[i].Unotice));
                        vq.Add(new PolicyQualifierInfo(PolicyQualifierID.IdQtUnotice, new DerSequence(vn)));
                    }

                    polinfo[i] = (new PolicyInformation(new DerObjectIdentifier(policies[i].Oid), new DerSequence(vq)));
                }
                else
                {
                    polinfo[i] = (new PolicyInformation(new DerObjectIdentifier(policies[i].Oid)));
                }
            }
            base.encValue = new CertificatePolicies(polinfo);
        }
Example #6
0
        public virtual bool Check(CertificateAndContext cert)
        {
            //TODO jbonilla - validar.
            //byte[] certificatePolicies = cert.GetCertificate().GetExtensionValue(X509Extensions.CertificatePolicies);
            Asn1OctetString certificatePolicies = cert.GetCertificate().GetExtensionValue(X509Extensions.CertificatePolicies);

            if (certificatePolicies != null)
            {
                try
                {
                    //Asn1InputStream input = new Asn1InputStream(certificatePolicies);
                    //DerOctetString s = (DerOctetString)input.ReadObject();
                    DerOctetString  s       = (DerOctetString)certificatePolicies;
                    byte[]          content = s.GetOctets();
                    Asn1InputStream input   = new Asn1InputStream(content);
                    DerSequence     seq     = (DerSequence)input.ReadObject();
                    for (int i = 0; i < seq.Count; i++)
                    {
                        PolicyInformation policyInfo = PolicyInformation.GetInstance(seq[i]);
                        if (policyInfo.PolicyIdentifier.Id.Equals(policyOid))
                        {
                            return(true);
                        }
                    }
                }
                catch (IOException e)
                {
                    throw new RuntimeException(e);
                }
            }
            return(false);
        }
Example #7
0
 private CertificatePolicies(Asn1Sequence seq)
 {
     policyInformation = new PolicyInformation[seq.Count];
     for (int i = 0; i < seq.Count; i++)
     {
         policyInformation[i] = PolicyInformation.GetInstance(seq[i]);
     }
 }
Example #8
0
 /// <summary>
 /// Add a policy to the list
 /// </summary>
 /// <param name="seq">Policy information</param>
 public CertificatePolicies(Asn1Sequence seq)
 {
     foreach (var pi in seq)
     {
         Asn1Sequence s = Asn1Sequence.GetInstance(pi);
         policies.Add(PolicyInformation.GetInstance(s));
     }
 }
Example #9
0
        /// <summary>
        /// Get the policy information
        /// </summary>
        /// <returns>Array of PolicyInformation</returns>
        public PolicyInformation[] GetPolicyInformation()
        {
            PolicyInformation[] pi = new PolicyInformation[policies.Count];

            for (int i = 0; i < policies.Count; ++i)
            {
                pi[i] = policies[i];
            }
            return(pi);
        }
        public void Read_WithAnyPolicyIdentifierAndNoPolicyQualifier_ReturnsPolicyInformation()
        {
            var bcPolicyInformation = new BcPolicyInformation(new DerObjectIdentifier(Oids.AnyPolicy));
            var bytes = bcPolicyInformation.GetDerEncoded();

            var policyInformation = PolicyInformation.Read(bytes);

            Assert.Equal(Oids.AnyPolicy, policyInformation.PolicyIdentifier.Value);
            Assert.Null(policyInformation.PolicyQualifiers);
        }
        public void Read_WithOnlyPolicyIdentifier_ReturnsPolicyInformation()
        {
            var policyId            = "1.2.3";
            var bcPolicyInformation = new BcPolicyInformation(new DerObjectIdentifier(policyId));
            var bytes = bcPolicyInformation.GetDerEncoded();

            var policyInformation = PolicyInformation.Read(bytes);

            Assert.Equal(policyId, policyInformation.PolicyIdentifier.Value);
            Assert.Null(policyInformation.PolicyQualifiers);
        }
Example #12
0
 public PolicyInformation[] GetPolicies()
 {
     if (this.policies == null)
     {
         return(null);
     }
     PolicyInformation[] array = new PolicyInformation[this.policies.Count];
     for (int i = 0; i < this.policies.Count; i++)
     {
         array[i] = PolicyInformation.GetInstance(this.policies[i].ToAsn1Object());
     }
     return(array);
 }
Example #13
0
 public PolicyInformation[] GetPolicies()
 {
     if (this.policies == null)
     {
         return(null);
     }
     PolicyInformation[] array = new PolicyInformation[this.policies.Count];
     for (int num = 0; num != this.policies.Count; num++)
     {
         array[num] = PolicyInformation.GetInstance(this.policies[num]);
     }
     return(array);
 }
Example #14
0
 public PolicyInformation[] GetPolicies()
 {
     if (policies == null)
     {
         return(null);
     }
     PolicyInformation[] array = new PolicyInformation[policies.Count];
     for (int i = 0; i != policies.Count; i++)
     {
         array[i] = PolicyInformation.GetInstance(policies[i]);
     }
     return(array);
 }
        public PolicyInformation[] GetPolicies()
        {
            if (policies == null)
            {
                return(null);
            }

            PolicyInformation[] ps = new PolicyInformation[policies.Count];
            for (int i = 0; i < policies.Count; ++i)
            {
                ps[i] = PolicyInformation.GetInstance(policies[i].ToAsn1Object());
            }
            return(ps);
        }
        public void Read_WithAnyPolicyIdentifierAndIdQtCpsPolicyQualifier_ReturnsPolicyInformation()
        {
            var cpsUri = new DerIA5String("http://test.test");
            var bcPolicyInformation = new BcPolicyInformation(
                new DerObjectIdentifier(Oids.AnyPolicy),
                new DerSequence(new BcPolicyQualifierInfo(new DerObjectIdentifier(Oids.IdQtCps), cpsUri)));
            var bytes = bcPolicyInformation.GetDerEncoded();

            var policyInformation = PolicyInformation.Read(bytes);

            Assert.Equal(Oids.AnyPolicy, policyInformation.PolicyIdentifier.Value);
            Assert.Equal(1, policyInformation.PolicyQualifiers.Count);
            Assert.Equal(cpsUri.GetDerEncoded(), policyInformation.PolicyQualifiers[0].Qualifier);
        }
Example #17
0
    public void InsertTemporaryPolicy(object o)
    {
        PolicyInformation pi    = (PolicyInformation)o;
        TemporaryPolicy   newTP = new TemporaryPolicy();

        newTP.PolicyNumber    = pi.PolicyNumber;
        newTP.PremiumValue    = pi.PremiumValue;
        newTP.StartDate       = pi.StartDate;
        newTP.WindshieldValue = pi.WindshieldValue;
        newTP.EndDate         = pi.EndDate;
        newTP.ClientName      = pi.ClientName;
        newTP.ClientAddress   = pi.ClientAddress;
        newTP.ApplicationDate = pi.ApplicationDate;
        newTP.Insert();
    }
        public static String GetCertificatePolicyOid(X509Certificate2 certificate)
        {
            var extensions = GetX509Extensions(certificate);
            var e          = extensions.GetExtension(X509Extensions.CertificatePolicies);
            var extIn      = new Asn1InputStream(e.Value.GetOctetStream());
            var piSeq      = (DerSequence)extIn.ReadObject();

            if (piSeq.Count != 1)
            {
                throw new NonOcesCertificateException("Could not find Certificate PolicyOID");
            }
            var pi = PolicyInformation.GetInstance(piSeq[0]);

            return(pi.PolicyIdentifier.Id);
        }
        /// <inheritdoc />
        public override void InjectReferenceValue(X509Certificate2 value)
        {
            Certificate = value;

            Asn1Object exValue = GetExtensionValue(value);

            if (exValue == null)
            {
                if (IsRequired())
                {
                    throw new PolicyRequiredException("Extention " + ExtentionIdentifier.Display + " is marked as required by is not present.");
                }
                var emptyList = new List <string>();
                PolicyValue = new PolicyValue <IList <string> >(emptyList);
                return;
            }
            var retVal = new List <String>();
            var seq    = exValue.ToAsn1Object() as Asn1Sequence;

            if (seq != null)
            {
                var pols = seq.GetEnumerator();
                while (pols.MoveNext())
                {
                    PolicyInformation pol = PolicyInformation.GetInstance(pols.Current);
                    if (pol.PolicyQualifiers != null)
                    {
                        var polInfos = pol.PolicyQualifiers.GetEnumerator();
                        while (polInfos.MoveNext())
                        {
                            // The PolicyQualifier object is not exposed nicely in the BouncyCastle API where Java is.
                            var derseq = polInfos.Current as DerSequence;

                            if (derseq.Id().Equals(PolicyQualifierID.IdQtCps))
                            {
                                retVal.Add(derseq.Value());
                            }
                        }
                    }
                }
            }

            PolicyValue = new PolicyValue <IList <string> >(retVal);
        }
Example #20
0
        static DerSequence CreatePolicyInformationsSequence(string cps, string org, string oid, string desc)
        {
            Asn1EncodableVector av = new Asn1EncodableVector();

            av.Add(new DerInteger(1));
            DerSequence noticeNumbers = new DerSequence(av);

            Asn1EncodableVector qualifiers = new Asn1EncodableVector();

            if (cps != null)
            {
                PolicyQualifierInfo cpsnotice = new PolicyQualifierInfo(cps);
                qualifiers.Add(cpsnotice);
            }
            if (org != null && desc != null)
            {
                UserNotice un = new UserNotice(
                    new NoticeReference(DisplayText.ContentTypeIA5String, org, noticeNumbers), // OPTIONAL Orgname
                    new DisplayText(DisplayText.ContentTypeVisibleString, desc
                                    )
                    );

                PolicyQualifierInfo pqiUNOTICE = new PolicyQualifierInfo(PolicyQualifierID.IdQtUnotice, un);


                qualifiers.Add(pqiUNOTICE);
            }

            DerObjectIdentifier policy = null;

            policy = new DerObjectIdentifier(oid);


            PolicyInformation policyInformation =
                new PolicyInformation(policy, new DerSequence(qualifiers));

            return(new DerSequence(policyInformation));
        }
Example #21
0
    public PolicyInformation Request(int nboCompanyID, string insuranceSubTypeCode)
    {
        PolicyInformation pi = new PolicyInformation();

        return(pi);
    }
        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(
                                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;
                    }
                }
            }
        }
Example #23
0
        public void CheckCertificate(
            int id,
            byte[]  cert)
        {
            Asn1Object seq  = Asn1Object.FromByteArray(cert);
            string     dump = Asn1Dump.DumpAsString(seq);

            X509CertificateStructure obj     = X509CertificateStructure.GetInstance(seq);
            TbsCertificateStructure  tbsCert = obj.TbsCertificate;

            if (!tbsCert.Subject.ToString().Equals(subjects[id - 1]))
            {
                Fail("failed subject test for certificate id " + id
                     + " got " + tbsCert.Subject.ToString());
            }

            if (tbsCert.Version >= 3)
            {
                X509Extensions ext = tbsCert.Extensions;
                if (ext != null)
                {
                    foreach (DerObjectIdentifier oid in ext.ExtensionOids)
                    {
                        X509Extension extVal = ext.GetExtension(oid);
                        Asn1Object    extObj = Asn1Object.FromByteArray(extVal.Value.GetOctets());

                        if (oid.Equals(X509Extensions.SubjectKeyIdentifier))
                        {
                            SubjectKeyIdentifier.GetInstance(extObj);
                        }
                        else if (oid.Equals(X509Extensions.KeyUsage))
                        {
                            KeyUsage.GetInstance(extObj);
                        }
                        else if (oid.Equals(X509Extensions.ExtendedKeyUsage))
                        {
                            ExtendedKeyUsage ku = ExtendedKeyUsage.GetInstance(extObj);

                            Asn1Sequence sq = (Asn1Sequence)ku.ToAsn1Object();
                            for (int i = 0; i != sq.Count; i++)
                            {
                                KeyPurposeID.GetInstance(sq[i]);
                            }
                        }
                        else if (oid.Equals(X509Extensions.SubjectAlternativeName))
                        {
                            GeneralNames gn = GeneralNames.GetInstance(extObj);

                            Asn1Sequence sq = (Asn1Sequence)gn.ToAsn1Object();
                            for (int i = 0; i != sq.Count; i++)
                            {
                                GeneralName.GetInstance(sq[i]);
                            }
                        }
                        else if (oid.Equals(X509Extensions.IssuerAlternativeName))
                        {
                            GeneralNames gn = GeneralNames.GetInstance(extObj);

                            Asn1Sequence sq = (Asn1Sequence)gn.ToAsn1Object();
                            for (int i = 0; i != sq.Count; i++)
                            {
                                GeneralName.GetInstance(sq[i]);
                            }
                        }
                        else if (oid.Equals(X509Extensions.CrlDistributionPoints))
                        {
                            CrlDistPoint p = CrlDistPoint.GetInstance(extObj);

                            DistributionPoint[] points = p.GetDistributionPoints();
                            for (int i = 0; i != points.Length; i++)
                            {
                                // do nothing
                            }
                        }
                        else if (oid.Equals(X509Extensions.CertificatePolicies))
                        {
                            Asn1Sequence cp = (Asn1Sequence)extObj;

                            for (int i = 0; i != cp.Count; i++)
                            {
                                PolicyInformation.GetInstance(cp[i]);
                            }
                        }
                        else if (oid.Equals(X509Extensions.AuthorityKeyIdentifier))
                        {
                            AuthorityKeyIdentifier.GetInstance(extObj);
                        }
                        else if (oid.Equals(X509Extensions.BasicConstraints))
                        {
                            BasicConstraints.GetInstance(extObj);
                        }
                        else
                        {
                            //Console.WriteLine(oid.Id);
                        }
                    }
                }
            }
        }
Example #24
0
        public virtual bool Match(object obj)
        {
            X509Certificate x509Certificate = obj as X509Certificate;

            if (x509Certificate == null)
            {
                return(false);
            }
            if (!MatchExtension(authorityKeyIdentifier, x509Certificate, X509Extensions.AuthorityKeyIdentifier))
            {
                return(false);
            }
            if (basicConstraints != -1)
            {
                int num = x509Certificate.GetBasicConstraints();
                if (basicConstraints == -2)
                {
                    if (num != -1)
                    {
                        return(false);
                    }
                }
                else if (num < basicConstraints)
                {
                    return(false);
                }
            }
            if (certificate != null && !certificate.Equals(x509Certificate))
            {
                return(false);
            }
            if (certificateValid != null && !x509Certificate.IsValid(certificateValid.Value))
            {
                return(false);
            }
            if (extendedKeyUsage != null)
            {
                global::System.Collections.IList list = x509Certificate.GetExtendedKeyUsage();
                if (list != null)
                {
                    {
                        global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)extendedKeyUsage).GetEnumerator();
                        try
                        {
                            while (enumerator.MoveNext())
                            {
                                DerObjectIdentifier derObjectIdentifier = (DerObjectIdentifier)enumerator.get_Current();
                                if (!list.Contains((object)derObjectIdentifier.Id))
                                {
                                    return(false);
                                }
                            }
                        }
                        finally
                        {
                            global::System.IDisposable disposable = enumerator as global::System.IDisposable;
                            if (disposable != null)
                            {
                                disposable.Dispose();
                            }
                        }
                    }
                }
            }
            if (issuer != null && !issuer.Equivalent(x509Certificate.IssuerDN, inOrder: true))
            {
                return(false);
            }
            if (keyUsage != null)
            {
                bool[] array = x509Certificate.GetKeyUsage();
                if (array != null)
                {
                    for (int i = 0; i < 9; i++)
                    {
                        if (keyUsage[i] && !array[i])
                        {
                            return(false);
                        }
                    }
                }
            }
            if (policy != null)
            {
                Asn1OctetString extensionValue = x509Certificate.GetExtensionValue(X509Extensions.CertificatePolicies);
                if (extensionValue == null)
                {
                    return(false);
                }
                Asn1Sequence instance = Asn1Sequence.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue));
                if (((global::System.Collections.ICollection)policy).get_Count() < 1 && instance.Count < 1)
                {
                    return(false);
                }
                bool flag = false;
                {
                    global::System.Collections.IEnumerator enumerator = instance.GetEnumerator();
                    try
                    {
                        while (enumerator.MoveNext())
                        {
                            PolicyInformation policyInformation = (PolicyInformation)enumerator.get_Current();
                            if (policy.Contains(policyInformation.PolicyIdentifier))
                            {
                                flag = true;
                                break;
                            }
                        }
                    }
                    finally
                    {
                        global::System.IDisposable disposable2 = enumerator as global::System.IDisposable;
                        if (disposable2 != null)
                        {
                            disposable2.Dispose();
                        }
                    }
                }
                if (!flag)
                {
                    return(false);
                }
            }
            if (privateKeyValid != null)
            {
                Asn1OctetString extensionValue2 = x509Certificate.GetExtensionValue(X509Extensions.PrivateKeyUsagePeriod);
                if (extensionValue2 == null)
                {
                    return(false);
                }
                PrivateKeyUsagePeriod   instance2 = PrivateKeyUsagePeriod.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue2));
                global::System.DateTime value     = privateKeyValid.Value;
                global::System.DateTime dateTime  = instance2.NotAfter.ToDateTime();
                global::System.DateTime dateTime2 = instance2.NotBefore.ToDateTime();
                if (value.CompareTo((object)dateTime) > 0 || value.CompareTo((object)dateTime2) < 0)
                {
                    return(false);
                }
            }
            if (serialNumber != null && !serialNumber.Equals(x509Certificate.SerialNumber))
            {
                return(false);
            }
            if (subject != null && !subject.Equivalent(x509Certificate.SubjectDN, inOrder: true))
            {
                return(false);
            }
            if (!MatchExtension(subjectKeyIdentifier, x509Certificate, X509Extensions.SubjectKeyIdentifier))
            {
                return(false);
            }
            if (subjectPublicKey != null && !subjectPublicKey.Equals(GetSubjectPublicKey(x509Certificate)))
            {
                return(false);
            }
            if (subjectPublicKeyAlgID != null && !subjectPublicKeyAlgID.Equals(GetSubjectPublicKey(x509Certificate).AlgorithmID))
            {
                return(false);
            }
            return(true);
        }
Example #25
0
 /// <summary>
 /// Add a policy to the list
 /// </summary>
 /// <param name="p">Policy information</param>
 public void AddPolicy(PolicyInformation p)
 {
     policies.Add(p);
 }
 public void Read_WithInvalidAsn1_Throws()
 {
     Assert.Throws <CryptographicException>(
         () => PolicyInformation.Read(new byte[] { 0x30, 0x07 }));
 }
Example #27
0
        internal static void PrepareNextCertB1(int i, global::System.Collections.IList[] policyNodes, string id_p, IDictionary m_idp, X509Certificate cert)
        {
            bool flag = false;

            global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)policyNodes[i]).GetEnumerator();
            while (enumerator.MoveNext())
            {
                PkixPolicyNode pkixPolicyNode = (PkixPolicyNode)enumerator.get_Current();
                if (pkixPolicyNode.ValidPolicy.Equals(id_p))
                {
                    flag = true;
                    pkixPolicyNode.ExpectedPolicies = (ISet)m_idp.get_Item((object)id_p);
                    break;
                }
            }
            if (flag)
            {
                return;
            }
            enumerator = ((global::System.Collections.IEnumerable)policyNodes[i]).GetEnumerator();
            while (enumerator.MoveNext())
            {
                PkixPolicyNode pkixPolicyNode2 = (PkixPolicyNode)enumerator.get_Current();
                if (!ANY_POLICY.Equals(pkixPolicyNode2.ValidPolicy))
                {
                    continue;
                }
                ISet         policyQualifiers = null;
                Asn1Sequence asn1Sequence     = null;
                try
                {
                    asn1Sequence = Asn1Sequence.GetInstance(GetExtensionValue(cert, X509Extensions.CertificatePolicies));
                }
                catch (global::System.Exception ex)
                {
                    throw new global::System.Exception("Certificate policies cannot be decoded.", ex);
                }
                global::System.Collections.IEnumerator enumerator2 = asn1Sequence.GetEnumerator();
                while (enumerator2.MoveNext())
                {
                    PolicyInformation policyInformation = null;
                    try
                    {
                        policyInformation = PolicyInformation.GetInstance(enumerator2.get_Current());
                    }
                    catch (global::System.Exception ex2)
                    {
                        throw new global::System.Exception("Policy information cannot be decoded.", ex2);
                    }
                    if (ANY_POLICY.Equals(policyInformation.PolicyIdentifier.Id))
                    {
                        try
                        {
                            policyQualifiers = GetQualifierSet(policyInformation.PolicyQualifiers);
                        }
                        catch (PkixCertPathValidatorException cause)
                        {
                            throw new PkixCertPathValidatorException("Policy qualifier info set could not be built.", cause);
                        }
                        break;
                    }
                }
                bool critical = false;
                ISet criticalExtensionOids = cert.GetCriticalExtensionOids();
                if (criticalExtensionOids != null)
                {
                    critical = criticalExtensionOids.Contains(X509Extensions.CertificatePolicies.Id);
                }
                PkixPolicyNode parent = pkixPolicyNode2.Parent;
                if (ANY_POLICY.Equals(parent.ValidPolicy))
                {
                    PkixPolicyNode pkixPolicyNode3 = new PkixPolicyNode(Platform.CreateArrayList(), i, (ISet)m_idp.get_Item((object)id_p), parent, policyQualifiers, id_p, critical);
                    parent.AddChild(pkixPolicyNode3);
                    policyNodes[i].Add((object)pkixPolicyNode3);
                }
                break;
            }
        }
Example #28
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));
        }
Example #29
0
        static bool Gen(string summoner, string region, string password, string file)
        {
            try
            {
                //Later in your Code

                //Requested Certificate Name
                X509Name name = new X509Name("CN=" + summoner + " - " + region + ", OU=Ghostblade Replays, O=Arsslensoft");

                //Key generation 2048bits
                RsaKeyPairGenerator rkpg = new RsaKeyPairGenerator();
                rkpg.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
                AsymmetricCipherKeyPair ackp   = rkpg.GenerateKeyPair();
                X509Certificate2        caCert = new X509Certificate2(GBReplay.Properties.Resources.GBSGN, "KGPAQW7894Q129D7Q1456W9A47897a9s7r5d6");
                //PKCS #10 Certificate Signing Request
                Pkcs10CertificationRequest csr = new Pkcs10CertificationRequest("SHA256WITHRSA", name, ackp.Public, null, ackp.Private);


                AsymmetricKeyParameter publicKey = csr.GetPublicKey();

                // Build a Version1 (No Extensions) Certificate
                DateTime   startDate    = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
                DateTime   expiryDate   = startDate.AddYears(5);
                BigInteger serialNumber = new BigInteger(32, new Random());


                X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

                X509Name dnName = new X509Name(caCert.Subject);

                certGen.SetSerialNumber(serialNumber);
                certGen.SetIssuerDN(dnName);
                certGen.SetNotBefore(startDate);
                certGen.SetNotAfter(expiryDate);
                certGen.SetSubjectDN(name);
                certGen.SetSignatureAlgorithm("SHA256WITHRSA");
                certGen.SetPublicKey(publicKey);

                UserNotice          unotice    = new UserNotice(null, "This certificate must be only used with Ghostblade replays files. This certificate is a property of Arsslensoft any usage of its content without prior request is prohibited.");
                PolicyQualifierInfo pqiunotice = new PolicyQualifierInfo(PolicyQualifierID.IdQtUnotice, unotice);
                PolicyInformation   p          = new PolicyInformation(new DerObjectIdentifier("1.3.6.1.4.1.44215.1.3"), new DerSequence(new PolicyQualifierInfo[1] {
                    pqiunotice
                }));
                certGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
                certGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(DotNetUtilities.FromX509Certificate(caCert).GetPublicKey()));
                certGen.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(publicKey));
                certGen.AddExtension(X509Extensions.KeyUsage, false, new  KeyUsage(KeyUsage.DigitalSignature));
                certGen.AddExtension(X509Extensions.ExtendedKeyUsage, false, new  ExtendedKeyUsage(new KeyPurposeID[] { KeyPurposeID.IdKPCodeSigning }));

                certGen.AddExtension(X509Extensions.CertificatePolicies, false, new DerSequence(p));



                Pkcs12Store pfx   = new Pkcs12Store(new MemoryStream(GBReplay.Properties.Resources.GBSGN), "KGPAQW7894Q129D7Q1456W9A47897a9s7r5d6".ToCharArray());
                string      alias = null;
                foreach (string al in pfx.Aliases)
                {
                    if (pfx.IsKeyEntry(al) && pfx.GetKey(al).Key.IsPrivate)
                    {
                        alias = al;
                        break;
                    }
                }

                //get our Private Key to Sign with

                //   AsymmetricCipherKeyPair caPair = DotNetUtilities.GetKeyPair(caCert.PrivateKey);
                AsymmetricKeyParameter caPair = pfx.GetKey(alias).Key;

                Al.Security.X509.X509Certificate cert = certGen.Generate(caPair);

                Pkcs12Store pk = new Pkcs12StoreBuilder().Build();
                // Add a Certificate entry
                X509CertificateEntry certEntry = new X509CertificateEntry(cert);
                pk.SetCertificateEntry(cert.SubjectDN.ToString(), certEntry); // use DN as the Alias.

                AsymmetricKeyEntry keyEntry = new AsymmetricKeyEntry(ackp.Private);
                pk.SetKeyEntry(cert.SubjectDN.ToString(), keyEntry, new X509CertificateEntry[] { certEntry }); // Note that we only have 1 cert in the 'chain'

                using (var filestream = new FileStream(file, FileMode.Create, FileAccess.ReadWrite))
                    pk.Save(filestream, password.ToCharArray(), new SecureRandom());

                X509Certificate2 cer = new X509Certificate2(File.ReadAllBytes(file), password);
                cer.Verify();
            }
            catch
            {
                return(false);
            }
            return(true);
        }
Example #30
0
        internal static void PrepareNextCertB1(int i, IList[] policyNodes, string id_p, IDictionary m_idp, X509Certificate cert)
        {
            bool        flag       = false;
            IEnumerator enumerator = policyNodes[i].GetEnumerator();

            while (enumerator.MoveNext())
            {
                PkixPolicyNode pkixPolicyNode = (PkixPolicyNode)enumerator.Current;
                if (pkixPolicyNode.ValidPolicy.Equals(id_p))
                {
                    flag = true;
                    pkixPolicyNode.ExpectedPolicies = (ISet)m_idp[id_p];
                    break;
                }
            }
            if (!flag)
            {
                enumerator = policyNodes[i].GetEnumerator();
                while (enumerator.MoveNext())
                {
                    PkixPolicyNode pkixPolicyNode2 = (PkixPolicyNode)enumerator.Current;
                    if (PkixCertPathValidatorUtilities.ANY_POLICY.Equals(pkixPolicyNode2.ValidPolicy))
                    {
                        ISet         policyQualifiers = null;
                        Asn1Sequence asn1Sequence     = null;
                        try
                        {
                            asn1Sequence = Asn1Sequence.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.CertificatePolicies));
                        }
                        catch (Exception innerException)
                        {
                            throw new Exception("Certificate policies cannot be decoded.", innerException);
                        }
                        IEnumerator enumerator2 = asn1Sequence.GetEnumerator();
                        while (enumerator2.MoveNext())
                        {
                            PolicyInformation policyInformation = null;
                            try
                            {
                                policyInformation = PolicyInformation.GetInstance(enumerator2.Current);
                            }
                            catch (Exception innerException2)
                            {
                                throw new Exception("Policy information cannot be decoded.", innerException2);
                            }
                            if (PkixCertPathValidatorUtilities.ANY_POLICY.Equals(policyInformation.PolicyIdentifier.Id))
                            {
                                try
                                {
                                    policyQualifiers = PkixCertPathValidatorUtilities.GetQualifierSet(policyInformation.PolicyQualifiers);
                                    break;
                                }
                                catch (PkixCertPathValidatorException cause)
                                {
                                    throw new PkixCertPathValidatorException("Policy qualifier info set could not be built.", cause);
                                }
                            }
                        }
                        bool critical = false;
                        ISet criticalExtensionOids = cert.GetCriticalExtensionOids();
                        if (criticalExtensionOids != null)
                        {
                            critical = criticalExtensionOids.Contains(X509Extensions.CertificatePolicies.Id);
                        }
                        PkixPolicyNode parent = pkixPolicyNode2.Parent;
                        if (PkixCertPathValidatorUtilities.ANY_POLICY.Equals(parent.ValidPolicy))
                        {
                            PkixPolicyNode pkixPolicyNode3 = new PkixPolicyNode(Platform.CreateArrayList(), i, (ISet)m_idp[id_p], parent, policyQualifiers, id_p, critical);
                            parent.AddChild(pkixPolicyNode3);
                            policyNodes[i].Add(pkixPolicyNode3);
                            return;
                        }
                        break;
                    }
                }
            }
        }