Exemplo n.º 1
0
        public static bool AddCertificateToStore(uint httpsPort)
        {
            var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

            try {
                store.Open(OpenFlags.ReadWrite);
            } catch {
                Out.Error(AuthenticationNeeded);
                return false;
            }

            var cert = new X509Certificate2(
                CreateSelfSignCertificatePfx(X509SubjectName, DateTime.Now.AddDays(-1), DateTime.Now.AddYears(1), CertificatePassword),
                CertificatePassword,
                X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);
            cert.FriendlyName = "Stubby4net Certificate";

            var existingCerts = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, cert.Subject, false);
            if(existingCerts.Count == 0)
                store.Add(cert);
            else
                cert = existingCerts[0];
            store.Close();

            var netshArgs = String.Format(NetshArgs, httpsPort, cert.GetCertHashString(), "{" + Stubby.Guid + "}");
            var netsh = new ProcessStartInfo("netsh", netshArgs)
            {
                Verb = "runas",
                CreateNoWindow = true,
                WindowStyle = ProcessWindowStyle.Hidden,
                UseShellExecute = true
            };

            try {
                var process = Process.Start(netsh);
                process.WaitForExit();
                Console.Out.WriteLine(process.ExitCode);
                if(process.ExitCode == 0)
                    return true;
            } catch {
            }

            var httpcfgArgs = String.Format(HttpcfgArgs, httpsPort, cert.GetCertHashString());
            var httpcfg = new ProcessStartInfo("httpcfg", httpcfgArgs)
            {
                Verb = "runas",
                CreateNoWindow = true,
                WindowStyle = ProcessWindowStyle.Hidden,
                UseShellExecute = true
            };

            try {
                var process = Process.Start(httpcfg);
                process.WaitForExit();
                return process.ExitCode == 0;
            } catch {
                return false;
            }
        }
Exemplo n.º 2
0
        // Helper methods

        private static void IndexFolder(string folderName, StringBuilder sb, bool noProgress, bool verify)
        {
            // Process all file in folder
            foreach (var fileName in Directory.GetFiles(folderName))
            {
                if (!_certExts.Contains(Path.GetExtension(fileName).ToLowerInvariant()))
                {
                    continue;
                }

                // Get basic cert properties
                var cert            = new System.Security.Cryptography.X509Certificates.X509Certificate2(fileName);
                var serialNumberHex = "0x" + cert.GetSerialNumberString();
                var serialNumberDec = uint.Parse(cert.GetSerialNumberString(), System.Globalization.NumberStyles.HexNumber);
                var email           = cert.GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType.EmailName, false);
                var domain          = email.Substring(email.IndexOf('@') + 1);
                var name            = cert.GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType.SimpleName, false);
                if (!noProgress)
                {
                    Console.Write($"0x{serialNumberHex,-8} {email,-40} {name,-30} ");
                }

                // Verify certificate
                var status = "Unknown";
                if (verify)
                {
                    var certValid = ValidateCertificate(cert);
                    status = certValid ? "OK" : "Revoked";
                }
                if (!noProgress)
                {
                    Console.WriteLine(status);
                }

                // Add line to index
                sb.AppendLine(string.Join(CSV_SEPARATOR,
                                          serialNumberHex,
                                          serialNumberDec,
                                          cert.GetCertHashString(),
                                          cert.NotBefore.ToString("yyyy-MM-dd"),
                                          cert.NotAfter.ToString("yyyy-MM-dd"),
                                          cert.PublicKey.Key.KeySize,
                                          status,
                                          domain,
                                          name,
                                          email,
                                          cert.Issuer,
                                          cert.Subject));
            }

            // Crafl subfolders
            foreach (var subFolderName in Directory.GetDirectories(folderName))
            {
                IndexFolder(subFolderName, sb, noProgress, verify);
            }
        }
Exemplo n.º 3
0
        public static Dictionary <string, string> ParseCert(byte[] certDER)
        {
            var ret = new Dictionary <string, string>();

            try {
                var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certDER);
                //logger.Debug("X.509v3証明書の発行先であるプリンシパルの名前(古い形式)");
                //logger.Debug(x509.GetName());

                ret.Add("X.509v3証明書の形式の名前", x509.GetFormat());
                ret.Add("バージョン", $"{x509.Version}");
                ret.Add("シリアル番号", x509.GetSerialNumberString());
                ret.Add("署名アルゴリズム", x509.SignatureAlgorithm.FriendlyName);
                ret.Add("証明書を発行した証明機関の名前", x509.Issuer);
                ret.Add("サブジェクトの識別名", x509.Subject);
                ret.Add("証明書のハッシュ値の16進文字列", x509.GetCertHashString());
                ret.Add("証明書の発効日", x509.GetEffectiveDateString());
                ret.Add("証明書の失効日", x509.GetExpirationDateString());
                ret.Add("キーアルゴリズム情報", x509.GetKeyAlgorithm());
                ret.Add("キーアルゴリズムパラメータ", x509.GetKeyAlgorithmParametersString());
                ret.Add("公開鍵", x509.GetPublicKeyString());

                foreach (var extension in x509.Extensions)
                {
                    /*
                     * if (extension.Oid.FriendlyName == "キー使用法") {
                     *  var ext = (X509KeyUsageExtension)extension;
                     *  ret.Add("Extension キー使用法", ext.KeyUsages.ToString());
                     * }
                     * if (extension.Oid.FriendlyName == "拡張キー使用法") {
                     *  var ext = (X509EnhancedKeyUsageExtension)extension;
                     *  string value = "";
                     *  var oids = ext.EnhancedKeyUsages;
                     *  foreach (var oid in oids) {
                     *      value = value + oid.FriendlyName + "(" + oid.Value + ")";
                     *  }
                     *  ret.Add("Extension 拡張キー使用法", value);
                     * }
                     */

                    ret.Add($"- Extension {extension.Oid.FriendlyName}", extension.Oid.Value);
                }

                //logger.Debug("X.509v3証明書を発行した証明機関の名前(古い形式)");
                //logger.Debug(x509.GetIssuerName());

                //logger.Debug("X.509証明書全体の生データ");
                //logger.Debug(x509.GetRawCertDataString());
            } catch (Exception ex) {
                logger.Debug(ex);
            }
            return(ret);
        }
        public byte[] InstallCertificateWithPrivateKey(string certificatePath, string certificateStoreName, RSAParameters privateKey)
        {            
            var certificateBytes = File.ReadAllBytes(certificatePath);
            var x509 = new X509Certificate2(certificateBytes, (string)null, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);
            var csp = new CspParameters { KeyContainerName = x509.GetCertHashString(), Flags = CspProviderFlags.UseMachineKeyStore };
            var rsa = new RSACryptoServiceProvider(csp);
            rsa.ImportParameters(privateKey);
            x509.PrivateKey = rsa;

            Info($"Installing certificate private key to localmachine\\{certificateStoreName}, container name {csp.KeyContainerName}");

            InstallCertificateToStore(x509, certificateStoreName);
            return x509.GetCertHash();
        }
		public TlsServerSession (X509Certificate2 cert, bool mutual)
		{
			this.mutual = mutual;
			stream = new MemoryStream ();
			ssl = new SslServerStream (stream, cert, mutual, true, SecurityProtocolType.Tls);
			ssl.PrivateKeyCertSelectionDelegate = delegate (X509Certificate c, string host) {
				if (c.GetCertHashString () == cert.GetCertHashString ())
					return cert.PrivateKey;
				return null;
			};
			ssl.ClientCertValidationDelegate = delegate (X509Certificate certificate, int[] certificateErrors) {
				// FIXME: use X509CertificateValidator
				return true;
			};
		}
        public void Should_install_a_x509_certificate_and_update_bindings()
        {
            // Arrange
            var x509 = new X509Certificate2(Encoding.ASCII.GetBytes(TestCertificate), (string)null, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);            
            var sut = new IISServerConfigurationProvider();
            var asn1Parser = new Asn1Parser();
            var rsaParser = new PrivateKeyParser(asn1Parser);
            var privateKey = rsaParser.ParsePem(TestPrivateKey).Key;            
            var csp = new CspParameters { KeyContainerName = x509.GetCertHashString(), Flags = CspProviderFlags.UseMachineKeyStore };
            var rsa2 = new RSACryptoServiceProvider(csp);
            rsa2.ImportParameters(privateKey);
            x509.PrivateKey = rsa2;

            // Act            
            sut.ConfigureServer("test.startliste.info", x509.GetCertHash(), "my", null, null);
        }
