예제 #1
0
        public static X509Certificate2 CreateSelfSignedCertificate(string subjectName, string[] extendedKeyUsageOids = null)
        {
            using var rsa = RSA.Create(2048);
            var request = new CertificateRequest($"CN={subjectName}", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);

            request.CertificateExtensions.Add(
                new X509BasicConstraintsExtension(false, false, 0, true));

            request.CertificateExtensions.Add(
                new X509SubjectKeyIdentifierExtension(request.PublicKey, false));

            request.CertificateExtensions.Add(new X509KeyUsageExtension(KeyUsageFlags, false));

            var extendedKeyUsages = new OidCollection();

            foreach (var oid in extendedKeyUsageOids ?? Array.Empty <string>())
            {
                extendedKeyUsages.Add(new Oid(oid));
            }

            var extension = new X509EnhancedKeyUsageExtension(extendedKeyUsages, false);

            request.CertificateExtensions.Add(extension);

            var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.Subtract(TimeSpan.FromDays(10)), DateTimeOffset.UtcNow.AddYears(5));

            return(certificate);
        }
예제 #2
0
            /// <summary>
            /// Check if the given certificate contains the given enhanced key usage Oid
            /// </summary>
            /// <param name="certificate">X509 certificate</param>
            /// <param name="enhancedKeyOid">the oid to check if it is specified</param>
            /// <returns><c>true</c> if the oid is specified as an enhanced key usage; otherwise <c>false</c></returns>
            private static bool ContainsEnhancedKeyUsage(X509Certificate certificate, string enhancedKeyOid)
            {
                X509Certificate2 cert2 = certificate as X509Certificate2;

                if (cert2 == null)
                {
                    cert2 = new X509Certificate2(certificate);
                }

                foreach (X509Extension extension in cert2.Extensions)
                {
                    if (extension is X509EnhancedKeyUsageExtension)
                    {
                        X509EnhancedKeyUsageExtension keyUsage = (X509EnhancedKeyUsageExtension)extension;
                        foreach (System.Security.Cryptography.Oid oid in keyUsage.EnhancedKeyUsages)
                        {
                            if (oid.Value == enhancedKeyOid)
                            {
                                return(true);
                            }
                        }
                    }
                }

                return(false);
            }
예제 #3
0
        private static void SimpleSelfSign(CertificateRequest request, string expectedKeyOid)
        {
            request.CertificateExtensions.Add(
                new X509EnhancedKeyUsageExtension(new OidCollection {
                new Oid("1.3.6.1.5.5.7.3.1")
            }, false));

            DateTimeOffset now = DateTimeOffset.UtcNow;

            using (X509Certificate2 newCert = request.CreateSelfSigned(now, now.AddDays(90)))
            {
                Assert.True(newCert.HasPrivateKey);

                Assert.Equal("CN=localhost", newCert.Subject);
                Assert.Equal(expectedKeyOid, newCert.GetKeyAlgorithm());
                Assert.Equal(1, newCert.Extensions.Count);

                X509Extension extension = newCert.Extensions["2.5.29.37"];
                Assert.NotNull(extension);

                X509EnhancedKeyUsageExtension ekuExtension = (X509EnhancedKeyUsageExtension)extension;
                Assert.Equal(1, ekuExtension.EnhancedKeyUsages.Count);
                Assert.Equal("1.3.6.1.5.5.7.3.1", ekuExtension.EnhancedKeyUsages[0].Value);

                // Ideally the serial number is 8 bytes.  But maybe it accidentally started with 0x00 (1/256),
                // or 0x0000 (1/32768), or even 0x00000000 (1/4 billion). But that's where we draw the line.
                string serialNumber = newCert.SerialNumber;
                // Using this construct so the value gets printed in a failure, instead of just the length.
                Assert.True(
                    serialNumber.Length >= 8 && serialNumber.Length <= 18,
                    $"Serial number ({serialNumber}) should be between 4 and 9 bytes, inclusive");
            }
        }
예제 #4
0
        public static bool IsAgentCertificate(X509Certificate2 cert)
        {
            if (!cert.HasPrivateKey)
            {
                return(false);
            }

            // Enhanced Key Usage is 2.5.29.37
            X509EnhancedKeyUsageExtension ekuExtension = null;

            foreach (X509Extension extension in cert.Extensions)
            {
                if (extension.Oid.Value == "2.5.29.37")
                {
                    ekuExtension = (X509EnhancedKeyUsageExtension)extension;
                }
            }

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

            // Certificate Request Agent is 1.3.6.1.4.1.311.20.2.1
            foreach (Oid oid in ekuExtension.EnhancedKeyUsages)
            {
                if (oid.Value == "1.3.6.1.4.1.311.20.2.1")
                {
                    return(true);
                }
            }

            return(false);
        }
예제 #5
0
        public void WrongAsnEncodedData()
        {
            AsnEncodedData aed = new AsnEncodedData(new byte[0]);
            X509EnhancedKeyUsageExtension eku = new X509EnhancedKeyUsageExtension(new OidCollection(), true);

            eku.CopyFrom(aed);              // note: not the same behaviour than using the constructor!
        }
예제 #6
0
        public static bool CanAuthenticateServer(X509Certificate2 certificate)
        {
            bool flag = false;

            foreach (X509Extension extension in certificate.Extensions)
            {
                if (string.Equals(extension.Oid.Value, "2.5.29.37", StringComparison.Ordinal))
                {
                    flag = true;
                    X509EnhancedKeyUsageExtension extension2 = extension as X509EnhancedKeyUsageExtension;
                    if (extension2 != null)
                    {
                        OidEnumerator enumerator = extension2.EnhancedKeyUsages.GetEnumerator();
                        while (enumerator.MoveNext())
                        {
                            if (string.Equals(enumerator.Current.Value, "1.3.6.1.5.5.7.3.1", StringComparison.Ordinal))
                            {
                                return(true);
                            }
                        }
                    }
                }
            }
            return(!flag);
        }
