コード例 #1
0
 internal static bool IssuersMatch(X509Name a, X509Name b)
 {
     return(a?.Equivalent(b, inOrder: true) ?? (b == null));
 }
コード例 #2
0
        internal static void GetCertStatus(
            DateTime validDate,
            X509Crl crl,
            Object cert,
            CertStatus certStatus)
        {
            X509Crl bcCRL = null;

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

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

            if (crl_entry == null)
            {
                return;
            }

            X509Name issuer = GetIssuerPrincipal(cert);

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

                // for reason keyCompromise, caCompromise, aACompromise or
                // unspecified
                if (!(validDate.Ticks < crl_entry.RevocationDate.Ticks) ||
                    reasonCode == null ||
                    reasonCode.Value.TestBit(0) ||
                    reasonCode.Value.TestBit(1) ||
                    reasonCode.Value.TestBit(2) ||
                    reasonCode.Value.TestBit(8))
                {
                    if (reasonCode != null)                     // (i) or (j) (1)
                    {
                        certStatus.Status = reasonCode.Value.SignValue;
                    }
                    else                     // (i) or (j) (2)
                    {
                        certStatus.Status = CrlReason.Unspecified;
                    }
                    certStatus.RevocationDate = new DateTimeObject(crl_entry.RevocationDate);
                }
            }
        }
コード例 #3
0
        /// <summary>
        /// Search the given Set of TrustAnchor's for one that is the
        /// issuer of the given X509 certificate.
        /// </summary>
        /// <param name="cert">the X509 certificate</param>
        /// <param name="trustAnchors">a Set of TrustAnchor's</param>
        /// <returns>the <code>TrustAnchor</code> object if found or
        /// <code>null</code> if not.
        /// </returns>
        /// @exception
        internal static TrustAnchor FindTrustAnchor(
            X509Certificate cert,
            ISet trustAnchors)
        {
            IEnumerator            iter           = trustAnchors.GetEnumerator();
            TrustAnchor            trust          = null;
            AsymmetricKeyParameter trustPublicKey = null;
            Exception invalidKeyEx = null;

            X509CertStoreSelector certSelectX509 = new X509CertStoreSelector();

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

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

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

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

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

            return(trust);
        }
コード例 #4
0
ファイル: Pkcs12Store.cs プロジェクト: Siegema/socket-test
        public X509CertificateEntry[] GetCertificateChain(
            string alias)
        {
            if (alias == null)
            {
                throw new ArgumentNullException("alias");
            }

            if (!IsKeyEntry(alias))
            {
                return(null);
            }

            X509CertificateEntry c = GetCertificate(alias);

            if (c != null)
            {
                IList cs = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();

                while (c != null)
                {
                    X509Certificate      x509c = c.Certificate;
                    X509CertificateEntry nextC = null;

                    Asn1OctetString akiValue = x509c.GetExtensionValue(X509Extensions.AuthorityKeyIdentifier);
                    if (akiValue != null)
                    {
                        AuthorityKeyIdentifier aki = AuthorityKeyIdentifier.GetInstance(akiValue.GetOctets());

                        byte[] keyID = aki.GetKeyIdentifier();
                        if (keyID != null)
                        {
                            nextC = (X509CertificateEntry)chainCerts[new CertId(keyID)];
                        }
                    }

                    if (nextC == null)
                    {
                        //
                        // no authority key id, try the Issuer DN
                        //
                        X509Name i = x509c.IssuerDN;
                        X509Name s = x509c.SubjectDN;

                        if (!i.Equivalent(s))
                        {
                            foreach (CertId certId in chainCerts.Keys)
                            {
                                X509CertificateEntry x509CertEntry = (X509CertificateEntry)chainCerts[certId];

                                X509Certificate crt = x509CertEntry.Certificate;

                                X509Name sub = crt.SubjectDN;
                                if (sub.Equivalent(i))
                                {
                                    try
                                    {
                                        x509c.Verify(crt.GetPublicKey());

                                        nextC = x509CertEntry;
                                        break;
                                    }
                                    catch (InvalidKeyException)
                                    {
                                        // TODO What if it doesn't verify?
                                    }
                                }
                            }
                        }
                    }

                    cs.Add(c);
                    if (nextC != c) // self signed - end of the chain
                    {
                        c = nextC;
                    }
                    else
                    {
                        c = null;
                    }
                }

                X509CertificateEntry[] result = new X509CertificateEntry[cs.Count];
                for (int i = 0; i < cs.Count; ++i)
                {
                    result[i] = (X509CertificateEntry)cs[i];
                }
                return(result);
            }

            return(null);
        }