Exemplo n.º 7
0
        public bool AddCertificateFromPfxToIPPort(String host, String port, String pfxFile, System.Security.SecureString password)
        {
            if (!File.Exists(pfxFile))
            {
                throw new Exception($"File {pfxFile} does not exist");
            }

            System.Security.Cryptography.X509Certificates.X509Certificate2 pfx = null;
            try
            {
                pfx = new System.Security.Cryptography.X509Certificates.X509Certificate2(pfxFile, password);
            }
            catch (Exception ex)
            {
                ServerComms.LogError($@"Unable to add the cert {pfxFile} to ipport={host}:{port} Error: {ex.Message}");
                return(false);
            }
            return(AddCertificateToIPPort(host, port, pfx.GetCertHashString()));
        }
        public override void AssignSession(Session oS)
        {
            base.AssignSession(oS);
            var dataItems = new List<DataItem>();
            dataItems.Add(new DataItem("Is Https", oS.isHTTPS));

            if (oS.isHTTPS && oS.oFlags.ContainsKey(CertificateStorage.CeritificateRequestPropertyName))
            {
                try
                {
                    var thumbprint = oS.oFlags[CertificateStorage.CeritificateRequestPropertyName];
                    FiddlerApplication.Log.LogString(thumbprint);

                    if (CertificateStorage.Certificates.ContainsKey(thumbprint))
                    {
                        var certificate = CertificateStorage.Certificates[thumbprint];
                        var cert = new X509Certificate2(certificate);

                        _informationTab.Certificate = cert;
                        //most commonly desired information up top.
                        dataItems.InsertRange(0, new[] { new DataItem("FriendlyName", cert.FriendlyName),
                                                         new DataItem("Subject", cert.Subject),
                                                         new DataItem("Issuer", cert.Issuer),
                                                         new DataItem("Effective Date", cert.GetEffectiveDateString()),
                                                         new DataItem("Expiration Date", cert.GetExpirationDateString()),
                                                         new DataItem("Thumbprint", cert.Thumbprint),
                                                         new DataItem("------------------------", "------------------------")});

                        //alphabatized data properties below
                        dataItems.Add(new DataItem("Archived", cert.Archived));
                        dataItems.Add(new DataItem("FriendlyName", cert.FriendlyName));
                        dataItems.Add(new DataItem("Certficate Hash", cert.GetCertHashString()));
                        dataItems.Add(new DataItem("Certificate Format", cert.GetFormat()));
                        dataItems.Add(new DataItem("Effective Date", cert.GetEffectiveDateString()));
                        dataItems.Add(new DataItem("Expiration Date", cert.GetExpirationDateString()));
                        dataItems.Add(new DataItem("Full Issuer Name", cert.IssuerName.Format(true)));
                        dataItems.Add(new DataItem("Full Subject Name", cert.SubjectName.Format(true)));
                        dataItems.Add(new DataItem("Has Private Key", cert.HasPrivateKey));
                        dataItems.Add(new DataItem("Issuer", cert.Issuer));
                        dataItems.Add(new DataItem("Key Algorithm", cert.GetKeyAlgorithm()));
                        dataItems.Add(new DataItem("Key Algorithm Parameters", cert.GetKeyAlgorithmParametersString()));
                        dataItems.Add(new DataItem("Public Key", cert.GetPublicKeyString()));
                        dataItems.Add(new DataItem("Raw Certificate Data", cert.GetRawCertDataString()));
                        dataItems.Add(new DataItem("SerialNumberString", cert.GetSerialNumberString()));
                        dataItems.Add(new DataItem("Subject", cert.Subject));
                        dataItems.Add(new DataItem("Thumbprint", cert.Thumbprint));
                        dataItems.Add(new DataItem("Version", cert.Version));

                        dataItems.Add(new DataItem("------------------------", "------------------------"));
                        dataItems.Add(new DataItem("Extensions", string.Empty));
                        dataItems.Add(new DataItem("------------------------", "------------------------"));
                        foreach (var extension in cert.Extensions)
                        {
                            dataItems.Add(new DataItem(extension.Oid.FriendlyName, extension.Format(true)));
                        }
                    }
                }
                catch (Exception ex)
                {
                    FiddlerApplication.Log.LogString("Unexpected error loading the assigned certificate." + ex.Message);
                }
            }

            _informationTab.DataGrid.DataSource = dataItems;
        }