예제 #7
0
        public void WrongExtension_X509EnhancedKeyUsageExtension()
        {
            X509EnhancedKeyUsageExtension eku = new X509EnhancedKeyUsageExtension();
            X509KeyUsageExtension         ku  = new X509KeyUsageExtension();

            ku.CopyFrom(eku);
        }
예제 #8
0
        public void ConstructorOidCollection()
        {
            OidCollection oc = new OidCollection();
            X509EnhancedKeyUsageExtension eku = new X509EnhancedKeyUsageExtension(oc, true);

            Assert.AreEqual("30-00", BitConverter.ToString(eku.RawData), "RawData");
            Assert.AreEqual(0, eku.EnhancedKeyUsages.Count, "Count 0");
            // FIXME: Don't expect that FriendlyName is English. This test fails under non-English Windows.
            //Assert.AreEqual ("Information Not Available", eku.Format (true), "Format(true)");
            //Assert.AreEqual ("Information Not Available", eku.Format (false), "Format(false)");
            oc.Add(new Oid("1.2.3.4"));
            Assert.AreEqual(0, eku.EnhancedKeyUsages.Count, "Count still 0");
            int n = eku.EnhancedKeyUsages.Add(new Oid("1.2.3"));

            Assert.AreEqual(0, n, "Add");
            Assert.AreEqual(0, eku.EnhancedKeyUsages.Count, "Count again 0");                   // readonly!
            Assert.AreEqual(1, oc.Count, "Count 1 - oc");
            Assert.AreEqual("1.2.3.4", oc [0].Value, "Value - oc");

            oc.Add(new Oid("1.3.6.1.5.5.7.3.1"));
            eku = new X509EnhancedKeyUsageExtension(oc, true);
            Assert.AreEqual(2, eku.EnhancedKeyUsages.Count, "Count 2");
            Assert.AreEqual("1.2.3.4", eku.EnhancedKeyUsages[0].Value, "Value - 1");
            Assert.AreEqual("1.3.6.1.5.5.7.3.1", eku.EnhancedKeyUsages[1].Value, "Value - 2");
            // FIXME: Don't expect that FriendlyName is English. This test fails under non-English Windows.
            //Assert.AreEqual ("Unknown Key Usage (1.2.3.4)" + Environment.NewLine + "Server Authentication (1.3.6.1.5.5.7.3.1)" + Environment.NewLine,
            //	eku.Format (true), "Format(true)");
            //Assert.AreEqual ("Unknown Key Usage (1.2.3.4), Server Authentication (1.3.6.1.5.5.7.3.1)", eku.Format (false), "Format(false)");
        }
예제 #9
0
        public void Certificate_CSR_SelfSigned_DomainBound()
        {
            X500DistinguishedName   dn      = new X500DistinguishedName("cn=domain.com,o=TNT,c=US");
            AsymmetricCipherKeyPair keyPair = Certificate.CreateRSAKeyPair();
            Extensions extensions           = new Extensions();

            extensions.Add(new TNT.Cryptography.Extension.KeyUsage(KeyUsage.KeyEncipherment | KeyUsage.DigitalSignature));
            extensions.Add(new TNT.Cryptography.Extension.SubjectAlternativeName(new GeneralName(GeneralName.DnsName, dn.Name.Split(',')[0].Split('=')[1])));
            extensions.Add(new TNT.Cryptography.Extension.ExtendedKeyUsage(KeyPurposeID.IdKPEmailProtection));
            extensions.Add(new TNT.Cryptography.Extension.SubjectKeyIdentifier(keyPair.Public));
            extensions.Add(new TNT.Cryptography.Extension.BasicConstraints(new BasicConstraints(false)));
            List <Uri> uris = new List <Uri>(new Uri[] { new Uri("http://domain1.com"), new Uri("http://domain2.com") });

            extensions.Add(new TNT.Cryptography.Extension.CrlDistributionPoints(uris));

            Pkcs10CertificationRequest csr  = Certificate.CreateCertificationRequest(dn.Name, keyPair, extensions);
            X509Certificate2           cert = Certificate.CreateCertificate(csr, keyPair, m_EffectiveDate, m_ExpirationDate);

            System.Security.Cryptography.X509Certificates.X509Extension subAltNameEx = cert.Extensions[1];
            X509EnhancedKeyUsageExtension enhancedKUEx      = cert.Extensions[2] as X509EnhancedKeyUsageExtension;
            X509BasicConstraintsExtension basicConstraintEx = cert.Extensions[4] as X509BasicConstraintsExtension;

            enhancedKUEx = cert.GetEnhancedKeyUsage();

            Assert.AreEqual("DNS Name=domain.com", subAltNameEx.Format(false));
            Assert.AreEqual(KeyPurposeID.IdKPEmailProtection.Id, enhancedKUEx.EnhancedKeyUsages[0].Value);
            Assert.IsFalse(basicConstraintEx.CertificateAuthority);
            Assert.AreEqual("C=US, O=TNT, CN=domain.com", cert.Issuer);
            Assert.AreEqual("C=US, O=TNT, CN=domain.com", cert.Subject);

            File.WriteAllBytes("CSR_SelfSigned_DomainBound.cer", cert.Export(X509ContentType.Cert));
        }