コード例 #5
0
        /**
         * @param certs
         */
        private static IList SortCerts(
            IList certs)
        {
            if (certs.Count < 2)
            {
                return(certs);
            }

            X509Name issuer = ((X509Certificate)certs[0]).IssuerDN;
            bool     okay   = true;

            for (int i = 1; i != certs.Count; i++)
            {
                X509Certificate cert = (X509Certificate)certs[i];

                if (issuer.Equivalent(cert.SubjectDN, true))
                {
                    issuer = ((X509Certificate)certs[i]).IssuerDN;
                }
                else
                {
                    okay = false;
                    break;
                }
            }

            if (okay)
            {
                return(certs);
            }

            // find end-entity cert
            IList retList = Platform.CreateArrayList(certs.Count);
            IList orig    = Platform.CreateArrayList(certs);

            for (int i = 0; i < certs.Count; i++)
            {
                X509Certificate cert  = (X509Certificate)certs[i];
                bool            found = false;

                X509Name subject = cert.SubjectDN;
                foreach (X509Certificate c in certs)
                {
                    if (c.IssuerDN.Equivalent(subject, true))
                    {
                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    retList.Add(cert);
                    certs.RemoveAt(i);
                }
            }

            // can only have one end entity cert - something's wrong, give up.
            if (retList.Count > 1)
            {
                return(orig);
            }

            for (int i = 0; i != retList.Count; i++)
            {
                issuer = ((X509Certificate)retList[i]).IssuerDN;

                for (int j = 0; j < certs.Count; j++)
                {
                    X509Certificate c = (X509Certificate)certs[j];
                    if (issuer.Equivalent(c.SubjectDN, true))
                    {
                        retList.Add(c);
                        certs.RemoveAt(j);
                        break;
                    }
                }
            }

            // make sure all certificates are accounted for.
            if (certs.Count > 0)
            {
                return(orig);
            }

            return(retList);
        }
コード例 #6
0
        public virtual bool Match(
            object obj)
        {
            X509Certificate c = obj as X509Certificate;

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

            if (!MatchExtension(authorityKeyIdentifier, c, X509Extensions.AuthorityKeyIdentifier))
            {
                return(false);
            }

            if (basicConstraints != -1)
            {
                int bc = c.GetBasicConstraints();

                if (basicConstraints == -2)
                {
                    if (bc != -1)
                    {
                        return(false);
                    }
                }
                else
                {
                    if (bc < basicConstraints)
                    {
                        return(false);
                    }
                }
            }

            if (certificate != null && !certificate.Equals(c))
            {
                return(false);
            }

            if (certificateValid != null && !c.IsValid(certificateValid.Value))
            {
                return(false);
            }

            if (extendedKeyUsage != null)
            {
                IList eku = c.GetExtendedKeyUsage();

                // Note: if no extended key usage set, all key purposes are implicitly allowed

                if (eku != null)
                {
                    foreach (DerObjectIdentifier oid in extendedKeyUsage)
                    {
                        if (!eku.Contains(oid.Id))
                        {
                            return(false);
                        }
                    }
                }
            }

            if (issuer != null && !issuer.Equivalent(c.IssuerDN, true))
            {
                return(false);
            }

            if (keyUsage != null)
            {
                bool[] ku = c.GetKeyUsage();

                // Note: if no key usage set, all key purposes are implicitly allowed

                if (ku != null)
                {
                    for (int i = 0; i < 9; ++i)
                    {
                        if (keyUsage[i] && !ku[i])
                        {
                            return(false);
                        }
                    }
                }
            }

            if (policy != null)
            {
                Asn1OctetString extVal = c.GetExtensionValue(X509Extensions.CertificatePolicies);
                if (extVal == null)
                {
                    return(false);
                }

                Asn1Sequence certPolicies = Asn1Sequence.GetInstance(
                    X509ExtensionUtilities.FromExtensionValue(extVal));

                if (policy.Count < 1 && certPolicies.Count < 1)
                {
                    return(false);
                }

                bool found = false;
                foreach (PolicyInformation pi in certPolicies)
                {
                    if (policy.Contains(pi.PolicyIdentifier))
                    {
                        found = true;
                        break;
                    }
                }

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

            if (privateKeyValid != null)
            {
                Asn1OctetString extVal = c.GetExtensionValue(X509Extensions.PrivateKeyUsagePeriod);
                if (extVal == null)
                {
                    return(false);
                }

                PrivateKeyUsagePeriod pkup = PrivateKeyUsagePeriod.GetInstance(
                    X509ExtensionUtilities.FromExtensionValue(extVal));

                DateTime dt        = privateKeyValid.Value;
                DateTime notAfter  = pkup.NotAfter.ToDateTime();
                DateTime notBefore = pkup.NotBefore.ToDateTime();

                if (dt.CompareTo(notAfter) > 0 || dt.CompareTo(notBefore) < 0)
                {
                    return(false);
                }
            }

            if (serialNumber != null && !serialNumber.Equals(c.SerialNumber))
            {
                return(false);
            }

            if (subject != null && !subject.Equivalent(c.SubjectDN, true))
            {
                return(false);
            }

            if (!MatchExtension(subjectKeyIdentifier, c, X509Extensions.SubjectKeyIdentifier))
            {
                return(false);
            }

            if (subjectPublicKey != null && !subjectPublicKey.Equals(GetSubjectPublicKey(c)))
            {
                return(false);
            }

            if (subjectPublicKeyAlgID != null &&
                !subjectPublicKeyAlgID.Equals(GetSubjectPublicKey(c).AlgorithmID))
            {
                return(false);
            }

            return(true);
        }
コード例 #7
0
 internal static bool IssuersMatch(
     X509Name a,
     X509Name b)
 {
     return(a == null ? b == null : a.Equivalent(b, true));
 }
コード例 #8
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);
        }