Exemplo n.º 9
0
        public static string GetIssuerCertificate(CertificateRequest certificate, CertificateProvider cp)
        {
            var linksEnum = certificate.Links;
            if (linksEnum != null)
            {
                var links = new LinkCollection(linksEnum);
                var upLink = links.GetFirstOrDefault("up");
                if (upLink != null)
                {
                    var tmp = Path.GetTempFileName();
                    try
                    {
                        using (var web = new WebClient())
                        {

                            var uri = new Uri(new Uri(BaseURI), upLink.Uri);
                            web.DownloadFile(uri, tmp);
                        }

                        var cacert = new X509Certificate2(tmp);
                        var sernum = cacert.GetSerialNumberString();
                        var tprint = cacert.Thumbprint;
                        var sigalg = cacert.SignatureAlgorithm?.FriendlyName;
                        var sigval = cacert.GetCertHashString();

                        var cacertDerFile = Path.Combine(certificatePath, $"ca-{sernum}-crt.der");
                        var cacertPemFile = Path.Combine(certificatePath, $"ca-{sernum}-crt.pem");

                        if (!File.Exists(cacertDerFile))
                            File.Copy(tmp, cacertDerFile, true);

                        Console.WriteLine($" Saving Issuer Certificate to {cacertPemFile}");
                        Log.Information("Saving Issuer Certificate to {cacertPemFile}", cacertPemFile);
                        if (!File.Exists(cacertPemFile))
                            using (FileStream source = new FileStream(cacertDerFile, FileMode.Open),
                                    target = new FileStream(cacertPemFile, FileMode.Create))
                            {
                                var caCrt = cp.ImportCertificate(EncodingFormat.DER, source);
                                cp.ExportCertificate(caCrt, EncodingFormat.PEM, target);
                            }

                        return cacertPemFile;
                    }
                    finally
                    {
                        if (File.Exists(tmp))
                            File.Delete(tmp);
                    }
                }
            }

            return null;
        }
        protected override void ProcessRecord()
        {
            using (var vp = InitializeVault.GetVaultProvider(VaultProfile))
            {
                vp.OpenStorage();
                var v = vp.LoadVault();

                if (v.Registrations == null || v.Registrations.Count < 1)
                    throw new InvalidOperationException("No registrations found");

                var ri = v.Registrations[0];
                var r = ri.Registration;

                if (v.Certificates == null || v.Certificates.Count < 1)
                    throw new InvalidOperationException("No certificates found");

                var ci = v.Certificates.GetByRef(Ref);
                if (ci == null)
                    throw new Exception("Unable to find a Certificate for the given reference");

                if (!LocalOnly)
                {
                    if (ci.CertificateRequest == null)
                        throw new Exception("Certificate has not been submitted yet; cannot update status");

                    using (var c = ClientHelper.GetClient(v, ri))
                    {
                        c.Init();
                        c.GetDirectory(true);

                        c.RefreshCertificateRequest(ci.CertificateRequest, UseBaseURI);
                    }

                    if ((Repeat || string.IsNullOrEmpty(ci.CrtPemFile))
                            && !string.IsNullOrEmpty(ci.CertificateRequest.CertificateContent))
                    {
                        var crtDerFile = $"{ci.Id}-crt.der";
                        var crtPemFile = $"{ci.Id}-crt.pem";

                        var crtDerAsset = vp.ListAssets(crtDerFile, VaultAssetType.CrtDer).FirstOrDefault();
                        var crtPemAsset = vp.ListAssets(crtPemFile, VaultAssetType.CrtPem).FirstOrDefault();

                        if (crtDerAsset == null)
                            crtDerAsset = vp.CreateAsset(VaultAssetType.CrtDer, crtDerFile);
                        if (crtPemAsset == null)
                            crtPemAsset = vp.CreateAsset(VaultAssetType.CrtPem, crtPemFile);

                        using (var s = vp.SaveAsset(crtDerAsset))
                        {
                            ci.CertificateRequest.SaveCertificate(s);
                            ci.CrtDerFile = crtDerFile;
                        }

                        using (Stream source = vp.LoadAsset(crtDerAsset), target = vp.SaveAsset(crtPemAsset))
                        {
                            CsrHelper.Crt.ConvertDerToPem(source, target);
                            ci.CrtPemFile = crtPemFile;
                        }

                        var crt = new X509Certificate2(ci.CertificateRequest.GetCertificateContent());
                        ci.SerialNumber = crt.SerialNumber;
                        ci.Thumbprint = crt.Thumbprint;
                        ci.SignatureAlgorithm = crt.SignatureAlgorithm?.FriendlyName;
                        ci.Signature = crt.GetCertHashString();
                    }

                    if (Repeat || string.IsNullOrEmpty(ci.IssuerSerialNumber))
                    {
                        var linksEnum = ci.CertificateRequest.Links;
                        if (linksEnum != null)
                        {
                            var links = new LinkCollection(linksEnum);
                            var upLink = links.GetFirstOrDefault("up");
                            if (upLink != null)
                            {
                                var tmp = Path.GetTempFileName();
                                try
                                {
                                    using (var web = new WebClient())
                                    {
                                        if (v.Proxy != null)
                                            web.Proxy = v.Proxy.GetWebProxy();

                                        var uri = new Uri(new Uri(v.BaseURI), upLink.Uri);
                                        web.DownloadFile(uri, tmp);
                                    }

                                    var cacert = new X509Certificate2(tmp);
                                    var sernum = cacert.GetSerialNumberString();
                                    var tprint = cacert.Thumbprint;
                                    var sigalg = cacert.SignatureAlgorithm?.FriendlyName;
                                    var sigval = cacert.GetCertHashString();

                                    if (v.IssuerCertificates == null)
                                        v.IssuerCertificates = new OrderedNameMap<IssuerCertificateInfo>();
                                    if (Repeat || !v.IssuerCertificates.ContainsKey(sernum))
                                    {
                                        var cacertDerFile = $"ca-{sernum}-crt.der";
                                        var cacertPemFile = $"ca-{sernum}-crt.pem";
                                        var issuerDerAsset = vp.ListAssets(cacertDerFile,
                                                VaultAssetType.IssuerDer).FirstOrDefault();
                                        var issuerPemAsset = vp.ListAssets(cacertPemFile,
                                                VaultAssetType.IssuerPem).FirstOrDefault();

                                        if (Repeat || issuerDerAsset == null)
                                        {
                                            if (issuerDerAsset == null)
                                            issuerDerAsset = vp.CreateAsset(VaultAssetType.IssuerDer, cacertDerFile);
                                                using (Stream fs = new FileStream(tmp, FileMode.Open),
                                                    s = vp.SaveAsset(issuerDerAsset))
                                            {
                                                fs.CopyTo(s);
                                            }
                                        }
                                        if (Repeat || issuerPemAsset == null)
                                        {
                                            if (issuerPemAsset == null)
                                                issuerPemAsset = vp.CreateAsset(VaultAssetType.IssuerPem, cacertPemFile);
                                            using (Stream source = vp.LoadAsset(issuerDerAsset),
                                                    target = vp.SaveAsset(issuerPemAsset))
                                            {
                                                CsrHelper.Crt.ConvertDerToPem(source, target);
                                            }
                                        }

                                        v.IssuerCertificates[sernum] = new IssuerCertificateInfo
                                        {
                                            SerialNumber = sernum,
                                            Thumbprint  = tprint,
                                            SignatureAlgorithm = sigalg,
                                            Signature = sigval,
                                            CrtDerFile = cacertDerFile,
                                            CrtPemFile = cacertPemFile,
                                        };
                                    }

                                    ci.IssuerSerialNumber = sernum;
                                }
                                finally
                                {
                                    if (File.Exists(tmp))
                                        File.Delete(tmp);
                                }
                            }
                        }
                    }
                }

                v.Alias = StringHelper.IfNullOrEmpty(Alias);
                v.Label = StringHelper.IfNullOrEmpty(Label);
                v.Memo = StringHelper.IfNullOrEmpty(Memo);

                vp.SaveVault(v);

                WriteObject(ci);
            }
        }
Exemplo n.º 11
0
        static string GetIssuerCertificate(CertificateRequest certificate)
        {
            var linksEnum = certificate.Links;
            if (linksEnum != null)
            {
                var links = new LinkCollection(linksEnum);
                var upLink = links.GetFirstOrDefault("up");
                if (upLink != null)
                {
                    var tmp = Path.GetTempFileName();
                    try
                    {
                        using (var web = new WebClient())
                        {
                            //if (v.Proxy != null)
                            //    web.Proxy = v.Proxy.GetWebProxy();

                            var uri = new Uri(new Uri(BaseURI), upLink.Uri);
                            web.DownloadFile(uri, tmp);
                        }

                        var cacert = new X509Certificate2(tmp);
                        var sernum = cacert.GetSerialNumberString();
                        var tprint = cacert.Thumbprint;
                        var sigalg = cacert.SignatureAlgorithm?.FriendlyName;
                        var sigval = cacert.GetCertHashString();

                        var cacertDerFile = Path.Combine(configPath, $"ca-{sernum}-crt.der");
                        var cacertPemFile = Path.Combine(configPath, $"ca-{sernum}-crt.pem");

                        if (!File.Exists(cacertDerFile))
                            File.Copy(tmp, cacertDerFile, true);

                        Console.WriteLine($" Saving Issuer Certificate to {cacertPemFile}");
                        if (!File.Exists(cacertPemFile))
                            CsrHelper.Crt.ConvertDerToPem(cacertDerFile, cacertPemFile);

                        return cacertPemFile;
                    }
                    finally
                    {
                        if (File.Exists(tmp))
                            File.Delete(tmp);
                    }
                }
            }

            return null;
        }
Exemplo n.º 12
0
        //
        // SECURITY: we open a private key container on behalf of the caller
        // and we require the caller to have permission associated with that operation.
        // After discussing with X509Certificate2 owners decided to demand KeyContainerPermission (Open)
        // At the same time we assert StorePermission on the caller frame since for consistency
        // we cannot predict when it will be demanded (SSL session reuse feature)
        //
        X509Certificate2 EnsurePrivateKey(X509Certificate certificate)
        {
            if (certificate == null)
                return null;

            if (Logging.On) Logging.PrintInfo(Logging.Web, this, SR.GetString(SR.net_log_locating_private_key_for_certificate, certificate.ToString(true)));
            
            try {
                X509Certificate2 certEx = certificate as X509Certificate2;
                Type t = certificate.GetType();
                string certHash = null;

                // Protecting from X509Certificate2 derived classes
                if (t != typeof(X509Certificate2) && t != typeof(X509Certificate))
                {
                    if (certificate.Handle != IntPtr.Zero)
                    {
                        certEx = new X509Certificate2(certificate);
                        certHash = certEx.GetCertHashString();
                    }
                }
                else
                {
                    certHash = certificate.GetCertHashString();
                }

                if (certEx != null)
                {
                    if (certEx.HasPrivateKey)
                    {
                        if (Logging.On) Logging.PrintInfo(Logging.Web, this, SR.GetString(SR.net_log_cert_is_of_type_2));
                        return certEx;
                    }

                    if ((object)certificate != (object) certEx)
                        certEx.Reset();
                }

                //
                // The certificate doesn't have a private key, so we need
                // to open the store and search for it there. Demand the
                // KeyContainerPermission with Open access before opening
                // the store. If store.Open() or store.Cert.Find()
                // demand the same permissions, then we should remove our
                // demand here.
                //
                #if FEATURE_MONO_CAS
                ExceptionHelper.KeyContainerPermissionOpen.Demand(); 
                #endif
                
                X509Certificate2Collection collectionEx;

                // ELSE Try MY user and machine stores for private key check
                // For server side mode MY machine store takes priority
                X509Store store = EnsureStoreOpened(m_ServerMode);
                if (store != null)
                {
                    collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false);
                    if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey)
                    {
                        if (Logging.On) Logging.PrintInfo(Logging.Web, this, SR.GetString(SR.net_log_found_cert_in_store, (m_ServerMode ? "LocalMachine" : "CurrentUser")));
                        return collectionEx[0];
                    }
                }

                store = EnsureStoreOpened(!m_ServerMode);
                if (store != null)
                {
                    collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false);
                    if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey)
                    {
                        if (Logging.On) Logging.PrintInfo(Logging.Web, this, SR.GetString(SR.net_log_found_cert_in_store, (m_ServerMode ? "CurrentUser" : "LocalMachine")));
                        return collectionEx[0];
                    }
                }
            }
            catch (CryptographicException) {
            }

            if (Logging.On) Logging.PrintInfo(Logging.Web, this, SR.GetString(SR.net_log_did_not_find_cert_in_store));

            return null;
        }