예제 #10
0
        public void WrongExtension_X509Extension_KeyUsages()
        {
            X509Extension ex = new X509Extension("1.2.3", new byte[0], true);
            X509EnhancedKeyUsageExtension eku = new X509EnhancedKeyUsageExtension();

            eku.CopyFrom(ex);
            Assert.AreEqual(0, eku.EnhancedKeyUsages.Count, "EnhancedKeyUsages");
        }
예제 #11
0
        /// <summary>
        /// Metodo para escribir el certificado de seguridad
        /// </summary>
        /// <param name="xCertificate"></param>
        ///<remarks>
        /// Autor:          José Faustino Posas
        /// Company:        Ssoft Colombia
        /// Fecha:          2012-01-16
        /// -------------------
        /// Control de Cambios
        /// -------------------
        /// Autor:
        /// Fecha:
        /// Descripción:
        /// </remarks>
        public string setCertificateWriten(X509Certificate2 xCertificate)
        {
            string sCertificate = null;

            try
            {
                X509Certificate2   objCert   = xCertificate; //Acá tenemos que poner el certificado
                StringBuilder      objSB     = new StringBuilder("Detalle del certificado: \n\n");
                SymmetricAlgorithm algoritmo = SymmetricAlgorithm.Create("Rijndael");

                //Detalle
                objSB.AppendLine("Persona = " + objCert.Subject);
                objSB.AppendLine("Emisor = " + objCert.Issuer);
                objSB.AppendLine("Válido desde = " + objCert.NotBefore.ToString());
                objSB.AppendLine("Válido hasta = " + objCert.NotAfter.ToString());
                objSB.AppendLine("Tamaño de la clave = " + objCert.PublicKey.Key.KeySize.ToString());
                objSB.AppendLine("Valor de la clave = " + objCert.GetPublicKeyString().ToString());
                objSB.AppendLine("Algoritmo de la clave = " + objCert.GetKeyAlgorithm().ToString());
                objSB.AppendLine("Número de serie = " + objCert.SerialNumber);
                objSB.AppendLine("Hash = " + objCert.Thumbprint);
                //Extensiones
                objSB.AppendLine("\nExtensiones:\n");
                foreach (X509Extension objExt in objCert.Extensions)
                {
                    objSB.AppendLine(objExt.Oid.FriendlyName + " (" + objExt.Oid.Value + ')');
                    if (objExt.Oid.FriendlyName == "Key Usage")
                    {
                        X509KeyUsageExtension ext = (X509KeyUsageExtension)objExt;
                        objSB.AppendLine("    " + ext.KeyUsages);
                    }
                    if (objExt.Oid.FriendlyName == "Basic Constraints")
                    {
                        X509BasicConstraintsExtension ext = (X509BasicConstraintsExtension)objExt;
                        objSB.AppendLine("    " + ext.CertificateAuthority);
                        objSB.AppendLine("    " + ext.HasPathLengthConstraint);
                        objSB.AppendLine("    " + ext.PathLengthConstraint);
                    }
                    if (objExt.Oid.FriendlyName == "Subject Key Identifier")
                    {
                        X509SubjectKeyIdentifierExtension ext = (X509SubjectKeyIdentifierExtension)objExt;
                        objSB.AppendLine("    " + ext.SubjectKeyIdentifier);
                    }
                    if (objExt.Oid.FriendlyName == "Enhanced Key Usage") //2.5.29.37
                    {
                        X509EnhancedKeyUsageExtension ext = (X509EnhancedKeyUsageExtension)objExt;
                        OidCollection objOids             = ext.EnhancedKeyUsages;
                        foreach (Oid oid in objOids)
                        {
                            objSB.AppendLine("    " + oid.FriendlyName + " (" + oid.Value + ')');
                        }
                    }
                }
                sCertificate = objSB.ToString();
                //Debug.Print(objSB.ToString());
            }
            catch { }
            return(sCertificate);
        }
예제 #12
0
        public X509Certificate2 CreateAspNetCoreHttpsDevelopmentCertificate(DateTimeOffset notBefore, DateTimeOffset notAfter, string subjectOverride, DiagnosticInformation diagnostics = null)
        {
            var subject    = new X500DistinguishedName(subjectOverride ?? LocalhostHttpsDistinguishedName);
            var extensions = new List <X509Extension>();
            var sanBuilder = new SubjectAlternativeNameBuilder();

            sanBuilder.AddDnsName(LocalhostHttpsDnsName);

            var keyUsage         = new X509KeyUsageExtension(X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature, critical: true);
            var enhancedKeyUsage = new X509EnhancedKeyUsageExtension(
                new OidCollection()
            {
                new Oid(
                    ServerAuthenticationEnhancedKeyUsageOid,
                    ServerAuthenticationEnhancedKeyUsageOidFriendlyName)
            },
                critical: true);

            var basicConstraints = new X509BasicConstraintsExtension(
                certificateAuthority: false,
                hasPathLengthConstraint: false,
                pathLengthConstraint: 0,
                critical: true);

            byte[] bytePayload;

            if (AspNetHttpsCertificateVersion != 0)
            {
                bytePayload    = new byte[1];
                bytePayload[0] = (byte)AspNetHttpsCertificateVersion;
            }
            else
            {
                bytePayload = Encoding.ASCII.GetBytes(AspNetHttpsOidFriendlyName);
            }

            var aspNetHttpsExtension = new X509Extension(
                new AsnEncodedData(
                    new Oid(AspNetHttpsOid, AspNetHttpsOidFriendlyName),
                    bytePayload),
                critical: false);

            extensions.Add(basicConstraints);
            extensions.Add(keyUsage);
            extensions.Add(enhancedKeyUsage);
            extensions.Add(sanBuilder.Build(critical: true));
            extensions.Add(aspNetHttpsExtension);

            var certificate = CreateSelfSignedCertificate(subject, extensions, notBefore, notAfter);

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                certificate.FriendlyName = AspNetHttpsOidFriendlyName;
            }

            return(certificate);
        }
