コード例 #1
0
        /// <summary>
        /// A PoP cert is a "fake" DeviceID cert containing a challenge subject common name.  To check this there must
        /// be two certs in the chain: the PoP cert and the vendor root cert.
        /// </summary>
        /// <param name="cn"></param>
        /// <returns>PoP cert is properly signed, and the subject common name is correct.</returns>
        internal bool CheckPopCert(string cn)
        {
            X509Name name = null;

            try
            {
                name = new X509Name(cn);
            }
            catch (Exception e)
            {
                Error($"Name {cn} is not a valid X509 Name (e.g. CN=XXXQQQ) {e.ToString()}");
                return(false);
            }
            Notify("Checking PoP Cert");
            bool ok = CheckSigningLinkage();

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

            var certSubject = Certs[0].SubjectDN;

            if (certSubject.ToString() != name.ToString())
            {
                Error($"Cert subject is incorrect.  Should be {name.ToString()} but is {certSubject.ToString()}");
                return(false);
            }
            return(true);
        }
コード例 #2
0
        public void Certificate_SignedWithCA()
        {
            var issuerDN  = new X509Name("cn=ca.test");
            var subjectDN = new X509Name("cn=signedCert");

            var caCert = Certificate.CreateCertificateAuthority(issuerDN.ToString(), m_EffectiveDate, m_ExpirationDate);

            Assert.IsNotNull(caCert);

            var cert = Certificate.CreateSigned(subjectDN.ToString(), m_EffectiveDate, m_ExpirationDate, null, caCert);

            Assert.IsNotNull(cert);
            Assert.AreEqual(subjectDN.ToString(), cert.Subject);
            Assert.AreEqual(caCert.Subject, cert.Issuer);
        }
コード例 #3
0
        private static String FormatX509Name(X500DistinguishedName name)
        {
            Asn1StreamParser parser = new Asn1StreamParser(name.RawData);
            X509Name         _name  = X509Name.GetInstance(parser.ReadObject().ToAsn1Object());

            return(_name.ToString(true, X509Name.RFC1779Symbols));
        }
コード例 #4
0
        private void compositeTest()
        {
            //
            // composite test
            //
            byte[]   enc = Hex.Decode("305e310b300906035504061302415531283026060355040a0c1f546865204c6567696f6e206f662074686520426f756e637920436173746c653125301006035504070c094d656c626f75726e653011060355040b0c0a4173636f742056616c65");
            X509Name n   = X509Name.GetInstance(Asn1Object.FromByteArray(enc));

            if (!n.ToString().Equals("C=AU,O=The Legion of the Bouncy Castle,L=Melbourne+OU=Ascot Vale"))
            {
                Fail("Failed composite to string test got: " + n.ToString());
            }

            IDictionary symbols = X509Name.DefaultSymbols;

            if (!n.ToString(true, symbols).Equals("L=Melbourne+OU=Ascot Vale,O=The Legion of the Bouncy Castle,C=AU"))
            {
                Fail("Failed composite to string test got: " + n.ToString(true, symbols));
            }

            n = new X509Name(true, "L=Melbourne+OU=Ascot Vale,O=The Legion of the Bouncy Castle,C=AU");
            if (!n.ToString().Equals("C=AU,O=The Legion of the Bouncy Castle,L=Melbourne+OU=Ascot Vale"))
            {
                Fail("Failed composite to string reversal test got: " + n.ToString());
            }

            n = new X509Name("C=AU, O=The Legion of the Bouncy Castle, L=Melbourne + OU=Ascot Vale");

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

            aOut.WriteObject(n);

            byte[] enc2 = bOut.ToArray();

            if (!Arrays.AreEqual(enc, enc2))
            {
                Fail("Failed composite string to encoding test");
            }

            //
            // dud name test - handle empty DN without barfing.
            //
            n = new X509Name("C=CH,O=,OU=dummy,[email protected]");

            n = X509Name.GetInstance(Asn1Object.FromByteArray(n.GetEncoded()));
        }