コード例 #9
0
        internal static void GetCertStatus(
            DateTime validDate,
            X509Crl crl,
            Object cert,
            CertStatus certStatus)
        {
            X509Crl bcCRL = null;

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

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

            if (crl_entry == null)
            {
                return;
            }

            X509Name issuer = GetIssuerPrincipal(cert);

            if (!issuer.Equivalent(crl_entry.GetCertificateIssuer(), true) &&
                !issuer.Equivalent(crl.IssuerDN, true))
            {
                return;
            }

            int reasonCodeValue = CrlReason.Unspecified;

            if (crl_entry.HasExtensions)
            {
                try
                {
                    Asn1Object    extValue   = GetExtensionValue(crl_entry, X509Extensions.ReasonCode);
                    DerEnumerated reasonCode = DerEnumerated.GetInstance(extValue);
                    if (null != reasonCode)
                    {
                        reasonCodeValue = reasonCode.IntValueExact;
                    }
                }
                catch (Exception e)
                {
                    throw new Exception("Reason code CRL entry extension could not be decoded.", e);
                }
            }

            DateTime revocationDate = crl_entry.RevocationDate;

            if (validDate.Ticks < revocationDate.Ticks)
            {
                switch (reasonCodeValue)
                {
                case CrlReason.Unspecified:
                case CrlReason.KeyCompromise:
                case CrlReason.CACompromise:
                case CrlReason.AACompromise:
                    break;

                default:
                    return;
                }
            }

            // (i) or (j)
            certStatus.Status         = reasonCodeValue;
            certStatus.RevocationDate = new DateTimeObject(revocationDate);
        }
コード例 #10
0
        internal static TrustAnchor FindTrustAnchor(X509Certificate cert, ISet trustAnchors)
        {
            //IL_0028: Expected O, but got Unknown
            global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)trustAnchors).GetEnumerator();
            TrustAnchor            trustAnchor            = null;
            AsymmetricKeyParameter asymmetricKeyParameter = null;

            global::System.Exception ex = null;
            X509CertStoreSelector    x509CertStoreSelector = new X509CertStoreSelector();

            try
            {
                x509CertStoreSelector.Subject = GetIssuerPrincipal(cert);
            }
            catch (IOException val)
            {
                IOException val2 = val;
                throw new global::System.Exception("Cannot set subject search criteria for trust anchor.", (global::System.Exception)(object) val2);
            }
            while (enumerator.MoveNext() && trustAnchor == null)
            {
                trustAnchor = (TrustAnchor)enumerator.get_Current();
                if (trustAnchor.TrustedCert != null)
                {
                    if (x509CertStoreSelector.Match(trustAnchor.TrustedCert))
                    {
                        asymmetricKeyParameter = trustAnchor.TrustedCert.GetPublicKey();
                    }
                    else
                    {
                        trustAnchor = null;
                    }
                }
                else if (trustAnchor.CAName != null && trustAnchor.CAPublicKey != null)
                {
                    try
                    {
                        X509Name issuerPrincipal = GetIssuerPrincipal(cert);
                        X509Name other           = new X509Name(trustAnchor.CAName);
                        if (issuerPrincipal.Equivalent(other, inOrder: true))
                        {
                            asymmetricKeyParameter = trustAnchor.CAPublicKey;
                        }
                        else
                        {
                            trustAnchor = null;
                        }
                    }
                    catch (InvalidParameterException)
                    {
                        trustAnchor = null;
                    }
                }
                else
                {
                    trustAnchor = null;
                }
                if (asymmetricKeyParameter != null)
                {
                    try
                    {
                        cert.Verify(asymmetricKeyParameter);
                    }
                    catch (global::System.Exception ex3)
                    {
                        ex          = ex3;
                        trustAnchor = null;
                    }
                }
            }
            if (trustAnchor == null && ex != null)
            {
                throw new global::System.Exception("TrustAnchor found but certificate validation failed.", ex);
            }
            return(trustAnchor);
        }