예제 #13
0
        void decodeUsages(Asn1Reader asn)
        {
            var eku = new X509EnhancedKeyUsageExtension(new AsnEncodedData(asn.GetTagRawData()), false);

            foreach (Oid usage in eku.EnhancedKeyUsages)
            {
                _usages.Add(usage);
            }
        }
예제 #14
0
        public void ConstructorAsnEncodedData_BadAsn()
        {
            AsnEncodedData aed = new AsnEncodedData("1.2.3", new byte[0]);
            X509EnhancedKeyUsageExtension eku = new X509EnhancedKeyUsageExtension(aed, true);

            Assert.AreEqual(String.Empty, eku.Format(true), "Format(true)");
            Assert.AreEqual(String.Empty, eku.Format(false), "Format(false)");
            OidCollection oc = eku.EnhancedKeyUsages;
        }
            // Adapted to System 2.0+ from TlsServerCertificate.cs
            //------------------------------
            // Note: this method only works for RSA certificates
            // DH certificates requires some changes - does anyone use one ?
            private static bool CheckCertificateUsage(X509Certificate2 cert)
            {
                try
                {
                    // certificate extensions are required for this
                    // we "must" accept older certificates without proofs
                    if (cert.Version < 3)
                    {
                        return(true);
                    }

                    X509KeyUsageExtension         kux = (cert.Extensions["2.5.29.15"] as X509KeyUsageExtension);
                    X509EnhancedKeyUsageExtension eku = (cert.Extensions["2.5.29.37"] as X509EnhancedKeyUsageExtension);
                    if (kux != null && eku != null)
                    {
                        // RFC3280 states that when both KeyUsageExtension and
                        // ExtendedKeyUsageExtension are present then BOTH should
                        // be valid
                        if ((kux.KeyUsages & s_flags) == 0)
                        {
                            return(false);
                        }
                        return(eku.EnhancedKeyUsages["1.3.6.1.5.5.7.3.1"] != null || eku.EnhancedKeyUsages["2.16.840.1.113730.4.1"] != null);
                    }
                    else if (kux != null)
                    {
                        return((kux.KeyUsages & s_flags) != 0);
                    }
                    else if (eku != null)
                    {
                        // Server Authentication (1.3.6.1.5.5.7.3.1) or
                        // Netscape Server Gated Crypto (2.16.840.1.113730.4)
                        return(eku.EnhancedKeyUsages["1.3.6.1.5.5.7.3.1"] != null || eku.EnhancedKeyUsages["2.16.840.1.113730.4.1"] != null);
                    }

                    // last chance - try with older (deprecated) Netscape extensions
                    X509Extension ext = cert.Extensions["2.16.840.1.113730.1.1"];
                    if (ext != null)
                    {
                        string text = ext.NetscapeCertType(false);
                        return(text.IndexOf("SSL Server Authentication", StringComparison.Ordinal) != -1);
                    }
                    return(true);
                }
                catch (Exception e)
                {
#if SSHARP
                    ErrorLog.Error("ERROR processing certificate: {0}", e);
                    ErrorLog.Error("Please, report this problem to the Mono team");
#else
                    Console.Error.WriteLine("ERROR processing certificate: {0}", e);
                    Console.Error.WriteLine("Please, report this problem to the Mono team");
#endif
                    return(false);
                }
            }
예제 #16
0
 internal string EnhancedKeyUsageExtension(bool multiLine)
 {
     try {
         X509EnhancedKeyUsageExtension eku = new X509EnhancedKeyUsageExtension(this, false);
         return(eku.ToString(multiLine));
     }
     catch {
         return(String.Empty);
     }
 }
예제 #17
0
        public X509Certificate2Collection GetCertificates()
        {
            X509Certificate2Collection certs = new X509Certificate2Collection();
            X509Store certificateStore       = new X509Store(StoreName.My, StoreLocation.CurrentUser);

            try
            {
                certificateStore.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
                foreach (X509Certificate2 certificate in certificateStore.Certificates)
                {
                    if (certificate.HasPrivateKey)
                    {
                        bool digitalSignatureUsage     = false;
                        bool clientAuthEnhancedUsage   = false;
                        bool enhancedKeyUsageSupported = false;

                        foreach (X509Extension extension in certificate.Extensions)
                        {
                            X509KeyUsageExtension keyUsage = extension as X509KeyUsageExtension;
                            if (keyUsage != null)
                            {
                                digitalSignatureUsage = (keyUsage.KeyUsages & X509KeyUsageFlags.DigitalSignature) != 0;
                            }
                            else
                            {
                                X509EnhancedKeyUsageExtension enhancedKeyUsage = extension as X509EnhancedKeyUsageExtension;
                                if (enhancedKeyUsage != null && enhancedKeyUsage.EnhancedKeyUsages != null)
                                {
                                    enhancedKeyUsageSupported = true;
                                    foreach (var oid in enhancedKeyUsage.EnhancedKeyUsages)
                                    {
                                        if (oid.Value == OidClientAuthValue)
                                        {
                                            clientAuthEnhancedUsage = true;
                                            break;
                                        }
                                    }
                                }
                            }
                        }

                        if (digitalSignatureUsage && (!enhancedKeyUsageSupported || clientAuthEnhancedUsage))
                        {
                            certs.Add(certificate);
                        }
                    }
                }
            }
            finally
            {
                certificateStore.Dispose();
            }

            return(certs);
        }