コード例 #5
0
        /// <summary>
        /// Исправить строку X509IssuerName для рукожопых пейсателей из Ланита
        /// </summary>
        /// <param name="x509Name">Исходная строка из сертификата</param>
        /// <returns>Исправленная строка, чтобы ее понимал сервер ГИС ЖКХ</returns>
        public static string ToX509IssuerName(this X509Name x509Name)
        {
            string x509IssuerName = x509Name.ToString();
            var    pairs          = x509IssuerName
                                    .Replace("\\,", "^_^")
                                    .Split(',')
                                    .Select(part => part.Split('='))
                                    .Select(lrParts => new ReplacementPair {
                Key   = lrParts[0],
                Value = lrParts.Length == 2 ? lrParts[1] : string.Empty
            }).ToList();

            var nCount = pairs.Count;
            var result = new StringBuilder();
            var i      = 0;

            // замена
            foreach (var pair in pairs)
            {
                switch (pair.Key.ToLower())
                {
                case "t":
                case "title":
                    pair.Key = "2.5.4.12";
                    break;

                case "g":
                case "givenname":
                    pair.Key = "2.5.4.42";
                    break;

                case "e":
                    pair.Key = "1.2.840.113549.1.9.1";
                    break;

                case "sn":
                case "surname":
                    pair.Key = "2.5.4.4";
                    break;

                case "ou":
                case "orgunit":
                    pair.Key = "2.5.4.11";
                    break;

                case "unstructured-name":
                case "unstructuredname":
                    pair.Key = "1.2.840.113549.1.9.2";
                    break;
                }

                result.Append($"{pair.Key}={pair.Value}{(i != (nCount - 1) ? ", " : string.Empty)}");
                i++;
            }
            return(result.ToString().Replace("^_^", "\\,"));
        }
コード例 #6
0
        /// <summary>
        /// Gets the database command to select the CRL records matching the specified issuer.
        /// </summary>
        /// <remarks>
        /// Gets the database command to select the CRL records matching the specified issuer.
        /// </remarks>
        /// <returns>The database command.</returns>
        /// <param name="issuer">The issuer.</param>
        /// <param name="fields">The fields to return.</param>
        protected override DbCommand GetSelectCommand(X509Name issuer, X509CrlRecordFields fields)
        {
            var query   = "SELECT " + string.Join(", ", GetColumnNames(fields)) + " FROM CRLS ";
            var command = connection.CreateCommand();

            command.CommandText = query + "WHERE ISSUERNAME = @ISSUERNAME";
            command.AddParameterWithValue("@ISSUERNAME", issuer.ToString());
            command.CommandType = CommandType.Text;

            return(command);
        }
コード例 #7
0
        public void Certificate_CreateCertificateAuthority()
        {
            var ca1Subject = new X509Name("cn=ca.one");
            var ca1        = Certificate.CreateCertificateAuthority(ca1Subject.ToString(), m_EffectiveDate, m_ExpirationDate);

            Assert.IsNotNull(ca1);
            Assert.AreEqual(ca1Subject.ToString(), ca1.Subject);
            Assert.AreEqual(ca1Subject.ToString(), ca1.Issuer);

            var ca2Subject = new X509Name("cn=ca.two");

            Uri[] uris = { new Uri("ldap://localhost/[email protected],dc=myhealthisp,dc=com,o=TNT"), new Uri("http://domain.com/file.crl") };
            var   ca2  = Certificate.CreateCertificateAuthority(ca2Subject.ToString(), m_EffectiveDate, m_ExpirationDate, uris.ToList(), ca1);

            Assert.IsNotNull(ca2);
            Assert.AreEqual(ca2Subject.ToString(), ca2.Subject);
            Assert.AreEqual(ca1Subject.ToString(), ca2.Issuer);

            var x = ca2.GetCrlDistributionPoints();
        }
コード例 #8
0
        public void Read_WithValidInput_ReturnsIssuerSerial()
        {
            var directoryName = new X509Name("CN=test");
            var generalNames  = new GeneralNames(
                new BcGeneralName(BcGeneralName.DirectoryName, directoryName));
            var bcIssuerSerial = new BcIssuerSerial(generalNames, new DerInteger(BigInteger.One));
            var bytes          = bcIssuerSerial.GetDerEncoded();

            var issuerSerial = IssuerSerial.Read(bytes);

            Assert.Equal(1, issuerSerial.GeneralNames.Count);
            Assert.Equal(directoryName.ToString(), issuerSerial.GeneralNames[0].DirectoryName.Name);
            Assert.Equal(bcIssuerSerial.Serial.Value.ToByteArray(), issuerSerial.SerialNumber);
        }