コード例 #11
0
ファイル: X509NameTest.cs プロジェクト: AlexPaskhin/bc-csharp
        public override void PerformTest()
        {
            doTestEncodingPrintableString(X509Name.C, "AU");
            doTestEncodingPrintableString(X509Name.SerialNumber, "123456");
            doTestEncodingPrintableString(X509Name.DnQualifier, "123456");
            doTestEncodingIA5String(X509Name.EmailAddress, "*****@*****.**");
            doTestEncodingIA5String(X509Name.DC, "test");
            // correct encoding
            doTestEncodingGeneralizedTime(X509Name.DateOfBirth, "#180F32303032303132323132323232305A");
            // compatability encoding
            doTestEncodingGeneralizedTime(X509Name.DateOfBirth, "20020122122220Z");

            //
            // composite
            //
            IDictionary attrs = new Hashtable();

            attrs.Add(X509Name.C, "AU");
            attrs.Add(X509Name.O, "The Legion of the Bouncy Castle");
            attrs.Add(X509Name.L, "Melbourne");
            attrs.Add(X509Name.ST, "Victoria");
            attrs.Add(X509Name.E, "*****@*****.**");

            IList order = new ArrayList();

            order.Add(X509Name.C);
            order.Add(X509Name.O);
            order.Add(X509Name.L);
            order.Add(X509Name.ST);
            order.Add(X509Name.E);

            X509Name name1 = new X509Name(order, attrs);

            if (!name1.Equivalent(name1))
            {
                Fail("Failed same object test");
            }

            if (!name1.Equivalent(name1, true))
            {
                Fail("Failed same object test - in Order");
            }

            X509Name name2 = new X509Name(order, attrs);

            if (!name1.Equivalent(name2))
            {
                Fail("Failed same name test");
            }

            if (!name1.Equivalent(name2, true))
            {
                Fail("Failed same name test - in Order");
            }

            if (name1.GetHashCode() != name2.GetHashCode())
            {
                Fail("Failed same name test - in Order");
            }

            IList ord1 = new ArrayList();

            ord1.Add(X509Name.C);
            ord1.Add(X509Name.O);
            ord1.Add(X509Name.L);
            ord1.Add(X509Name.ST);
            ord1.Add(X509Name.E);

            IList ord2 = new ArrayList();

            ord2.Add(X509Name.E);
            ord2.Add(X509Name.ST);
            ord2.Add(X509Name.L);
            ord2.Add(X509Name.O);
            ord2.Add(X509Name.C);

            name1 = new X509Name(ord1, attrs);
            name2 = new X509Name(ord2, attrs);

            if (!name1.Equivalent(name2))
            {
                Fail("Failed reverse name test");
            }

            // FIXME Sort out X509Name hashcode problem
//			if (name1.GetHashCode() != name2.GetHashCode())
//			{
//				Fail("Failed reverse name test GetHashCode");
//			}

            if (name1.Equivalent(name2, true))
            {
                Fail("Failed reverse name test - in Order");
            }

            if (!name1.Equivalent(name2, false))
            {
                Fail("Failed reverse name test - in Order false");
            }

            IList oids = name1.GetOidList();

            if (!CompareVectors(oids, ord1))
            {
                Fail("oid comparison test");
            }

            IList val1 = new ArrayList();

            val1.Add("AU");
            val1.Add("The Legion of the Bouncy Castle");
            val1.Add("Melbourne");
            val1.Add("Victoria");
            val1.Add("*****@*****.**");

            name1 = new X509Name(ord1, val1);

            IList values = name1.GetValueList();

            if (!CompareVectors(values, val1))
            {
                Fail("value comparison test");
            }

            ord2 = new ArrayList();

            ord2.Add(X509Name.ST);
            ord2.Add(X509Name.ST);
            ord2.Add(X509Name.L);
            ord2.Add(X509Name.O);
            ord2.Add(X509Name.C);

            name1 = new X509Name(ord1, attrs);
            name2 = new X509Name(ord2, attrs);

            if (name1.Equivalent(name2))
            {
                Fail("Failed different name test");
            }

            ord2 = new ArrayList();

            ord2.Add(X509Name.ST);
            ord2.Add(X509Name.L);
            ord2.Add(X509Name.O);
            ord2.Add(X509Name.C);

            name1 = new X509Name(ord1, attrs);
            name2 = new X509Name(ord2, attrs);

            if (name1.Equivalent(name2))
            {
                Fail("Failed subset name test");
            }


            compositeTest();


            //
            // getValues test
            //
            IList v1 = name1.GetValueList(X509Name.O);

            if (v1.Count != 1 || !v1[0].Equals("The Legion of the Bouncy Castle"))
            {
                Fail("O test failed");
            }

            IList v2 = name1.GetValueList(X509Name.L);

            if (v2.Count != 1 || !v2[0].Equals("Melbourne"))
            {
                Fail("L test failed");
            }

            //
            // general subjects test
            //
            for (int i = 0; i != subjects.Length; i++)
            {
                X509Name name        = new X509Name(subjects[i]);
                byte[]   encodedName = name.GetEncoded();
                name = X509Name.GetInstance(Asn1Object.FromByteArray(encodedName));

                if (!name.ToString().Equals(subjects[i]))
                {
                    Fail("Failed regeneration test " + i);
                }
            }

            //
            // sort test
            //
            X509Name unsorted = new X509Name("SERIALNUMBER=BBB + CN=AA");

            if (!FromBytes(unsorted.GetEncoded()).ToString().Equals("CN=AA+SERIALNUMBER=BBB"))
            {
                Fail("Failed sort test 1");
            }

            unsorted = new X509Name("CN=AA + SERIALNUMBER=BBB");

            if (!FromBytes(unsorted.GetEncoded()).ToString().Equals("CN=AA+SERIALNUMBER=BBB"))
            {
                Fail("Failed sort test 2");
            }

            unsorted = new X509Name("SERIALNUMBER=B + CN=AA");

            if (!FromBytes(unsorted.GetEncoded()).ToString().Equals("SERIALNUMBER=B+CN=AA"))
            {
                Fail("Failed sort test 3");
            }

            unsorted = new X509Name("CN=AA + SERIALNUMBER=B");

            if (!FromBytes(unsorted.GetEncoded()).ToString().Equals("SERIALNUMBER=B+CN=AA"))
            {
                Fail("Failed sort test 4");
            }

            //
            // equality tests
            //
            equalityTest(new X509Name("CN=The     Legion"), new X509Name("CN=The Legion"));
            equalityTest(new X509Name("CN=   The Legion"), new X509Name("CN=The Legion"));
            equalityTest(new X509Name("CN=The Legion   "), new X509Name("CN=The Legion"));
            equalityTest(new X509Name("CN=  The     Legion "), new X509Name("CN=The Legion"));
            equalityTest(new X509Name("CN=  the     legion "), new X509Name("CN=The Legion"));

            // # test

            X509Name n1 = new X509Name("SERIALNUMBER=8,O=ABC,CN=ABC Class 3 CA,C=LT");
            X509Name n2 = new X509Name("2.5.4.5=8,O=ABC,CN=ABC Class 3 CA,C=LT");
            X509Name n3 = new X509Name("2.5.4.5=#130138,O=ABC,CN=ABC Class 3 CA,C=LT");

            equalityTest(n1, n2);
            equalityTest(n2, n3);
            equalityTest(n3, n1);

            n1 = new X509Name(true, "2.5.4.5=#130138,CN=SSC Class 3 CA,O=UAB Skaitmeninio sertifikavimo centras,C=LT");
            n2 = new X509Name(true, "SERIALNUMBER=#130138,CN=SSC Class 3 CA,O=UAB Skaitmeninio sertifikavimo centras,C=LT");
            n3 = X509Name.GetInstance(Asn1Object.FromByteArray(Hex.Decode("3063310b3009060355040613024c54312f302d060355040a1326"
                                                                          + "55414220536b6169746d656e696e696f20736572746966696b6176696d6f2063656e74726173311730150603550403130e53534320436c6173732033204341310a30080603550405130138")));

            equalityTest(n1, n2);
            equalityTest(n2, n3);
            equalityTest(n3, n1);

            n1 = new X509Name("SERIALNUMBER=8,O=XX,CN=ABC Class 3 CA,C=LT");
            n2 = new X509Name("2.5.4.5=8,O=,CN=ABC Class 3 CA,C=LT");

            if (n1.Equivalent(n2))
            {
                Fail("empty inequality check failed");
            }

            n1 = new X509Name("SERIALNUMBER=8,O=,CN=ABC Class 3 CA,C=LT");
            n2 = new X509Name("2.5.4.5=8,O=,CN=ABC Class 3 CA,C=LT");

            equalityTest(n1, n2);

            //
            // inequality to sequences
            //
            name1 = new X509Name("CN=The Legion");

            if (name1.Equals(DerSequence.Empty))
            {
                Fail("inequality test with sequence");
            }

            if (name1.Equals(new DerSequence(DerSet.Empty)))
            {
                Fail("inequality test with sequence and set");
            }

            Asn1EncodableVector v = new Asn1EncodableVector(
                new DerObjectIdentifier("1.1"),
                new DerObjectIdentifier("1.1"));

            if (name1.Equals(new DerSequence(new DerSet(new DerSet(v)))))
            {
                Fail("inequality test with sequence and bad set");
            }

//			if (name1.Equals(new DerSequence(new DerSet(new DerSet(v))), true))
//			{
//				Fail("inequality test with sequence and bad set");
//			}
            try
            {
                X509Name.GetInstance(new DerSequence(new DerSet(new DerSet(v))));
                Fail("GetInstance should reject bad sequence");
            }
            catch (ArgumentException)
            {
                //expected
            }

            if (name1.Equals(new DerSequence(new DerSet(DerSequence.Empty))))
            {
                Fail("inequality test with sequence and short sequence");
            }

//			if (name1.Equals(new DerSequence(new DerSet(DerSequence.Empty)), true))
//			{
//				Fail("inequality test with sequence and short sequence");
//			}
            try
            {
                X509Name.GetInstance(new DerSequence(new DerSet(DerSequence.Empty)));
                Fail("GetInstance should reject short sequence");
            }
            catch (ArgumentException)
            {
                //expected
            }

            v = new Asn1EncodableVector(
                new DerObjectIdentifier("1.1"),
                DerSequence.Empty);

            if (name1.Equals(new DerSequence(new DerSet(new DerSequence(v)))))
            {
                Fail("inequality test with sequence and bad sequence");
            }

            if (name1.Equivalent(null))
            {
                Fail("inequality test with null");
            }

            if (name1.Equivalent(null, true))
            {
                Fail("inequality test with null");
            }

            //
            // this is contrived but it checks sorting of sets with equal elements
            //
            unsorted = new X509Name("CN=AA + CN=AA + CN=AA");

            //
            // tagging test - only works if CHOICE implemented
            //

            /*
             * ASN1TaggedObject tag = new DERTaggedObject(false, 1, new X509Name("CN=AA"));
             *
             * if (!tag.isExplicit())
             * {
             *  Fail("failed to explicitly tag CHOICE object");
             * }
             *
             * X509Name name = X509Name.getInstance(tag, false);
             *
             * if (!name.equals(new X509Name("CN=AA")))
             * {
             *  Fail("failed to recover tagged name");
             * }
             */

            DerUtf8String testString = new DerUtf8String("The Legion of the Bouncy Castle");

            byte[] encodedBytes     = testString.GetEncoded();
            string hexEncodedString = "#" + Hex.ToHexString(encodedBytes);

            DerUtf8String converted = (DerUtf8String)
                                      new X509DefaultEntryConverter().GetConvertedValue(
                X509Name.L, hexEncodedString);

            if (!converted.Equals(testString))
            {
                Fail("Failed X509DefaultEntryConverter test");
            }

            //
            // try escaped.
            //
            converted = (DerUtf8String) new X509DefaultEntryConverter().GetConvertedValue(
                X509Name.L, "\\" + hexEncodedString);

            if (!converted.Equals(new DerUtf8String(hexEncodedString)))
            {
                Fail("Failed X509DefaultEntryConverter test got " + converted + " expected: " + hexEncodedString);
            }

            //
            // try a weird value
            //
            X509Name n = new X509Name("CN=\\#nothex#string");

            if (!n.ToString().Equals("CN=\\#nothex#string"))
            {
                Fail("# string not properly escaped.");
            }

            IList vls = n.GetValueList(X509Name.CN);

            if (vls.Count != 1 || !vls[0].Equals("#nothex#string"))
            {
                Fail("Escaped # not reduced properly");
            }

            n = new X509Name("CN=\"a+b\"");

            vls = n.GetValueList(X509Name.CN);
            if (vls.Count != 1 || !vls[0].Equals("a+b"))
            {
                Fail("Escaped + not reduced properly");
            }

            n = new X509Name("CN=a\\+b");

            vls = n.GetValueList(X509Name.CN);
            if (vls.Count != 1 || !vls[0].Equals("a+b"))
            {
                Fail("Escaped + not reduced properly");
            }

            if (!n.ToString().Equals("CN=a\\+b"))
            {
                Fail("+ in string not properly escaped.");
            }

            n = new X509Name("CN=a\\=b");

            vls = n.GetValueList(X509Name.CN);
            if (vls.Count != 1 || !vls[0].Equals("a=b"))
            {
                Fail("Escaped = not reduced properly");
            }

            if (!n.ToString().Equals("CN=a\\=b"))
            {
                Fail("= in string not properly escaped.");
            }

            n = new X509Name("TELEPHONENUMBER=\"+61999999999\"");

            vls = n.GetValueList(X509Name.TelephoneNumber);
            if (vls.Count != 1 || !vls[0].Equals("+61999999999"))
            {
                Fail("telephonenumber escaped + not reduced properly");
            }

            n = new X509Name("TELEPHONENUMBER=\\+61999999999");

            vls = n.GetValueList(X509Name.TelephoneNumber);
            if (vls.Count != 1 || !vls[0].Equals("+61999999999"))
            {
                Fail("telephonenumber escaped + not reduced properly");
            }

            n = new X509Name(@"TELEPHONENUMBER=\+61999999999");

            vls = n.GetValueList(X509Name.TelephoneNumber);
            if (vls.Count != 1 || !vls[0].Equals("+61999999999"))
            {
                Fail("telephonenumber escaped + not reduced properly");
            }
        }