예제 #18
0
        private X509Certificate2 _GetSelfSignedCert(string subjectName)
        {
            var keyParam = new CngKeyCreationParameters
            {
                ExportPolicy       = CngExportPolicies.AllowExport,
                KeyCreationOptions = CngKeyCreationOptions.MachineKey | CngKeyCreationOptions.OverwriteExistingKey,
                KeyUsage           = CngKeyUsages.AllUsages,
                Provider           = CngProvider.MicrosoftSoftwareKeyStorageProvider,
            };

            keyParam.Parameters.Add(new CngProperty("Length", BitConverter.GetBytes(2048), CngPropertyOptions.None));

            CngKey key;

            try
            {
                key = CngKey.Create(CngAlgorithm2.Rsa, Guid.NewGuid().ToString(), keyParam);
            }
            catch (PlatformNotSupportedException)
            {
                try
                {
                    key = CngKey.Create(CngAlgorithm2.Aes, Guid.NewGuid().ToString(), keyParam);
                }
                catch (PlatformNotSupportedException)
                {
                    return(null);
                }
            }

            X509CertificateCreationParameters param = new X509CertificateCreationParameters(new X500DistinguishedName(subjectName))
            {
                SubjectName = new X500DistinguishedName(subjectName),
                EndTime     = DateTime.Today.AddYears(20) //,SignatureAlgorithm = X509CertificateSignatureAlgorithm.RsaSha512
            };

            OidCollection oc = new OidCollection {
                new Oid("1.3.6.1.5.5.7.3.1")
            };
            X509Extension eku = new X509EnhancedKeyUsageExtension(oc, true);

            param.Extensions.Add(eku);

            param.TakeOwnershipOfKey = true;

            byte[] rawData = key.CreateSelfSignedCertificate(param).Export(X509ContentType.Pfx, "");
            var    cert    = new X509Certificate2(rawData, "", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet)
            {
                FriendlyName = _RuleName + " Server Certificate"
            };

            return(cert);
        }
예제 #19
0
파일: sample.cs 프로젝트: ruo2012/samples-1
    public static void Main()
    {
        try
        {
            X509Store store = new X509Store("MY", StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);

            X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;
            for (int i = 0; i < collection.Count; i++)
            {
                foreach (X509Extension extension in collection[i].Extensions)
                {
                    Console.WriteLine(extension.Oid.FriendlyName + "(" + extension.Oid.Value + ")");


                    if (extension.Oid.FriendlyName == "Key Usage")
                    {
                        X509KeyUsageExtension ext = (X509KeyUsageExtension)extension;
                        Console.WriteLine(ext.KeyUsages);
                    }

                    if (extension.Oid.FriendlyName == "Basic Constraints")
                    {
                        X509BasicConstraintsExtension ext = (X509BasicConstraintsExtension)extension;
                        Console.WriteLine(ext.CertificateAuthority);
                        Console.WriteLine(ext.HasPathLengthConstraint);
                        Console.WriteLine(ext.PathLengthConstraint);
                    }

                    if (extension.Oid.FriendlyName == "Subject Key Identifier")
                    {
                        X509SubjectKeyIdentifierExtension ext = (X509SubjectKeyIdentifierExtension)extension;
                        Console.WriteLine(ext.SubjectKeyIdentifier);
                    }

                    if (extension.Oid.FriendlyName == "Enhanced Key Usage")
                    {
                        X509EnhancedKeyUsageExtension ext = (X509EnhancedKeyUsageExtension)extension;
                        OidCollection oids = ext.EnhancedKeyUsages;
                        foreach (Oid oid in oids)
                        {
                            Console.WriteLine(oid.FriendlyName + "(" + oid.Value + ")");
                        }
                    }
                }
            }
            store.Close();
        }
        catch (CryptographicException)
        {
            Console.WriteLine("Information could not be written out for this certificate.");
        }
    }
예제 #20
0
        private void LoadCerts()
        {
            X509Store x509Store = new X509Store(StoreName.My, StoreLocation.CurrentUser);

            x509Store.Open(OpenFlags.ReadOnly);
            X509Certificate2Enumerator enumerator = x509Store.Certificates.GetEnumerator();

            while (enumerator.MoveNext())
            {
                X509Certificate2 current = enumerator.Current;
                if (true) //!(current.GetKeyAlgorithm() != "1.2.643.2.2.19"))
                {
                    if (current.HasPrivateKey)
                    {
                        X509EnhancedKeyUsageExtension x509EnhancedKeyUsageExtension = current.Extensions["2.5.29.37"] as X509EnhancedKeyUsageExtension;
                        if (true)// x509EnhancedKeyUsageExtension != null)
                        {
                            //int num = 0;
                            //string sEKU = "";
                            //OidEnumerator enumerator2 = x509EnhancedKeyUsageExtension.EnhancedKeyUsages.GetEnumerator();
                            //while (enumerator2.MoveNext())
                            //{
                            //    Oid current2 = enumerator2.Current;
                            //    if (this.OidToString(current2.Value) != "Не определен")
                            //    {
                            //        sEKU = current2.Value;
                            //        num++;
                            //    }
                            //}
                            //Regex regex = new Regex("\nCN=(.*)\n");
                            //string sName = current.SubjectName.Name;
                            //Match match = regex.Match("\n" + current.SubjectName.Format(true).Replace("\r", "") + "\n");
                            //if (match.Success)
                            //{
                            //    sName = match.Groups[1].Value;
                            //}
                            cbCerts.Items.Add(current);

                            //item = default(UserSelectForm.info);
                            //item.sName = sName;
                            //item.cert = current;
                            //item.sEMail = UserSelectForm.GetEMail(current.SubjectName.Format(true));
                            //item.sEKU = sEKU;
                            //item.dtStartDate = current.NotBefore.ToLocalTime();
                            //item.dtEndDate = current.NotAfter.ToLocalTime();
                            //item.bValid = Program.ValidateCertificate(this.log, current, "^.+\\.1\\.3\\..+$", true, out item.sTooltip);
                            //this.l.Add(item);
                        }
                    }
                }
            }
            x509Store.Close();
        }