コード例 #9
0
        public static String ExtractCommonName(X509Certificate certificate)
        {
            X509Name principal = certificate.SubjectDN;
            Match    m         = PatternCn.Match(principal.ToString());

            if (m.Success)
            {
                return(m.Groups[1].Value);
            }
            else
            {
                throw new InvalidOperationException("Unable to extract the CN attribute from " + principal);
            }
        }
コード例 #10
0
ファイル: Utility.cs プロジェクト: hugocurran/OSCA2
        /// <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);
        }
コード例 #11
0
        private static Name RetriveName(X509Name x509Name)
        {
            Name name = new Name();

            name.isEmpty = x509Name.ToString().Length == 0;
            var commonNameList = x509Name.GetValueList(X509Name.CN);

            if (commonNameList != null && commonNameList.Count != 0)
            {
                name.CommonName = StringUtil.StringToByteArray(commonNameList[0].ToString());
            }

            //todo - add other fields if required
            return(name);
        }
コード例 #12
0
 public TrustAnchor(X509Name caPrincipal, AsymmetricKeyParameter pubKey, byte[] nameConstraints)
 {
     if (caPrincipal == null)
     {
         throw new ArgumentNullException("caPrincipal");
     }
     if (pubKey == null)
     {
         throw new ArgumentNullException("pubKey");
     }
     trustedCert      = null;
     this.caPrincipal = caPrincipal;
     caName           = caPrincipal.ToString();
     this.pubKey      = pubKey;
     setNameConstraints(nameConstraints);
 }
コード例 #13
0
        public void Read_WithDefaultAlgorithmIdentifier_ReturnsEssCertIdV2()
        {
            var directoryName = new X509Name("CN=test");
            var generalNames  = new GeneralNames(
                new BcGeneralName(BcGeneralName.DirectoryName, directoryName));
            var bcIssuerSerial = new BcIssuerSerial(generalNames, new DerInteger(BigInteger.One));
            var hash           = CryptoHashUtility.ComputeHash(HashAlgorithmName.SHA256, Encoding.UTF8.GetBytes("peach"));
            var bcEssCertId    = new BcEssCertIdV2(hash, bcIssuerSerial);
            var bytes          = bcEssCertId.GetDerEncoded();

            var essCertIdV2 = EssCertIdV2.Read(bytes);

            Assert.Equal(Oids.Sha256, essCertIdV2.HashAlgorithm.Algorithm.Value);
            Assert.Equal(1, essCertIdV2.IssuerSerial.GeneralNames.Count);
            Assert.Equal(directoryName.ToString(), essCertIdV2.IssuerSerial.GeneralNames[0].DirectoryName.Name);
            SigningTestUtility.VerifyByteArrays(hash, essCertIdV2.CertificateHash);
            SigningTestUtility.VerifyByteArrays(bcIssuerSerial.Serial.Value.ToByteArray(), essCertIdV2.IssuerSerial.SerialNumber);
        }
コード例 #14
0
ファイル: TrustAnchor.cs プロジェクト: smdx24/CPI-Source-Code
 public TrustAnchor(X509Name caPrincipal, AsymmetricKeyParameter pubKey, byte[] nameConstraints)
 {
     //IL_000e: Unknown result type (might be due to invalid IL or missing references)
     //IL_001c: Unknown result type (might be due to invalid IL or missing references)
     if (caPrincipal == null)
     {
         throw new ArgumentNullException("caPrincipal");
     }
     if (pubKey == null)
     {
         throw new ArgumentNullException("pubKey");
     }
     trustedCert      = null;
     this.caPrincipal = caPrincipal;
     caName           = caPrincipal.ToString();
     this.pubKey      = pubKey;
     setNameConstraints(nameConstraints);
 }