コード例 #12
0
        internal static TrustAnchor FindTrustAnchor(X509Certificate cert, ISet trustAnchors)
        {
            IEnumerator            enumerator             = trustAnchors.GetEnumerator();
            TrustAnchor            trustAnchor            = null;
            AsymmetricKeyParameter asymmetricKeyParameter = null;
            Exception             ex = null;
            X509CertStoreSelector x509CertStoreSelector = new X509CertStoreSelector();

            try
            {
                x509CertStoreSelector.Subject = PkixCertPathValidatorUtilities.GetIssuerPrincipal(cert);
                goto IL_C4;
            }
            catch (IOException innerException)
            {
                throw new Exception("Cannot set subject search criteria for trust anchor.", innerException);
            }
IL_35:
            trustAnchor = (TrustAnchor)enumerator.Current;
            if (trustAnchor.TrustedCert != null)
            {
                if (x509CertStoreSelector.Match(trustAnchor.TrustedCert))
                {
                    asymmetricKeyParameter = trustAnchor.TrustedCert.GetPublicKey();
                }
                else
                {
                    trustAnchor = null;
                }
            }
            else
            {
                if (trustAnchor.CAName != null && trustAnchor.CAPublicKey != null)
                {
                    try
                    {
                        X509Name issuerPrincipal = PkixCertPathValidatorUtilities.GetIssuerPrincipal(cert);
                        X509Name other           = new X509Name(trustAnchor.CAName);
                        if (issuerPrincipal.Equivalent(other, true))
                        {
                            asymmetricKeyParameter = trustAnchor.CAPublicKey;
                        }
                        else
                        {
                            trustAnchor = null;
                        }
                        goto IL_AF;
                    }
                    catch (InvalidParameterException)
                    {
                        trustAnchor = null;
                        goto IL_AF;
                    }
                }
                trustAnchor = null;
            }
IL_AF:
            if (asymmetricKeyParameter != null)
            {
                try
                {
                    cert.Verify(asymmetricKeyParameter);
                }
                catch (Exception ex2)
                {
                    ex          = ex2;
                    trustAnchor = null;
                }
            }
IL_C4:
            if (enumerator.MoveNext() && trustAnchor == null)
            {
                goto IL_35;
            }
            if (trustAnchor == null && ex != null)
            {
                throw new Exception("TrustAnchor found but certificate validation failed.", ex);
            }
            return(trustAnchor);
        }
