Exemplo n.º 1
0
        public static Dictionary <string, List <string> > ParseX509Name(X509Name x509Name)
        {
            if (x509Name == null)
            {
                throw new ArgumentNullException("x509Name");
            }

            Dictionary <string, List <string> > parts = new Dictionary <string, List <string> >();

            IList oidList   = x509Name.GetOidList();
            IList valueList = x509Name.GetValueList();

            for (int i = 0; i < oidList.Count; i++)
            {
                DerObjectIdentifier oid = oidList[i] as DerObjectIdentifier;
                string value            = valueList[i] as string;

                if (!parts.ContainsKey(oid.Id))
                {
                    parts.Add(oid.Id, new List <string>()
                    {
                        value
                    });
                }
                else
                {
                    parts[oid.Id].Add(value);
                }
            }

            return(parts);
        }
        /// <summary>
        /// Gets the X509 subject attribute values from a subject.
        /// </summary>
        /// <param name="subject">The subject.</param>
        /// <returns>
        /// The X509 subject attribute values indexed by the kind of subject attribute.
        /// </returns>
        /// <exception cref="ArgumentNullException"><paramref name="subject"/> is null.</exception>
        public static IReadOnlyDictionary <X509SubjectAttributeKind, string> GetX509SubjectAttributes(
            this X509Name subject)
        {
            new { subject }.Must().NotBeNull();

            var objectIds = subject.GetOidList();
            var values    = subject.GetValueList();

            var result = new Dictionary <X509SubjectAttributeKind, string>();

            for (int x = 0; x < objectIds.Count; x++)
            {
                if ((objectIds[x] is DerObjectIdentifier derId) && (values[x] is string value))
                {
                    if (derId.Id == X509Name.C.Id)
                    {
                        result.Add(X509SubjectAttributeKind.Country, value);
                    }
                    else if (derId.Id == X509Name.O.Id)
                    {
                        result.Add(X509SubjectAttributeKind.Organization, value);
                    }
                    else if (derId.Id == X509Name.OU.Id)
                    {
                        result.Add(X509SubjectAttributeKind.OrganizationalUnit, value);
                    }
                    else if (derId.Id == X509Name.T.Id)
                    {
                        result.Add(X509SubjectAttributeKind.Title, value);
                    }
                    else if (derId.Id == X509Name.CN.Id)
                    {
                        result.Add(X509SubjectAttributeKind.CommonName, value);
                    }
                    else if (derId.Id == X509Name.Street.Id)
                    {
                        result.Add(X509SubjectAttributeKind.Street, value);
                    }
                    else if (derId.Id == X509Name.SerialNumber.Id)
                    {
                        result.Add(X509SubjectAttributeKind.SerialNumber, value);
                    }
                    else if (derId.Id == X509Name.L.Id)
                    {
                        result.Add(X509SubjectAttributeKind.Locality, value);
                    }
                    else if (derId.Id == X509Name.ST.Id)
                    {
                        result.Add(X509SubjectAttributeKind.State, value);
                    }
                }
            }

            return(result);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Checks and reorders a DN to place CN first (default) or last
        /// </summary>
        /// <param name="Name">DN to check</param>
        /// <param name="CNFirst">if set to <c>true</c> [cn first].</param>
        /// <returns>
        /// Reordered DN
        /// </returns>
        public static X509Name OrderDN(X509Name Name, bool CNFirst = true)
        {
            IList oids;

            if (CNFirst)
            {
                oids = Name.GetOidList();
                if (!X509Name.CN.Equals(oids[0]))
                {
                    return(new X509Name(CNFirst, Name.ToString()));
                }
            }
            return(Name);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Adds the distinguished name as certificate subject.
        /// </summary>
        /// <param name="distinguishedName">The distinguished name.</param>
        public void AddName(string distinguishedName)
        {
            var name = new X509Name(distinguishedName);

            var oidList   = name.GetOidList();
            var valueList = name.GetValueList();
            var len       = oidList.Count;

            for (var i = 0; i < len; ++i)
            {
                var id    = (DerObjectIdentifier)oidList[i];
                var value = valueList[i]?.ToString();
                attributes.Add(Tuple.Create(id, value));

                if (id == X509Name.CN)
                {
                    this.commonName = value;
                }
            }
        }
        /// <summary>
        /// Checks if certificate subject contains specified RDNs.
        /// </summary>
        /// <param name="certificate">certificate to check</param>
        /// <returns></returns>
        public bool Match(X509Certificate certificate)
        {
            if (certificate == null)
            {
                return(false);
            }

            IList subjectDnOidList = _subjectDn.GetOidList();
            IList valueList        = _subjectDn.GetValueList();

            for (int i = 0; i < subjectDnOidList.Count; i++)
            {
                if (!Contains(valueList[i], certificate.SubjectDN.GetValueList((DerObjectIdentifier)subjectDnOidList[i])))
                {
                    return(false);
                }
            }

            return(true);
        }
Exemplo n.º 6
0
        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");
            }
        }