예제 #21
0
        public void ConstructorEmpty()
        {
            X509EnhancedKeyUsageExtension eku = new X509EnhancedKeyUsageExtension();

            Assert.IsFalse(eku.Critical, "Critical");
            Assert.IsNull(eku.RawData, "RawData");
            Assert.AreEqual(oid, eku.Oid.Value, "Oid.Value");
            // FIXME: Don't expect that FriendlyName is English. This test fails under non-English Windows.
            //Assert.AreEqual (fname, eku.Oid.FriendlyName, "Oid.FriendlyName");
            Assert.AreEqual(String.Empty, eku.Format(true), "Format(true)");
            Assert.AreEqual(String.Empty, eku.Format(false), "Format(false)");
        }
예제 #22
0
        public static void VerifyCACert(string subject, X509Certificate2 cert)
        {
            Assert.NotNull(cert);
            Assert.False(cert.HasPrivateKey);
            Assert.True(Utils.CompareDistinguishedName(subject, cert.Subject));
            Assert.True(Utils.CompareDistinguishedName(subject, cert.Issuer));

            // test basic constraints
            var constraints = FindExtension <X509BasicConstraintsExtension>(cert);

            Assert.NotNull(constraints);
            Assert.True(constraints.Critical);
            Assert.True(constraints.CertificateAuthority);
            Assert.True(constraints.HasPathLengthConstraint);

            // key usage
            var keyUsage = FindExtension <X509KeyUsageExtension>(cert);

            Assert.NotNull(keyUsage);
            Assert.True(keyUsage.Critical);
            Assert.True((keyUsage.KeyUsages & X509KeyUsageFlags.CrlSign) == X509KeyUsageFlags.CrlSign);
            Assert.True((keyUsage.KeyUsages & X509KeyUsageFlags.DataEncipherment) == 0);
            Assert.True((keyUsage.KeyUsages & X509KeyUsageFlags.DecipherOnly) == 0);
            Assert.True((keyUsage.KeyUsages & X509KeyUsageFlags.DigitalSignature) == X509KeyUsageFlags.DigitalSignature);
            Assert.True((keyUsage.KeyUsages & X509KeyUsageFlags.EncipherOnly) == 0);
            Assert.True((keyUsage.KeyUsages & X509KeyUsageFlags.KeyAgreement) == 0);
            Assert.True((keyUsage.KeyUsages & X509KeyUsageFlags.KeyCertSign) == X509KeyUsageFlags.KeyCertSign);
            Assert.True((keyUsage.KeyUsages & X509KeyUsageFlags.KeyEncipherment) == 0);
            Assert.True((keyUsage.KeyUsages & X509KeyUsageFlags.NonRepudiation) == 0);

            // enhanced key usage
            X509EnhancedKeyUsageExtension enhancedKeyUsage = FindExtension <X509EnhancedKeyUsageExtension>(cert);

            Assert.Null(enhancedKeyUsage);

            // test for authority key
            X509AuthorityKeyIdentifierExtension authority = FindAuthorityKeyIdentifier(cert);

            Assert.NotNull(authority);
            Assert.NotNull(authority.SerialNumber);
            Assert.NotNull(authority.KeyId);
            Assert.NotNull(authority.AuthorityNames);

            // verify authority key in signed cert
            X509SubjectKeyIdentifierExtension subjectKeyId = FindExtension <X509SubjectKeyIdentifierExtension>(cert);

            Assert.AreEqual(subjectKeyId.SubjectKeyIdentifier, authority.KeyId);
            Assert.AreEqual(cert.SerialNumber, authority.SerialNumber);

            X509SubjectAltNameExtension subjectAlternateName = FindSubjectAltName(cert);

            Assert.Null(subjectAlternateName);
        }
예제 #23
0
        private static ISet <string> ReadExtendedKeyUsageExtension(X509Extension extension)
        {
            X509EnhancedKeyUsageExtension ekusExtension = (X509EnhancedKeyUsageExtension)extension;
            HashSet <string> oids = new HashSet <string>();

            foreach (Oid oid in ekusExtension.EnhancedKeyUsages)
            {
                oids.Add(oid.Value);
            }

            return(oids);
        }