コード例 #15
0
        private string GetResponderName(ResponderID responderId, ref bool byKey)
        {
            DerTaggedObject derTaggedObject = (DerTaggedObject)responderId.ToAsn1Object();

            if (derTaggedObject.TagNo != 1)
            {
                if (derTaggedObject.TagNo != 2)
                {
                    return(null);
                }
                Asn1TaggedObject asn1TaggedObject = (Asn1TaggedObject)responderId.ToAsn1Object();
                Asn1OctetString  asn1OctetString  = (Asn1OctetString)asn1TaggedObject.GetObject();
                byKey = true;
                return(Convert.ToBase64String(asn1OctetString.GetOctets()));
            }
            X509Name instance = X509Name.GetInstance(derTaggedObject.GetObject());

            byKey = false;
            return(instance.ToString());
        }
コード例 #16
0
        protected static IList <string> Extract(X509Name principal, string field)
        {
            if (field == null)
            {
                return(new SingletonList <string>(principal.ToString()));
                // return Arrays.asList(principal.toString());
            }

            var values          = new List <string>();
            var normalizedField = field.Trim().ToLowerInvariant();

            if (!X509Name.DefaultLookup.Contains(normalizedField))
            {
                return(values);
            }

            var oidField = (DerObjectIdentifier)X509Name.DefaultLookup[normalizedField];

            values = principal.GetValueList(oidField).OfType <string>().ToList();
            return(values);
        }
コード例 #17
0
        private MSX509.X509Certificate2 LoadCertificate(X509Name name, MSX509.StoreName storeName, MSX509.StoreLocation location)
        {
            if (certificates_.ContainsKey(name))
            {
                return(certificates_[name]);
            }

            string dn = name.ToString();

            MSX509.X509Store store = new MSX509.X509Store(storeName, location);
            store.Open(MSX509.OpenFlags.ReadOnly);
            var certificates = store.Certificates.Find(MSX509.X509FindType.FindBySubjectDistinguishedName, dn, true);

            store.Close();

            if (certificates.Count <= 0)
            {
                return(null);
            }

            MSX509.X509Certificate2 certificate = certificates[0];
            certificates_[name] = certificate;
            return(certificate);
        }
コード例 #18
0
 private static string Canonicalize(X509Name name)
 {
     return(name.ToString(false, (IDictionary)X509Name.RFC2253Symbols));
 }
コード例 #19
0
 public static string ToX509IssuerName(this X509Name x509Name)
 {
     return(x509Name.ToString().Replace("E=", "1.2.840.113549.1.9.1="));
 }
コード例 #20
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");
            }
        }