Exemplo n.º 7
0
        private XmlElement CreateXadesObject(Org.BouncyCastle.X509.X509Certificate cert)
        {
            X509Name old = cert.SubjectDN;
            X509Name n   = new X509Name(old.GetOidList(), old.GetValueList());

            byte[]     data = n.GetDerEncoded();
            Sha1Digest hash = new Sha1Digest();

            hash.BlockUpdate(data, 0, data.Length);
            byte[] result = new byte[hash.GetDigestSize()];
            hash.DoFinal(result, 0);
            string sCertDigest = Convert.ToBase64String(result);

            string Issuer = cert.IssuerDN.ToString(true, X509Name.RFC2253Symbols);
            string Serial = cert.SerialNumber.LongValue.ToString();


            XmlElement   XmlObject = m_doc.CreateElement(ns_dsig_prefix, "Object", ns_dsig_uri);
            XmlAttribute Id        = m_doc.CreateAttribute("Id");

            Id.Value = "etsi-signed-1-1";
            XmlObject.Attributes.Append(Id);

            XmlElement QualifyingProperties = m_doc.CreateElement(ns_etsi_prefix, "QualifyingProperties", ns_etsi_uri);

            XmlObject.AppendChild(QualifyingProperties);
            XmlAttribute Target = m_doc.CreateAttribute("Target");

            Target.Value = "#signature-1-1";
            QualifyingProperties.Attributes.Append(Target);
            XmlAttribute nsxml = m_doc.CreateAttribute("xmlns:" + ns_etsi_prefix);

            nsxml.Value = ns_etsi_uri;
            QualifyingProperties.Attributes.Append(nsxml);

            XmlElement SignedProperties = m_doc.CreateElement(ns_etsi_prefix, "SignedProperties", ns_etsi_uri);

            QualifyingProperties.AppendChild(SignedProperties);

            XmlElement SignedSignatureProperties = m_doc.CreateElement(ns_etsi_prefix, "SignedSignatureProperties", ns_etsi_uri);

            SignedProperties.AppendChild(SignedSignatureProperties);

            XmlElement SigningTime = m_doc.CreateElement(ns_etsi_prefix, "SigningTime", ns_etsi_uri);

            SignedSignatureProperties.AppendChild(SigningTime);
            SigningTime.AppendChild(m_doc.CreateTextNode(DateTime.UtcNow.ToString("s") + "Z"));

            XmlElement SigningCertificate = m_doc.CreateElement(ns_etsi_prefix, "SigningCertificate", ns_etsi_uri);

            SignedSignatureProperties.AppendChild(SigningCertificate);
            XmlElement Cert = m_doc.CreateElement(ns_etsi_prefix, "Cert", ns_etsi_uri);

            SigningCertificate.AppendChild(Cert);

            XmlElement CertDigest = m_doc.CreateElement(ns_etsi_prefix, "CertDigest", ns_etsi_uri);

            Cert.AppendChild(CertDigest);
            XmlElement DigestMethod = m_doc.CreateElement(ns_etsi_prefix, "DigestMethod", ns_etsi_uri);

            CertDigest.AppendChild(DigestMethod);
            XmlAttribute Algorithm = m_doc.CreateAttribute("Algorithm");

            Algorithm.Value = "http://www.w3.org/2000/09/xmldsig#sha1";
            DigestMethod.Attributes.Append(Algorithm);
            XmlElement DigestValue = m_doc.CreateElement(ns_etsi_prefix, "DigestValue", ns_etsi_uri);

            CertDigest.AppendChild(DigestValue);
            DigestValue.AppendChild(m_doc.CreateTextNode(sCertDigest));


            XmlElement IssuerSerial = m_doc.CreateElement(ns_etsi_prefix, "IssuerSerial", ns_etsi_uri);

            Cert.AppendChild(IssuerSerial);
            XmlElement X509IssuerName = m_doc.CreateElement(ns_dsig_prefix, "X509IssuerName", ns_dsig_uri);

            IssuerSerial.AppendChild(X509IssuerName);
            X509IssuerName.AppendChild(m_doc.CreateTextNode(Issuer));
            XmlElement X509SerialNumber = m_doc.CreateElement(ns_dsig_prefix, "X509SerialNumber", ns_dsig_uri);

            IssuerSerial.AppendChild(X509SerialNumber);
            X509SerialNumber.AppendChild(m_doc.CreateTextNode(Serial));


            XmlElement SignaturePolicyIdentifier = m_doc.CreateElement(ns_etsi_prefix, "SignaturePolicyIdentifier", ns_etsi_uri);

            SignedSignatureProperties.AppendChild(SignaturePolicyIdentifier);
            XmlElement SignaturePolicyImplied = m_doc.CreateElement(ns_etsi_prefix, "SignaturePolicyImplied", ns_etsi_uri);

            SignaturePolicyIdentifier.AppendChild(SignaturePolicyImplied);

            XmlElement SignedDataObjectProperties = m_doc.CreateElement(ns_etsi_prefix, "SignedDataObjectProperties", ns_etsi_uri);

            SignedProperties.AppendChild(SignedDataObjectProperties);
            XmlElement DataObjectFormat = m_doc.CreateElement(ns_etsi_prefix, "DataObjectFormat", ns_etsi_uri);

            SignedDataObjectProperties.AppendChild(DataObjectFormat);
            XmlAttribute ObjectReference = m_doc.CreateAttribute("ObjectReference");

            ObjectReference.Value = "#reference-1-1";
            DataObjectFormat.Attributes.Append(ObjectReference);

            XmlElement MimeType = m_doc.CreateElement(ns_etsi_prefix, "MimeType", ns_etsi_uri);

            DataObjectFormat.AppendChild(MimeType);
            MimeType.AppendChild(m_doc.CreateTextNode("text/xml"));

            return(XmlObject);
        }