예제 #24
0
 private static X509EnhancedKeyUsageExtension FindEnhancedKeyUsageExtension(X509Certificate2 certificate)
 {
     for (int ii = 0; ii < certificate.Extensions.Count; ii++)
     {
         X509EnhancedKeyUsageExtension extension = certificate.Extensions[ii] as X509EnhancedKeyUsageExtension;
         if (extension != null)
         {
             return(extension);
         }
     }
     return(null);
 }
        private bool ValidateIdentityCertificate(X509Certificate2 identity)
        {
            string subject = this.ExtractSubjectName(identity);

            if (!identity.HasPrivateKey)
            {
                SslNoPrivateKeyRecord.TraceAndLog(subject, identity.Thumbprint);
                DebugTrace.Trace(TraceLevel.Warning, "Identity certificate with subject name {0} and thumbprint {1} does not have a private key", subject, identity.Thumbprint);
                return(false);
            }
            try
            {
                AsymmetricAlgorithm privateKey = identity.PrivateKey;
            }
            catch (CryptographicException exception)
            {
                Microsoft.Transactions.Bridge.DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Warning);
                SslNoAccessiblePrivateKeyRecord.TraceAndLog(subject, identity.Thumbprint);
                DebugTrace.Trace(TraceLevel.Warning, "Identity certificate with subject name {0} and thumbprint {1} does not have an accessible private key", subject, identity.Thumbprint);
                return(false);
            }
            X509KeyUsageExtension extension = (X509KeyUsageExtension)identity.Extensions["2.5.29.15"];

            if ((extension != null) && ((extension.KeyUsages & (X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment)) != (X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment)))
            {
                MissingNecessaryKeyUsageRecord.TraceAndLog(subject, identity.Thumbprint, X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment);
                DebugTrace.Trace(TraceLevel.Warning, "Identity certificate with subject name {0} and thumbprint {1} does not provide {2} among its KeyUsages", subject, identity.Thumbprint, (X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment).ToString());
                return(false);
            }
            X509EnhancedKeyUsageExtension extension2 = (X509EnhancedKeyUsageExtension)identity.Extensions["2.5.29.37"];

            if (extension2 != null)
            {
                if (extension2.EnhancedKeyUsages["1.3.6.1.5.5.7.3.2"] == null)
                {
                    MissingNecessaryEnhancedKeyUsageRecord.TraceAndLog(subject, identity.Thumbprint, "1.3.6.1.5.5.7.3.2");
                    DebugTrace.Trace(TraceLevel.Warning, "Identity certificate with subject name {0} and thumbprint {1} does not provide {2} as one of its EnhancedKeyUsages", subject, identity.Thumbprint, "1.3.6.1.5.5.7.3.2");
                    return(false);
                }
                if (extension2.EnhancedKeyUsages["1.3.6.1.5.5.7.3.1"] == null)
                {
                    MissingNecessaryEnhancedKeyUsageRecord.TraceAndLog(subject, identity.Thumbprint, "1.3.6.1.5.5.7.3.1");
                    DebugTrace.Trace(TraceLevel.Warning, "Identity certificate with subject name {0} and thumbprint {1} does not provide {2} as one of its EnhancedKeyUsages", subject, identity.Thumbprint, "1.3.6.1.5.5.7.3.1");
                    return(false);
                }
            }
            if (DebugTrace.Info)
            {
                DebugTrace.Trace(TraceLevel.Info, "Identity certificate was successfully validated");
            }
            return(true);
        }
예제 #26
0
        private static bool ValidatEKUForChain(ICmsSignature signature, X509Chain chain, SignatureLogger verboseWriter)
        {
            bool signingCertEKU = false;
            bool chainEKU       = false;
            X509ExtensionCollection extensions = signature.Certificate.Extensions;

            foreach (X509Extension extension in extensions)
            {
                if (extension.Oid.FriendlyName == "Enhanced Key Usage")
                {
                    signingCertEKU = true;
                    //break;
                    X509EnhancedKeyUsageExtension ext = (X509EnhancedKeyUsageExtension)extension;

                    OidCollection oids = ext.EnhancedKeyUsages;
                    EKUCritical = ext.Critical;

                    foreach (Oid oid in oids)
                    {
                        //if (oid.Equals("1.3.6.1.5.5.7.3.3"))


                        EKU_oidStr = oid.FriendlyName + "(" + oid.Value + ")" + ";" + EKU_oidStr;
                    }
                    Console.WriteLine(EKU_oidStr);
                }
            }
            string EKU =
                var signatureStrength = GetHashStrenghForComparison(signature.DigestAlgorithm.Value);
            var strongShaChain = true;
            var leafCertificateSignatureAlgorithm         = chain.ChainElements[0].Certificate.SignatureAlgorithm;
            var leafCertificateSignatureAlgorithmStrength = GetHashStrenghForComparison(leafCertificateSignatureAlgorithm.Value);

            //We use count-1 because we don't want to validate the root certificate.
            for (var i = 0; i < chain.ChainElements.Count - 1; i++)
            {
                var element                 = chain.ChainElements[i];
                var signatureAlgorithm      = element.Certificate.SignatureAlgorithm;
                var certificateHashStrength = GetHashStrenghForComparison(signatureAlgorithm.Value);
                if (certificateHashStrength < signatureStrength)
                {
                    verboseWriter.LogSignatureMessage(signature, $"Certificate {element.Certificate.Thumbprint} in chain uses {element.Certificate.SignatureAlgorithm.FriendlyName} for its signature algorithm instead of at least {signature.DigestAlgorithm.FriendlyName}.");
                    strongShaChain = false;
                }
                //Check that all intermediates are at least as strong as the leaf.
                else if (certificateHashStrength < leafCertificateSignatureAlgorithmStrength)
                {
                    verboseWriter.LogSignatureMessage(signature, $"Certificate {element.Certificate.Thumbprint} in chain uses {element.Certificate.SignatureAlgorithm.FriendlyName} for its signature algorithm instead of at least {signature.DigestAlgorithm.FriendlyName}.");
                }
            }
            return(strongShaChain);
        }