Exemplo n.º 13
0
 public override void Validate(X509Certificate2 certificate)
 {
     if(!_certs.ContainsKey(certificate.GetCertHashString()))
     {
         throw new SecurityTokenException("invalid certificate");
     }
 }
        public X509Certificate2Collection Find(X509FindType findType, object findValue, bool validOnly)
        {
            if (findValue == null)
            {
                throw new ArgumentNullException("findValue");
            }
            string            text              = string.Empty;
            string            text2             = string.Empty;
            X509KeyUsageFlags x509KeyUsageFlags = X509KeyUsageFlags.None;
            DateTime          t = DateTime.MinValue;

            switch (findType)
            {
            case X509FindType.FindByThumbprint:
            case X509FindType.FindBySubjectName:
            case X509FindType.FindBySubjectDistinguishedName:
            case X509FindType.FindByIssuerName:
            case X509FindType.FindByIssuerDistinguishedName:
            case X509FindType.FindBySerialNumber:
            case X509FindType.FindByTemplateName:
            case X509FindType.FindBySubjectKeyIdentifier:
                try
                {
                    text = (string)findValue;
                }
                catch (Exception inner)
                {
                    string text3 = Locale.GetText("Invalid find value type '{0}', expected '{1}'.", new object[]
                    {
                        findValue.GetType(),
                        "string"
                    });
                    throw new CryptographicException(text3, inner);
                }
                break;

            case X509FindType.FindByTimeValid:
            case X509FindType.FindByTimeNotYetValid:
            case X509FindType.FindByTimeExpired:
                try
                {
                    t = (DateTime)findValue;
                }
                catch (Exception inner2)
                {
                    string text4 = Locale.GetText("Invalid find value type '{0}', expected '{1}'.", new object[]
                    {
                        findValue.GetType(),
                        "X509DateTime"
                    });
                    throw new CryptographicException(text4, inner2);
                }
                break;

            case X509FindType.FindByApplicationPolicy:
            case X509FindType.FindByCertificatePolicy:
            case X509FindType.FindByExtension:
                try
                {
                    text2 = (string)findValue;
                }
                catch (Exception inner3)
                {
                    string text5 = Locale.GetText("Invalid find value type '{0}', expected '{1}'.", new object[]
                    {
                        findValue.GetType(),
                        "X509KeyUsageFlags"
                    });
                    throw new CryptographicException(text5, inner3);
                }
                try
                {
                    CryptoConfig.EncodeOID(text2);
                }
                catch (CryptographicUnexpectedOperationException)
                {
                    string text6 = Locale.GetText("Invalid OID value '{0}'.", new object[]
                    {
                        text2
                    });
                    throw new ArgumentException("findValue", text6);
                }
                break;

            case X509FindType.FindByKeyUsage:
                try
                {
                    x509KeyUsageFlags = (X509KeyUsageFlags)((int)findValue);
                }
                catch (Exception inner4)
                {
                    string text7 = Locale.GetText("Invalid find value type '{0}', expected '{1}'.", new object[]
                    {
                        findValue.GetType(),
                        "X509KeyUsageFlags"
                    });
                    throw new CryptographicException(text7, inner4);
                }
                break;

            default:
            {
                string text8 = Locale.GetText("Invalid find type '{0}'.", new object[]
                    {
                        findType
                    });
                throw new CryptographicException(text8);
            }
            }
            CultureInfo invariantCulture = CultureInfo.InvariantCulture;
            X509Certificate2Collection x509Certificate2Collection = new X509Certificate2Collection();

            foreach (object obj in base.InnerList)
            {
                X509Certificate2 x509Certificate = (X509Certificate2)obj;
                bool             flag            = false;
                switch (findType)
                {
                case X509FindType.FindByThumbprint:
                    flag = (string.Compare(text, x509Certificate.Thumbprint, true, invariantCulture) == 0 || string.Compare(text, x509Certificate.GetCertHashString(), true, invariantCulture) == 0);
                    break;

                case X509FindType.FindBySubjectName:
                {
                    string nameInfo = x509Certificate.GetNameInfo(X509NameType.SimpleName, false);
                    flag = (nameInfo.IndexOf(text, StringComparison.InvariantCultureIgnoreCase) >= 0);
                    break;
                }

                case X509FindType.FindBySubjectDistinguishedName:
                    flag = (string.Compare(text, x509Certificate.Subject, true, invariantCulture) == 0);
                    break;

                case X509FindType.FindByIssuerName:
                {
                    string nameInfo2 = x509Certificate.GetNameInfo(X509NameType.SimpleName, true);
                    flag = (nameInfo2.IndexOf(text, StringComparison.InvariantCultureIgnoreCase) >= 0);
                    break;
                }

                case X509FindType.FindByIssuerDistinguishedName:
                    flag = (string.Compare(text, x509Certificate.Issuer, true, invariantCulture) == 0);
                    break;

                case X509FindType.FindBySerialNumber:
                    flag = (string.Compare(text, x509Certificate.SerialNumber, true, invariantCulture) == 0);
                    break;

                case X509FindType.FindByTimeValid:
                    flag = (t >= x509Certificate.NotBefore && t <= x509Certificate.NotAfter);
                    break;

                case X509FindType.FindByTimeNotYetValid:
                    flag = (t < x509Certificate.NotBefore);
                    break;

                case X509FindType.FindByTimeExpired:
                    flag = (t > x509Certificate.NotAfter);
                    break;

                case X509FindType.FindByApplicationPolicy:
                    flag = (x509Certificate.Extensions.Count == 0);
                    break;

                case X509FindType.FindByExtension:
                    flag = (x509Certificate.Extensions[text2] != null);
                    break;

                case X509FindType.FindByKeyUsage:
                {
                    X509KeyUsageExtension x509KeyUsageExtension = x509Certificate.Extensions["2.5.29.15"] as X509KeyUsageExtension;
                    flag = (x509KeyUsageExtension == null || (x509KeyUsageExtension.KeyUsages & x509KeyUsageFlags) == x509KeyUsageFlags);
                    break;
                }

                case X509FindType.FindBySubjectKeyIdentifier:
                {
                    X509SubjectKeyIdentifierExtension x509SubjectKeyIdentifierExtension = x509Certificate.Extensions["2.5.29.14"] as X509SubjectKeyIdentifierExtension;
                    if (x509SubjectKeyIdentifierExtension != null)
                    {
                        flag = (string.Compare(text, x509SubjectKeyIdentifierExtension.SubjectKeyIdentifier, true, invariantCulture) == 0);
                    }
                    break;
                }
                }
                if (flag)
                {
                    if (validOnly)
                    {
                        try
                        {
                            if (x509Certificate.Verify())
                            {
                                x509Certificate2Collection.Add(x509Certificate);
                            }
                        }
                        catch
                        {
                        }
                    }
                    else
                    {
                        x509Certificate2Collection.Add(x509Certificate);
                    }
                }
            }
            return(x509Certificate2Collection);
        }