コード例 #21
0
        protected override void CompleteWizard()
        {
            // Generate the CSR
            X509Name subjectName =
                new X509Name(string.Format("C={0},ST={1},L={2},O={3},OU={4},CN={5}",
                                           _wizardData.Country,
                                           _wizardData.State,
                                           _wizardData.City,
                                           _wizardData.Organization,
                                           _wizardData.Unit,
                                           _wizardData.CommonName));

            // Generate the private/public keypair
            RsaKeyPairGenerator      kpgen           = new RsaKeyPairGenerator();
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();

            kpgen.Init(new KeyGenerationParameters(new SecureRandom(randomGenerator), _wizardData.Length));
            AsymmetricCipherKeyPair keyPair = kpgen.GenerateKeyPair();
            // Generate the CSR

            Asn1Set attributes = new DerSet(
                new DerSequence(
                    new DerObjectIdentifier("1.3.6.1.4.1.311.13.2.3"),
                    new DerSet(new DerIA5String(Environment.OSVersion.Version.ToString()))),
                new DerSequence(
                    new DerObjectIdentifier("1.3.6.1.4.1.311.21.20"),
                    new DerSet(
                        new DerSequence(
                            new DerInteger(5),
                            new DerUtf8String(Environment.MachineName),
                            new DerUtf8String(Environment.UserName),
                            new DerUtf8String("JexusManager.exe")))),
                new DerSequence(
                    new DerObjectIdentifier("1.3.6.1.4.1.311.13.2.2"),
                    new DerSet(
                        new DerSequence(
                            new DerInteger(1),
                            new DerBmpString("Microsoft RSA SChannel Cryptographic Provider"),
                            new DerBitString(new byte[0])))),
                new DerSequence(
                    new DerObjectIdentifier("1.2.840.113549.1.9.14"),
                    new DerSet(
                        new DerSequence(
                            new DerSequence(
                                new DerObjectIdentifier("2.5.29.15"),
                                new DerBoolean(new byte[] { 0x01 }),
                                new DerOctetString(new byte[] { 0x03, 0x02, 0x04, 0xF0 })),
                            new DerSequence(
                                new DerObjectIdentifier("2.5.29.37"),
                                new DerOctetString(new byte[]
            {
                0x30, 0x0a, 0x06, 0x08,
                0x2b, 0x06, 0x01, 0x05,
                0x05, 0x07, 0x03, 0x01
            })),
                            new DerSequence(
                                new DerObjectIdentifier("1.2.840.113549.1.9.15"),
                                new DerOctetString(new byte[]
            {
                0x30, 0x69, 0x30, 0x0e,
                0x06, 0x08, 0x2a, 0x86,
                0x48, 0x86, 0xf7, 0x0d,
                0x03, 0x02, 0x02, 0x02,
                0x00, 0x80, 0x30, 0x0e,
                0x06, 0x08, 0x2a, 0x86,
                0x48, 0x86, 0xf7, 0x0d,
                0x03, 0x04, 0x02, 0x02,
                0x00, 0x80, 0x30, 0x0b,
                0x06, 0x09, 0x60, 0x86,
                0x48, 0x01, 0x65, 0x03,
                0x04, 0x01, 0x2a, 0x30,
                0x0b, 0x06, 0x09, 0x60,
                0x86, 0x48, 0x01, 0x65,
                0x03, 0x04, 0x01, 0x2d,
                0x30, 0x0b, 0x06, 0x09,
                0x60, 0x86, 0x48, 0x01,
                0x65, 0x03, 0x04, 0x01,
                0x02, 0x30, 0x0b, 0x06,
                0x09, 0x60, 0x86, 0x48,
                0x01, 0x65, 0x03, 0x04,
                0x01, 0x05, 0x30, 0x07,
                0x06, 0x05, 0x2b, 0x0e,
                0x03, 0x02, 0x07, 0x30,
                0x0a, 0x06, 0x08, 0x2a,
                0x86, 0x48, 0x86, 0xf7,
                0x0d, 0x03, 0x07
            })),
                            new DerSequence(
                                new DerObjectIdentifier("2.5.29.14"),
                                new DerOctetString(new byte[]
            {
                0x04, 0x14, 0xaa, 0x25,
                0xd9, 0xa2, 0x39, 0x7e,
                0x49, 0xd2, 0x94, 0x85,
                0x7e, 0x82, 0xa8, 0x8f,
                0x3b, 0x20, 0xf1, 0x4e, 0x65, 0xe5
            }))))));

            var signing = new Asn1SignatureFactory("SHA256withRSA", keyPair.Private);
            Pkcs10CertificationRequest kpGen = new Pkcs10CertificationRequest(signing, subjectName, keyPair.Public, attributes);

            using (var stream = new StreamWriter(_wizardData.FileName))
            {
                stream.WriteLine(_wizardData.UseIisStyle ? "-----BEGIN NEW CERTIFICATE REQUEST-----" : "-----BEGIN CERTIFICATE REQUEST-----");
                stream.WriteLine(Convert.ToBase64String(kpGen.GetDerEncoded(), Base64FormattingOptions.InsertLineBreaks));
                stream.WriteLine(_wizardData.UseIisStyle ? "-----END NEW CERTIFICATE REQUEST-----" : "-----END CERTIFICATE REQUEST-----");
            }

            var        key = DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters)keyPair.Private);
            PrivateKey pvk = new PrivateKey();

            pvk.RSA = new RSACryptoServiceProvider();
            pvk.RSA.ImportParameters(key);

            var file   = DialogHelper.GetPrivateKeyFile(subjectName.ToString());
            var folder = Path.GetDirectoryName(file);

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }

            pvk.Save(file);
        }