コード例 #13
0
        private static IList SortCerts(IList certs)
        {
            if (certs.Count < 2)
            {
                return(certs);
            }
            X509Name issuerDN = ((X509Certificate)certs[0]).IssuerDN;
            bool     flag     = true;

            for (int num = 1; num != certs.Count; num++)
            {
                X509Certificate x509Certificate = (X509Certificate)certs[num];
                if (!issuerDN.Equivalent(x509Certificate.SubjectDN, true))
                {
                    flag = false;
                    break;
                }
                issuerDN = ((X509Certificate)certs[num]).IssuerDN;
            }
            if (flag)
            {
                return(certs);
            }
            IList list   = Platform.CreateArrayList(certs.Count);
            IList result = Platform.CreateArrayList(certs);

            for (int i = 0; i < certs.Count; i++)
            {
                X509Certificate x509Certificate2 = (X509Certificate)certs[i];
                bool            flag2            = false;
                X509Name        subjectDN        = x509Certificate2.SubjectDN;
                foreach (X509Certificate x509Certificate3 in certs)
                {
                    if (x509Certificate3.IssuerDN.Equivalent(subjectDN, true))
                    {
                        flag2 = true;
                        break;
                    }
                }
                if (!flag2)
                {
                    list.Add(x509Certificate2);
                    certs.RemoveAt(i);
                }
            }
            if (list.Count > 1)
            {
                return(result);
            }
            for (int num2 = 0; num2 != list.Count; num2++)
            {
                issuerDN = ((X509Certificate)list[num2]).IssuerDN;
                for (int j = 0; j < certs.Count; j++)
                {
                    X509Certificate x509Certificate4 = (X509Certificate)certs[j];
                    if (issuerDN.Equivalent(x509Certificate4.SubjectDN, true))
                    {
                        list.Add(x509Certificate4);
                        certs.RemoveAt(j);
                        break;
                    }
                }
            }
            if (certs.Count > 0)
            {
                return(result);
            }
            return(list);
        }