Exemplo n.º 15
0
        static void Main(string[] args)
        {
            if (args.Length > 1 && args[0].EndsWith(".pfx"))
            {
                var cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(args[0], args[1]);
                Console.WriteLine(cert.GetCertHashString());
                return;
            }
            //固定当前工作目录
            System.IO.Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);

            var builder = new ConfigurationBuilder();

            builder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
            var configuration = builder.Build();

            var port = configuration.GetValue <int>("Port");
            CommandArgParser cmdArg = new CommandArgParser(args);

            port = cmdArg.TryGetValue <int>("port", port);

            var datafolder = configuration.GetValue <string>("DataFolder");

            if (!System.IO.Directory.Exists(datafolder))
            {
                System.IO.Directory.CreateDirectory(datafolder);
            }
            datafolder = cmdArg.TryGetValue <string>("DataFolder", datafolder);

            ServiceCollection services = new ServiceCollection();

            services.AddLogging(loggingBuilder =>
            {
                loggingBuilder.AddConfiguration(configuration.GetSection("Logging"));
                loggingBuilder.AddConsole(); // 将日志输出到控制台
            });
            services.AddSingleton <IConfiguration>(configuration);
            services.AddSingleton <GatewayRefereeClient>();
            services.AddSingleton <IRequestReception, RequestReception>();
            services.AddSingleton <ICommandHandlerManager, CommandHandlerManager>();
            services.AddSingleton <Gateway>();
            services.AddSingleton <LockKeyManager>();
            services.AddTransient <IMicroServiceReception, MicroServiceReception>();
            services.AddSingleton <TransactionIdBuilder>();
            services.AddSingleton <FileChangeWatcher>();
            services.AddTransient <ListenFileChangeReception>();

            var assembly = Assembly.Load(configuration.GetValue <string>("ServiceProviderAllocator:Assembly"));
            var serviceProviderAllocatorType = assembly.GetType(configuration.GetValue <string>("ServiceProviderAllocator:FullName"));
            var serviceProviderAllocator     = (IServiceProviderAllocator)Activator.CreateInstance(serviceProviderAllocatorType);


            services.AddSingleton <IServiceProviderAllocator>(serviceProviderAllocator);
            var serviceProvider = services.BuildServiceProvider();

            serviceProvider.GetService <LockKeyManager>();
            serviceProvider.GetService <FileChangeWatcher>();

            //启动GatewayRefereeClient,申请成为主网关
            serviceProvider.GetService <GatewayRefereeClient>();

            var gateway = serviceProvider.GetService <Gateway>();

            //SSL
            var certPath = configuration.GetValue <string>("SSL:Cert");

            if (!string.IsNullOrEmpty(certPath))
            {
                gateway.ServerCert     = new System.Security.Cryptography.X509Certificates.X509Certificate2(certPath, configuration.GetValue <string>("SSL:Password"));
                gateway.AcceptCertHash = configuration.GetSection("SSL:AcceptCertHash").Get <string[]>();
            }

            gateway.ServiceProvider = serviceProvider;
            gateway.Run(port);
        }
Exemplo n.º 16
0
        protected override void ProcessRecord()
        {
            using (var vp = InitializeVault.GetVaultProvider(VaultProfile))
            {
                vp.OpenStorage();
                var v = vp.LoadVault();

                if (v.Registrations == null || v.Registrations.Count < 1)
                    throw new InvalidOperationException("No registrations found");

                var ri = v.Registrations[0];
                var r = ri.Registration;

                if (v.Certificates == null || v.Certificates.Count < 1)
                    throw new InvalidOperationException("No certificates found");

                var ci = v.Certificates.GetByRef(Ref);
                if (ci == null)
                    throw new Exception("Unable to find a Certificate for the given reference");

                using (var cp = CertificateProvider.GetProvider())
                {

                    if (!string.IsNullOrEmpty(ci.GenerateDetailsFile))
                    {
                        // Generate a private key and CSR:
                        //    Key:  RSA 2048-bit
                        //    MD:   SHA 256
                        //    CSR:  Details pulled from CSR Details JSON file

                        CsrDetails csrDetails;
                        var csrDetailsAsset = vp.GetAsset(VaultAssetType.CsrDetails, ci.GenerateDetailsFile);
                        using (var s = vp.LoadAsset(csrDetailsAsset))
                        {
                            csrDetails = JsonHelper.Load<CsrDetails>(s);
                        }

                        var keyGenFile = $"{ci.Id}-gen-key.json";
                        var keyPemFile = $"{ci.Id}-key.pem";
                        var csrGenFile = $"{ci.Id}-gen-csr.json";
                        var csrPemFile = $"{ci.Id}-csr.pem";

                        var keyGenAsset = vp.CreateAsset(VaultAssetType.KeyGen, keyGenFile);
                        var keyPemAsset = vp.CreateAsset(VaultAssetType.KeyPem, keyPemFile);
                        var csrGenAsset = vp.CreateAsset(VaultAssetType.CsrGen, csrGenFile);
                        var csrPemAsset = vp.CreateAsset(VaultAssetType.CsrPem, csrPemFile);

                        var genKeyParams = new RsaPrivateKeyParams();

                        var genKey = cp.GeneratePrivateKey(genKeyParams);
                        using (var s = vp.SaveAsset(keyGenAsset))
                        {
                            cp.SavePrivateKey(genKey, s);
                        }
                        using (var s = vp.SaveAsset(keyPemAsset))
                        {
                            cp.ExportPrivateKey(genKey, EncodingFormat.PEM, s);
                        }

                        // TODO: need to surface details of the CSR params up higher
                        var csrParams = new CsrParams
                        {
                            Details = csrDetails
                        };
                        var genCsr = cp.GenerateCsr(csrParams, genKey, Crt.MessageDigest.SHA256);
                        using (var s = vp.SaveAsset(csrGenAsset))
                        {
                            cp.SaveCsr(genCsr, s);
                        }
                        using (var s = vp.SaveAsset(csrPemAsset))
                        {
                            cp.ExportCsr(genCsr, EncodingFormat.PEM, s);
                        }

                        ci.KeyPemFile = keyPemFile;
                        ci.CsrPemFile = csrPemFile;
                    }



                    byte[] derRaw;

                    var asset = vp.GetAsset(VaultAssetType.CsrPem, ci.CsrPemFile);
                    // Convert the stored CSR in PEM format to DER
                    using (var source = vp.LoadAsset(asset))
                    {
                        var csr = cp.ImportCsr(EncodingFormat.PEM, source);
                        using (var target = new MemoryStream())
                        {
                            cp.ExportCsr(csr, EncodingFormat.DER, target);
                            derRaw = target.ToArray();
                        }
                    }

                    var derB64u = JwsHelper.Base64UrlEncode(derRaw);

                    using (var c = ClientHelper.GetClient(v, ri))
                    {
                        c.Init();
                        c.GetDirectory(true);

                        ci.CertificateRequest = c.RequestCertificate(derB64u);
                    }

                    if (!string.IsNullOrEmpty(ci.CertificateRequest.CertificateContent))
                    {
                        var crtDerFile = $"{ci.Id}-crt.der";
                        var crtPemFile = $"{ci.Id}-crt.pem";

                        var crtDerBytes = ci.CertificateRequest.GetCertificateContent();

                        var crtDerAsset = vp.CreateAsset(VaultAssetType.CrtDer, crtDerFile);
                        var crtPemAsset = vp.CreateAsset(VaultAssetType.CrtPem, crtPemFile);

                        using (Stream source = new MemoryStream(crtDerBytes),
                                derTarget = vp.SaveAsset(crtDerAsset),
                                pemTarget = vp.SaveAsset(crtPemAsset))
                        {
                            var crt = cp.ImportCertificate(EncodingFormat.DER, source);

                            cp.ExportCertificate(crt, EncodingFormat.DER, derTarget);
                            ci.CrtDerFile = crtDerFile;

                            cp.ExportCertificate(crt, EncodingFormat.PEM, pemTarget);
                            ci.CrtPemFile = crtPemFile;
                        }

                        // Extract a few pieces of info from the issued
                        // cert that we like to have quick access to
                        var x509 = new X509Certificate2(ci.CertificateRequest.GetCertificateContent());
                        ci.SerialNumber = x509.SerialNumber;
                        ci.Thumbprint = x509.Thumbprint;
                        ci.SignatureAlgorithm = x509.SignatureAlgorithm?.FriendlyName;
                        ci.Signature = x509.GetCertHashString();
                    }
                }

                vp.SaveVault(v);

                WriteObject(ci);
            }
        }