예제 #27
0
        /// <summary>
        ///   returns true if the X509 Certificate can be used  as SSL Client Certificate.
        /// </summary>
        private static bool IsClientCertificate(X509Certificate2 cert)
        {
            Debug.Assert(cert != null, "certificate cannot be null");

            bool foundEku           = false;
            bool foundKeyUsages     = false;
            bool isClientAuth       = true;
            bool isDigitalSignature = true;

            foreach (X509Extension extension in cert.Extensions)
            {
                // check if the extension is an enhanced usage ext.
                // But do this only if needed. No point going over it, if we already have established that our cert has the
                // required extension.
                if (!foundEku)
                {
                    X509EnhancedKeyUsageExtension enhancedUsageExt = extension as X509EnhancedKeyUsageExtension;
                    if (enhancedUsageExt != null)
                    {
                        foundEku     = true;
                        isClientAuth = false;
                        foreach (Oid oid in enhancedUsageExt.EnhancedKeyUsages)
                        {
                            if (string.Equals(ClientCertificateOid, oid.Value))
                            {
                                isClientAuth = true;
                                break;
                            }
                        }
                    }
                }

                // Check if the extension is a key usage extension.
                // No point going over it if we have already established that our cert has digital signature
                if (!foundKeyUsages)
                {
                    X509KeyUsageExtension usageExt = extension as X509KeyUsageExtension;
                    if (usageExt != null)
                    {
                        foundKeyUsages     = true;
                        isDigitalSignature = (usageExt.KeyUsages & X509KeyUsageFlags.DigitalSignature) != 0;
                    }
                }

                if (foundKeyUsages && foundEku)
                {
                    break;
                }
            }

            return(isClientAuth && isDigitalSignature);
        }
예제 #28
0
 /// <summary>
 /// Decodes ASN.1-encoded object identifier to an instance of generic <see cref="Oid"/> class.
 /// </summary>
 /// <param name="rawData">Byte array to decode.</param>
 /// <exception cref="ArgumentNullException"><strong>rawData</strong> parameter is null reference.</exception>
 /// <exception cref="InvalidDataException">The data is not properly encoded Object Identifier.</exception>
 /// <returns>An instance of <see cref="Oid"/> class contained decoded object identifier.</returns>
 public static Oid DecodeObjectIdentifier(Byte[] rawData)
 {
     if (rawData == null)
     {
         throw new ArgumentNullException();
     }
     try {
         Byte[]         raw                = Encode(rawData, 48);
         AsnEncodedData asnencoded         = new AsnEncodedData(raw);
         X509EnhancedKeyUsageExtension eku = new X509EnhancedKeyUsageExtension(asnencoded, false);
         return(eku.EnhancedKeyUsages[0]);
     } catch { throw new InvalidDataException("Input data is not valid ASN-encoded Oid."); }
 }
예제 #29
0
        private X509EnhancedKeyUsageExtension GetEnhancedKeyUsageExtension(X509Certificate2 cert)
        {
            foreach (var extension in cert.Extensions)
            {
                X509EnhancedKeyUsageExtension eku = extension as X509EnhancedKeyUsageExtension;

                if (eku != null)
                {
                }
            }

            throw new Exception("Certificate does not contain Enhanced Key Usage Extension");
        }
예제 #30
0
        public static void CollectionPropertyIsolation()
        {
            Oid           oid1              = new Oid("1.3.6.1.5.5.7.3.1");
            OidCollection usages            = new OidCollection();
            X509EnhancedKeyUsageExtension e = new X509EnhancedKeyUsageExtension(usages, false);

            Assert.Equal(0, e.EnhancedKeyUsages.Count);
            usages.Add(oid1);
            Assert.Equal(0, e.EnhancedKeyUsages.Count);
            e.EnhancedKeyUsages.Add(oid1);
            Assert.Equal(0, e.EnhancedKeyUsages.Count);
            Assert.NotSame(e.EnhancedKeyUsages, e.EnhancedKeyUsages);
        }
예제 #31
0
		internal string EnhancedKeyUsageExtension (bool multiLine)
		{
			try {
				X509EnhancedKeyUsageExtension eku = new X509EnhancedKeyUsageExtension  (this, false);
				return eku.ToString (multiLine);
			}
			catch {
				return String.Empty;
			}
		}
예제 #32
0
        public static void EnhancedKeyUsageExtensionDefault()
        {
            X509EnhancedKeyUsageExtension e = new X509EnhancedKeyUsageExtension();
            string oidValue = e.Oid.Value;
            Assert.Equal("2.5.29.37", oidValue);

            byte[] rawData = e.RawData;
            Assert.Null(rawData);

            OidCollection usages = e.EnhancedKeyUsages;
            Assert.Equal(0, usages.Count);
        }
예제 #33
0
        private static void TestEnhancedKeyUsageExtension(
            OidCollection usages,
            bool critical,
            byte[] expectedDer)
        {
            X509EnhancedKeyUsageExtension ext = new X509EnhancedKeyUsageExtension(usages, critical);
            byte[] rawData = ext.RawData;
            Assert.Equal(expectedDer, rawData);

            ext = new X509EnhancedKeyUsageExtension(new AsnEncodedData(rawData), critical);
            OidCollection actualUsages = ext.EnhancedKeyUsages;

            Assert.Equal(usages.Count, actualUsages.Count);

            for (int i = 0; i < usages.Count; i++)
            {
                Assert.Equal(usages[i].Value, actualUsages[i].Value);
            }
        }