コード例 #14
0
        public X509CertificateEntry[] GetCertificateChain(
            string alias)
        {
            if (alias == null)
            {
                throw new ArgumentNullException("alias");
            }

            if (!IsKeyEntry(alias))
            {
                return(null);
            }

            X509CertificateEntry c = GetCertificate(alias);

            if (c != null)
            {
                ArrayList cs = new ArrayList();

                while (c != null)
                {
                    X509Certificate      x509c = c.Certificate;
                    X509CertificateEntry nextC = null;

                    Asn1OctetString ext = x509c.GetExtensionValue(X509Extensions.AuthorityKeyIdentifier);
                    if (ext != null)
                    {
                        AuthorityKeyIdentifier id = AuthorityKeyIdentifier.GetInstance(
                            Asn1Object.FromByteArray(ext.GetOctets()));

                        if (id.GetKeyIdentifier() != null)
                        {
                            nextC = (X509CertificateEntry)chainCerts[new CertId(id.GetKeyIdentifier())];
                        }
                    }

                    if (nextC == null)
                    {
                        //
                        // no authority key id, try the Issuer DN
                        //
                        X509Name i = x509c.IssuerDN;
                        X509Name s = x509c.SubjectDN;

                        if (!i.Equivalent(s))
                        {
                            foreach (CertId certId in chainCerts.Keys)
                            {
                                X509CertificateEntry x509CertEntry = (X509CertificateEntry)chainCerts[certId];

                                X509Certificate crt = x509CertEntry.Certificate;

                                X509Name sub = crt.SubjectDN;
                                if (sub.Equivalent(i))
                                {
                                    try
                                    {
                                        x509c.Verify(crt.GetPublicKey());

                                        nextC = x509CertEntry;
                                        break;
                                    }
                                    catch (InvalidKeyException)
                                    {
                                        // TODO What if it doesn't verify?
                                    }
                                }
                            }
                        }
                    }

                    cs.Add(c);
                    if (nextC != c)                     // self signed - end of the chain
                    {
                        c = nextC;
                    }
                    else
                    {
                        c = null;
                    }
                }

                return((X509CertificateEntry[])cs.ToArray(typeof(X509CertificateEntry)));
            }

            return(null);
        }