Exemplo n.º 17
0
        private static void SetupSecureEnvironment(X509Certificate2 certificate, string port)
        {
            SecurityHelper.PrepareEnvironment("serverCert.pfx", port, WindowsIdentity.GetCurrent().Name, "security");

            ServicePointManager.ServerCertificateValidationCallback +=
                (sender, cert, chan, sslPolicyErrors) => cert.GetCertHashString() == certificate.GetCertHashString();
        }
Exemplo n.º 18
0
        protected override void ProcessRecord()
        {
            using (var vlt = Util.VaultHelper.GetVault(VaultProfile))
            {
                vlt.OpenStorage();
                var v = vlt.LoadVault();

                if (v.Registrations == null || v.Registrations.Count < 1)
                    throw new InvalidOperationException("No registrations found");

                var ri = v.Registrations[0];
                var r = ri.Registration;

                if (v.Certificates == null || v.Certificates.Count < 1)
                    throw new InvalidOperationException("No certificates found");

                var ci = v.Certificates.GetByRef(CertificateRef, throwOnMissing: false);
                if (ci == null)
                    throw new Exception("Unable to find a Certificate for the given reference");

                // If we're renaming the Alias, do that
                // first in case there are any problems
                if (NewAlias != null)
                {
                    v.Certificates.Rename(CertificateRef, NewAlias);
                    ci.Alias = NewAlias == "" ? null : NewAlias;
                }

                if (!LocalOnly)
                {
                    if (ci.CertificateRequest == null)
                        throw new Exception("Certificate has not been submitted yet; cannot update status");

                    using (var c = ClientHelper.GetClient(v, ri))
                    {
                        c.Init();
                        c.GetDirectory(true);

                        c.RefreshCertificateRequest(ci.CertificateRequest, UseBaseUri);
                    }

                    if ((Repeat || string.IsNullOrEmpty(ci.CrtPemFile))
                            && !string.IsNullOrEmpty(ci.CertificateRequest.CertificateContent))
                    {
                        var crtDerFile = $"{ci.Id}-crt.der";
                        var crtPemFile = $"{ci.Id}-crt.pem";

                        var crtDerAsset = vlt.ListAssets(crtDerFile, VaultAssetType.CrtDer).FirstOrDefault();
                        var crtPemAsset = vlt.ListAssets(crtPemFile, VaultAssetType.CrtPem).FirstOrDefault();

                        if (crtDerAsset == null)
                            crtDerAsset = vlt.CreateAsset(VaultAssetType.CrtDer, crtDerFile);
                        if (crtPemAsset == null)
                            crtPemAsset = vlt.CreateAsset(VaultAssetType.CrtPem, crtPemFile);

                        using (var cp = PkiHelper.GetPkiTool(
                            StringHelper.IfNullOrEmpty(PkiTool, v.PkiTool)))
                        {
                            var bytes = ci.CertificateRequest.GetCertificateContent();

                            using (Stream source = new MemoryStream(bytes),
                                    derTarget = vlt.SaveAsset(crtDerAsset),
                                    pemTarget = vlt.SaveAsset(crtPemAsset))
                            {
                                var crt = cp.ImportCertificate(EncodingFormat.DER, source);

                                // We're saving the DER format cert "through"
                                // the CP in order to validate its content
                                cp.ExportCertificate(crt, EncodingFormat.DER, derTarget);
                                ci.CrtDerFile = crtDerFile;

                                cp.ExportCertificate(crt, EncodingFormat.PEM, pemTarget);
                                ci.CrtPemFile = crtPemFile;
                            }
                        }

                        var x509 = new X509Certificate2(ci.CertificateRequest.GetCertificateContent());
                        ci.SerialNumber = x509.SerialNumber;
                        ci.Thumbprint = x509.Thumbprint;
                        ci.SignatureAlgorithm = x509.SignatureAlgorithm?.FriendlyName;
                        ci.Signature = x509.GetCertHashString();
                    }

                    if (Repeat || string.IsNullOrEmpty(ci.IssuerSerialNumber))
                    {
                        var linksEnum = ci.CertificateRequest.Links;
                        if (linksEnum != null)
                        {
                            var links = new LinkCollection(linksEnum);
                            var upLink = links.GetFirstOrDefault("up");
                            if (upLink != null)
                            {
                                // We need to save the ICA certificate to a local
                                // temp file so that we can read it in and store
                                // it properly as a vault asset through a stream
                                var tmp = Path.GetTempFileName();
                                try
                                {
                                    using (var web = new WebClient())
                                    {
                                        if (v.Proxy != null)
                                            web.Proxy = v.Proxy.GetWebProxy();

                                        var uri = new Uri(new Uri(v.BaseUri), upLink.Uri);
                                        web.DownloadFile(uri, tmp);
                                    }

                                    var cacert = new X509Certificate2(tmp);
                                    var sernum = cacert.GetSerialNumberString();
                                    var tprint = cacert.Thumbprint;
                                    var sigalg = cacert.SignatureAlgorithm?.FriendlyName;
                                    var sigval = cacert.GetCertHashString();

                                    if (v.IssuerCertificates == null)
                                        v.IssuerCertificates = new OrderedNameMap<IssuerCertificateInfo>();
                                    if (Repeat || !v.IssuerCertificates.ContainsKey(sernum))
                                    {
                                        var cacertDerFile = $"ca-{sernum}-crt.der";
                                        var cacertPemFile = $"ca-{sernum}-crt.pem";
                                        var issuerDerAsset = vlt.ListAssets(cacertDerFile,
                                                VaultAssetType.IssuerDer).FirstOrDefault();
                                        var issuerPemAsset = vlt.ListAssets(cacertPemFile,
                                                VaultAssetType.IssuerPem).FirstOrDefault();

                                        if (Repeat || issuerDerAsset == null)
                                        {
                                            if (issuerDerAsset == null)
                                            issuerDerAsset = vlt.CreateAsset(VaultAssetType.IssuerDer, cacertDerFile);
                                                using (Stream fs = new FileStream(tmp, FileMode.Open),
                                                    s = vlt.SaveAsset(issuerDerAsset))
                                            {
                                                fs.CopyTo(s);
                                            }
                                        }
                                        if (Repeat || issuerPemAsset == null)
                                        {
                                            if (issuerPemAsset == null)
                                                issuerPemAsset = vlt.CreateAsset(VaultAssetType.IssuerPem, cacertPemFile);

                                            using (var cp = PkiHelper.GetPkiTool(
                                                StringHelper.IfNullOrEmpty(PkiTool, v.PkiTool)))
                                            {

                                                using (Stream source = vlt.LoadAsset(issuerDerAsset),
                                                    target = vlt.SaveAsset(issuerPemAsset))
                                                {
                                                    var crt = cp.ImportCertificate(EncodingFormat.DER, source);
                                                    cp.ExportCertificate(crt, EncodingFormat.PEM, target);
                                                }
                                            }
                                        }

                                        v.IssuerCertificates[sernum] = new IssuerCertificateInfo
                                        {
                                            SerialNumber = sernum,
                                            Thumbprint  = tprint,
                                            SignatureAlgorithm = sigalg,
                                            Signature = sigval,
                                            CrtDerFile = cacertDerFile,
                                            CrtPemFile = cacertPemFile,
                                        };
                                    }

                                    ci.IssuerSerialNumber = sernum;
                                }
                                finally
                                {
                                    if (File.Exists(tmp))
                                        File.Delete(tmp);
                                }
                            }
                        }
                    }
                }

                ci.Label = StringHelper.IfNullOrEmpty(Label);
                ci.Memo = StringHelper.IfNullOrEmpty(Memo);

                vlt.SaveVault(v);

                WriteObject(ci);
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Adds a certificate to the Azure certificate store
        /// </summary>
        private IAsyncAzureOperation AddCertificateToAzureStore(X509Certificate2 certificate, string password)
        {
            AzureManagementClient client = new AzureManagementClient(this.certificate, this.subscriptionId);
            AzureManagementResponse response;

            IEnumerable<X509Certificate2> currentCerts = this.EnumerateServiceCertificates(CertificateLocation.AzureManagement);
            foreach (X509Certificate2 existingCert in currentCerts)
            {
                if (existingCert.Thumbprint == certificate.Thumbprint &&
                    existingCert.Thumbprint != null &&
                    existingCert.GetCertHashString() == certificate.GetCertHashString())
                {
                    return new AsyncAzureOperation(this, string.Empty, true);
                }

                // If the certificate does not match, but has a matching name we should delete it
                if (string.Equals(existingCert.SubjectName.Name, certificate.SubjectName.Name))
                {
                    // Delete the certificate using Azure APIs
                    response = client.SubmitRequest(
                        RequestType.DELETE,
                        "2009-10-01",
                        "services/hostedservices/{0}/certificates/SHA1-{1}",
                        this.serviceName,
                        existingCert.Thumbprint
                        );

                    IAsyncAzureOperation op = new AsyncAzureOperation(this, response.OperationId, false);
                    op.WaitForCompletion(TimeSpan.FromSeconds(30));
                }
            }

            string request =
                "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<CertificateFile xmlns=\"http://schemas.microsoft.com/windowsazure\">" +
                "<Data>{0}</Data>" +
                "<CertificateFormat>pfx</CertificateFormat>" +
                "<Password>{1}</Password>" +
                "</CertificateFile>";

            byte[] content = certificate.Export(X509ContentType.Pfx, password);
            request = string.Format(request, Convert.ToBase64String(content), System.Security.SecurityElement.Escape(password));

            response = client.SubmitRequestWithBody(
                RequestType.POST,
                request,
                "2009-10-01",
                "services/hostedservices/{0}/certificates",
                this.serviceName
            );

            return new AsyncAzureOperation(this, response.OperationId, false);
        }
        protected override void ProcessRecord()
        {
            using (var vp = InitializeVault.GetVaultProvider(VaultProfile))
            {
                vp.OpenStorage();
                var v = vp.LoadVault();

                if (v.Registrations == null || v.Registrations.Count < 1)
                    throw new InvalidOperationException("No registrations found");

                var ri = v.Registrations[0];
                var r = ri.Registration;

                if (v.Certificates == null || v.Certificates.Count < 1)
                    throw new InvalidOperationException("No certificates found");

                var ci = v.Certificates.GetByRef(Ref);
                if (ci == null)
                    throw new Exception("Unable to find a Certificate for the given reference");

                if (!string.IsNullOrEmpty(ci.GenerateDetailsFile))
                {
                    // Generate a private key and CSR:
                    //    Key:  RSA 2048-bit
                    //    MD:   SHA 256
                    //    CSR:  Details pulled from CSR Details JSON file

                    CsrHelper.CsrDetails csrDetails;
                    var csrDetailsAsset = vp.GetAsset(VaultAssetType.CsrDetails, ci.GenerateDetailsFile);
                    using (var s = vp.LoadAsset(csrDetailsAsset))
                    {
                        csrDetails = JsonHelper.Load<CsrHelper.CsrDetails>(s);
                    }

                    var keyGenFile = $"{ci.Id}-gen-key.json";
                    var keyPemFile = $"{ci.Id}-key.pem";
                    var csrGenFile = $"{ci.Id}-gen-csr.json";
                    var csrPemFile = $"{ci.Id}-csr.pem";

                    var keyGenAsset = vp.CreateAsset(VaultAssetType.KeyGen, keyGenFile);
                    var keyPemAsset = vp.CreateAsset(VaultAssetType.KeyPem, keyPemFile);
                    var csrGenAsset = vp.CreateAsset(VaultAssetType.CsrGen, csrGenFile);
                    var csrPemAsset = vp.CreateAsset(VaultAssetType.CsrPem, csrPemFile);

                    var genKey = CsrHelper.GenerateRsaPrivateKey();
                    using (var s = vp.SaveAsset(keyGenAsset))
                    {
                        genKey.Save(s);
                    }
                    using (var w = new StreamWriter(vp.SaveAsset(keyPemAsset)))
                    {
                        w.Write(genKey.Pem);
                    }

                    var genCsr = CsrHelper.GenerateCsr(csrDetails, genKey);
                    using (var s = vp.SaveAsset(csrGenAsset))
                    {
                        genCsr.Save(s);
                    }
                    using (var w = new StreamWriter(vp.SaveAsset(csrPemAsset)))
                    {
                        w.Write(genCsr.Pem);
                    }

                    ci.KeyPemFile = keyPemFile;
                    ci.CsrPemFile = csrPemFile;
                }

                var asset = vp.GetAsset(VaultAssetType.CsrPem, ci.CsrPemFile);

                byte[] derRaw;
                using (var s = vp.LoadAsset(asset))
                {
                    using (var ms = new MemoryStream())
                    {
                        CsrHelper.Csr.ConvertPemToDer(s, ms);
                        derRaw = ms.ToArray();
                    }
                }

                var derB64u = JwsHelper.Base64UrlEncode(derRaw);

                using (var c = ClientHelper.GetClient(v, ri))
                {
                    c.Init();
                    c.GetDirectory(true);

                    ci.CertificateRequest = c.RequestCertificate(derB64u);
                }

                if (!string.IsNullOrEmpty(ci.CertificateRequest.CertificateContent))
                {
                    var crtDerFile = $"{ci.Id}-crt.der";
                    var crtPemFile = $"{ci.Id}-crt.pem";

                    var crtDerAsset = vp.CreateAsset(VaultAssetType.CrtDer, crtDerFile);
                    var crtPemAsset = vp.CreateAsset(VaultAssetType.CrtPem, crtPemFile);

                    using (var s = vp.SaveAsset(crtDerAsset))
                    {
                        ci.CertificateRequest.SaveCertificate(s);
                        ci.CrtDerFile = crtDerFile;
                    }

                    using (Stream source = vp.LoadAsset(crtDerAsset), target = vp.SaveAsset(crtPemAsset))
                    {
                        CsrHelper.Crt.ConvertDerToPem(source, target);
                        ci.CrtPemFile = crtPemFile;
                    }

                    var crt = new X509Certificate2(ci.CertificateRequest.GetCertificateContent());
                    ci.SerialNumber = crt.SerialNumber;
                    ci.Thumbprint = crt.Thumbprint;
                    ci.SignatureAlgorithm = crt.SignatureAlgorithm?.FriendlyName;
                    ci.Signature = crt.GetCertHashString();
                }

                vp.SaveVault(v);

                WriteObject(ci);
            }
        }
        private void InstallCertificateToStore(X509Certificate2 certificate,  string certificateStoreName)
        {
            var hash = certificate.GetCertHashString();

            var store = new X509Store(certificateStoreName, StoreLocation.LocalMachine);            
            store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite); 
            if (store.Certificates.OfType<X509Certificate2>()
                .Any(
                    c =>
                        c.Subject == certificate.Subject &&
                        c.HasPrivateKey &&                        
                        string.Equals(c.GetCertHashString(), hash, StringComparison.OrdinalIgnoreCase)))
            {
                Info($"the certificate with subject {certificate.Subject} and hash {hash} is already installed in store LocalMachine\\{certificateStoreName}");
                store.Close();
                return;
            }

            Info($"Installing certificate with subject {certificate.Subject} and hash {hash} to store LocalMachine\\{certificateStoreName}");
            
            store.Add(certificate);
            store.Close();
        }
 private X509Certificate2 EnsurePrivateKey(X509Certificate certificate)
 {
     if (certificate != null)
     {
         if (Logging.On)
         {
             Logging.PrintInfo(Logging.Web, this, SR.GetString("net_log_locating_private_key_for_certificate", new object[] { certificate.ToString(true) }));
         }
         try
         {
             X509Certificate2Collection certificates;
             X509Certificate2 certificate2 = certificate as X509Certificate2;
             Type type = certificate.GetType();
             string findValue = null;
             if ((type != typeof(X509Certificate2)) && (type != typeof(X509Certificate)))
             {
                 if (certificate.Handle != IntPtr.Zero)
                 {
                     certificate2 = new X509Certificate2(certificate);
                     findValue = certificate2.GetCertHashString();
                 }
             }
             else
             {
                 findValue = certificate.GetCertHashString();
             }
             if (certificate2 != null)
             {
                 if (certificate2.HasPrivateKey)
                 {
                     if (Logging.On)
                     {
                         Logging.PrintInfo(Logging.Web, this, SR.GetString("net_log_cert_is_of_type_2"));
                     }
                     return certificate2;
                 }
                 if (certificate != certificate2)
                 {
                     certificate2.Reset();
                 }
             }
             ExceptionHelper.KeyContainerPermissionOpen.Demand();
             X509Store store = EnsureStoreOpened(this.m_ServerMode);
             if (store != null)
             {
                 certificates = store.Certificates.Find(X509FindType.FindByThumbprint, findValue, false);
                 if ((certificates.Count > 0) && (certificates[0].PrivateKey != null))
                 {
                     if (Logging.On)
                     {
                         Logging.PrintInfo(Logging.Web, this, SR.GetString("net_log_found_cert_in_store", new object[] { this.m_ServerMode ? "LocalMachine" : "CurrentUser" }));
                     }
                     return certificates[0];
                 }
             }
             store = EnsureStoreOpened(!this.m_ServerMode);
             if (store != null)
             {
                 certificates = store.Certificates.Find(X509FindType.FindByThumbprint, findValue, false);
                 if ((certificates.Count > 0) && (certificates[0].PrivateKey != null))
                 {
                     if (Logging.On)
                     {
                         Logging.PrintInfo(Logging.Web, this, SR.GetString("net_log_found_cert_in_store", new object[] { this.m_ServerMode ? "CurrentUser" : "LocalMachine" }));
                     }
                     return certificates[0];
                 }
             }
         }
         catch (CryptographicException)
         {
         }
         if (Logging.On)
         {
             Logging.PrintInfo(Logging.Web, this, SR.GetString("net_log_did_not_find_cert_in_store"));
         }
     }
     return null;
 }
        private void OutputCertificate(X509Certificate2 x509Certificate)
        {
            System.Diagnostics.Debug.WriteLine("");
            System.Diagnostics.Debug.WriteLine("Certificate Data: ******************************************************************");

            System.Diagnostics.Debug.WriteLine("");
            System.Diagnostics.Debug.WriteLine("Basic Certificate Information");
            //System.Diagnostics.Debug.WriteLine("\t Content Type: " + X509Certificate2.GetCertContentType(x509Certificate.RawData));
            System.Diagnostics.Debug.WriteLine("\t Format: " + x509Certificate.GetFormat());
            System.Diagnostics.Debug.WriteLine("\t Version: " + x509Certificate.Version.ToString());
            System.Diagnostics.Debug.WriteLine("\t Hash String: " + x509Certificate.GetCertHashString());
            System.Diagnostics.Debug.WriteLine("\t Issuer Name: " + x509Certificate.IssuerName.Name);
            System.Diagnostics.Debug.WriteLine("\t Issuer Name OID: " + x509Certificate.IssuerName.Oid.Value);
            System.Diagnostics.Debug.WriteLine("\t Subject Name: " + x509Certificate.SubjectName.Name);
            System.Diagnostics.Debug.WriteLine("\t Serial Number: " + x509Certificate.GetSerialNumberString());
            System.Diagnostics.Debug.WriteLine("\t Thumb Print: " + x509Certificate.Thumbprint);
            System.Diagnostics.Debug.WriteLine("\t Friendly Name: " + x509Certificate.FriendlyName);
            System.Diagnostics.Debug.WriteLine("\t Signature Algorithm: " + x509Certificate.SignatureAlgorithm.FriendlyName);
            if (null != x509Certificate.PrivateKey)
                System.Diagnostics.Debug.WriteLine("\t Signature Key Exchange Algorithm: " + x509Certificate.PrivateKey.KeyExchangeAlgorithm);
            else
                System.Diagnostics.Debug.WriteLine("\t Signature Key Exchange Algorithm: ");
            System.Diagnostics.Debug.WriteLine("\t Key Algorithm Parameters: " + x509Certificate.GetKeyAlgorithmParametersString());
            System.Diagnostics.Debug.WriteLine("\t Not Valid Before: " + x509Certificate.NotBefore.ToString());
            System.Diagnostics.Debug.WriteLine("\t Not Valid After: " + x509Certificate.NotAfter.ToString());
            System.Diagnostics.Debug.WriteLine("\t Can Be Verified: " + x509Certificate.Verify());
            System.Diagnostics.Debug.WriteLine("\t Is Archived: " + x509Certificate.Archived);

            System.Diagnostics.Debug.WriteLine("");
            System.Diagnostics.Debug.WriteLine("X509 Name Elements");
            System.Diagnostics.Debug.WriteLine("\t X509 Simple Name: " + x509Certificate.GetNameInfo(X509NameType.SimpleName, false));
            System.Diagnostics.Debug.WriteLine("\t X509 DNS From Alternative Name: " + x509Certificate.GetNameInfo(X509NameType.DnsFromAlternativeName, false));
            System.Diagnostics.Debug.WriteLine("\t X509 DNS Name: " + x509Certificate.GetNameInfo(X509NameType.DnsName, false));
            System.Diagnostics.Debug.WriteLine("\t X509 Email Name: " + x509Certificate.GetNameInfo(X509NameType.EmailName, false));
            System.Diagnostics.Debug.WriteLine("\t X509 UPN Name: " + x509Certificate.GetNameInfo(X509NameType.UpnName, false));
            System.Diagnostics.Debug.WriteLine("\t X509 URL Name: " + x509Certificate.GetNameInfo(X509NameType.UrlName, false));

            System.Diagnostics.Debug.WriteLine("");
            System.Diagnostics.Debug.WriteLine("X509 Name Elements for Issuer");
            System.Diagnostics.Debug.WriteLine("\t X509 Simple Name: " + x509Certificate.GetNameInfo(X509NameType.SimpleName, true));
            System.Diagnostics.Debug.WriteLine("\t X509 DNS From Alternative Name: " + x509Certificate.GetNameInfo(X509NameType.DnsFromAlternativeName, true));
            System.Diagnostics.Debug.WriteLine("\t X509 DNS Name: " + x509Certificate.GetNameInfo(X509NameType.DnsName, true));
            System.Diagnostics.Debug.WriteLine("\t X509 Email Name: " + x509Certificate.GetNameInfo(X509NameType.EmailName, true));
            System.Diagnostics.Debug.WriteLine("\t X509 UPN Name: " + x509Certificate.GetNameInfo(X509NameType.UpnName, true));
            System.Diagnostics.Debug.WriteLine("\t X509 URL Name: " + x509Certificate.GetNameInfo(X509NameType.UrlName, true));

            System.Diagnostics.Debug.WriteLine("");
            System.Diagnostics.Debug.WriteLine("Keys");
            System.Diagnostics.Debug.WriteLine("\t Public Key: " + x509Certificate.PublicKey.Key.ToXmlString(false));
            if (null != x509Certificate.PrivateKey)
                System.Diagnostics.Debug.WriteLine("\t Private Key: " + x509Certificate.PrivateKey.ToXmlString(false));
            else
                System.Diagnostics.Debug.WriteLine("\t Private Key: ");

            System.Diagnostics.Debug.WriteLine("");
            System.Diagnostics.Debug.WriteLine("Raw Cert");
            System.Diagnostics.Debug.WriteLine("\t " + x509Certificate.GetRawCertDataString());

            System.Diagnostics.Debug.WriteLine("");
            System.Diagnostics.Debug.WriteLine("************************************************************************************");
            System.Diagnostics.Debug.WriteLine("");
        }