コード例 #15
0
        public X509CertificateEntry[] GetCertificateChain(string alias)
        {
            if (alias == null)
            {
                throw new ArgumentNullException("alias");
            }
            if (!this.IsKeyEntry(alias))
            {
                return(null);
            }
            X509CertificateEntry x509CertificateEntry = this.GetCertificate(alias);

            if (x509CertificateEntry != null)
            {
                IList list = Platform.CreateArrayList();
                while (x509CertificateEntry != null)
                {
                    X509Certificate      certificate           = x509CertificateEntry.Certificate;
                    X509CertificateEntry x509CertificateEntry2 = null;
                    Asn1OctetString      extensionValue        = certificate.GetExtensionValue(X509Extensions.AuthorityKeyIdentifier);
                    if (extensionValue != null)
                    {
                        AuthorityKeyIdentifier instance = AuthorityKeyIdentifier.GetInstance(Asn1Object.FromByteArray(extensionValue.GetOctets()));
                        if (instance.GetKeyIdentifier() != null)
                        {
                            x509CertificateEntry2 = (X509CertificateEntry)this.chainCerts[new Pkcs12Store.CertId(instance.GetKeyIdentifier())];
                        }
                    }
                    if (x509CertificateEntry2 == null)
                    {
                        X509Name issuerDN  = certificate.IssuerDN;
                        X509Name subjectDN = certificate.SubjectDN;
                        if (!issuerDN.Equivalent(subjectDN))
                        {
                            foreach (Pkcs12Store.CertId key in this.chainCerts.Keys)
                            {
                                X509CertificateEntry x509CertificateEntry3 = (X509CertificateEntry)this.chainCerts[key];
                                X509Certificate      certificate2          = x509CertificateEntry3.Certificate;
                                X509Name             subjectDN2            = certificate2.SubjectDN;
                                if (subjectDN2.Equivalent(issuerDN))
                                {
                                    try
                                    {
                                        certificate.Verify(certificate2.GetPublicKey());
                                        x509CertificateEntry2 = x509CertificateEntry3;
                                        break;
                                    }
                                    catch (InvalidKeyException)
                                    {
                                    }
                                }
                            }
                        }
                    }
                    list.Add(x509CertificateEntry);
                    if (x509CertificateEntry2 != x509CertificateEntry)
                    {
                        x509CertificateEntry = x509CertificateEntry2;
                    }
                    else
                    {
                        x509CertificateEntry = null;
                    }
                }
                X509CertificateEntry[] array = new X509CertificateEntry[list.Count];
                for (int i = 0; i < list.Count; i++)
                {
                    array[i] = (X509CertificateEntry)list[i];
                }
                return(array);
            }
            return(null);
        }
コード例 #16
0
        private static global::System.Collections.IList SortCerts(global::System.Collections.IList certs)
        {
            if (((global::System.Collections.ICollection)certs).get_Count() < 2)
            {
                return(certs);
            }
            X509Name issuerDN = ((X509Certificate)certs.get_Item(0)).IssuerDN;
            bool     flag     = true;

            for (int i = 1; i != ((global::System.Collections.ICollection)certs).get_Count(); i++)
            {
                X509Certificate x509Certificate = (X509Certificate)certs.get_Item(i);
                if (issuerDN.Equivalent(x509Certificate.SubjectDN, inOrder: true))
                {
                    issuerDN = ((X509Certificate)certs.get_Item(i)).IssuerDN;
                    continue;
                }
                flag = false;
                break;
            }
            if (flag)
            {
                return(certs);
            }
            global::System.Collections.IList list   = Platform.CreateArrayList(((global::System.Collections.ICollection)certs).get_Count());
            global::System.Collections.IList result = Platform.CreateArrayList((global::System.Collections.ICollection)certs);
            for (int j = 0; j < ((global::System.Collections.ICollection)certs).get_Count(); j++)
            {
                X509Certificate x509Certificate2 = (X509Certificate)certs.get_Item(j);
                bool            flag2            = false;
                X509Name        subjectDN        = x509Certificate2.SubjectDN;
                {
                    global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)certs).GetEnumerator();
                    try
                    {
                        while (enumerator.MoveNext())
                        {
                            X509Certificate x509Certificate3 = (X509Certificate)enumerator.get_Current();
                            if (x509Certificate3.IssuerDN.Equivalent(subjectDN, inOrder: true))
                            {
                                flag2 = true;
                                break;
                            }
                        }
                    }
                    finally
                    {
                        global::System.IDisposable disposable = enumerator as global::System.IDisposable;
                        if (disposable != null)
                        {
                            disposable.Dispose();
                        }
                    }
                }
                if (!flag2)
                {
                    list.Add((object)x509Certificate2);
                    certs.RemoveAt(j);
                }
            }
            if (((global::System.Collections.ICollection)list).get_Count() > 1)
            {
                return(result);
            }
            for (int k = 0; k != ((global::System.Collections.ICollection)list).get_Count(); k++)
            {
                issuerDN = ((X509Certificate)list.get_Item(k)).IssuerDN;
                for (int l = 0; l < ((global::System.Collections.ICollection)certs).get_Count(); l++)
                {
                    X509Certificate x509Certificate4 = (X509Certificate)certs.get_Item(l);
                    if (issuerDN.Equivalent(x509Certificate4.SubjectDN, inOrder: true))
                    {
                        list.Add((object)x509Certificate4);
                        certs.RemoveAt(l);
                        break;
                    }
                }
            }
            if (((global::System.Collections.ICollection)certs).get_Count() > 0)
            {
                return(result);
            }
            return(list);
        }