使用 C# 自动将 SSL 证书安装到 IIS 6 站点

发布于 2024-12-09 17:37:11 字数 507 浏览 0 评论 0原文

我正在尝试通过 C# 代码自动化在 IIS 6 中生成站点的过程。我正在使用 DirectoryServices,我已经快到了。我用它来创建站点,设置所有绑定等,一切都很好。我还没弄清楚如何安装我们的通配符 ssl 证书。详细信息如下:

我们有一个与“*.example.com”匹配的 SSL 证书。 我们托管的每个站点都有一个匹配的服务器绑定。例如“test.example.com”。 我想我知道如何添加 SecureBinding 属性:

DirectoryEntrySite.Properties["SecureBindings"][0] = "xx.xx.xx.xx:443:test.example.com";

但我没有成功找到有关如何自动将证书安装到站点的信息。在 IIS 6 管理器中,您可以通过右键单击站点 -> 来完成此操作。属性->目录安全->服务器证书->下一步->分配现有证书 -> (选择证书)->接下来...

有人可以帮忙吗?

I'm trying to automate the process of generating a site in IIS 6 via C# code. I'm using DirectoryServices and I'm nearly there.. I have it creating the site, setting up all the bindings etc. just fine. I have not figured out how to install our wildcard ssl cert. Here's the details:

We have a SSL certificate that matches '*.example.com'.
Every site we host has a server binding that matches. e.g. 'test.example.com'.
I think I know how to add the SecureBinding property:

DirectoryEntrySite.Properties["SecureBindings"][0] = "xx.xx.xx.xx:443:test.example.com";

But I have had no success finding information on how to automatically install the certificate to the site. In the IIS 6 Manager, you would do this by right clicking a site -> properties -> Directory Security -> Server Certificate -> Next -> Assign an existing certificate -> (select certificate) -> Next...

Can anyone help?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

能否归途做我良人 2024-12-16 17:37:11

请参阅:http://forums.iis.net/t/1163325.aspx

using Microsoft.Web.Administration;  

X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite);

X509Certificate2 certificate = new X509Certificate2(pfxFilePath);

store.Add(certificate);

using (ServerManager serverManager = new ServerManager())
{
    Site site = serverManager.Sites["Default Web Site"];

    if (site != null)
    {
         site.Bindings.Add("*:443:", certificate.GetCertHash(), store.Name);
    }

    store.Close();
}

See this: http://forums.iis.net/t/1163325.aspx

using Microsoft.Web.Administration;  

X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite);

X509Certificate2 certificate = new X509Certificate2(pfxFilePath);

store.Add(certificate);

using (ServerManager serverManager = new ServerManager())
{
    Site site = serverManager.Sites["Default Web Site"];

    if (site != null)
    {
         site.Bindings.Add("*:443:", certificate.GetCertHash(), store.Name);
    }

    store.Close();
}
瀞厅☆埖开 2024-12-16 17:37:11

好的,这个问题已经有了答案,但是所授予的答案不是针对 IIS6 的,而是针对 IIS7 及更高版本的。命名空间 Microsoft.Web.Administration 不适用于 IIS6。我们在 .NET 4.0 中整合了一系列技术来实现这一目标。

步骤...

  1. 添加对 COM 组件 IIS CertObj 1.0 类型库的引用
  2. 在添加的引用 CERTOBJLib 上,在属性表中设置
    “嵌入互操作类型”为 false
  3. 使用以下方法创建一个类...

using System.Linq;
using System.Management;
namespace CertStuff
{
    public class CertificateInstaller
    {
public void RegisterCertificateWithIIS6(string webSiteName, string certificateFilePath, string certificatePassword)
        {
            // USE WMI TO DERIVE THE INSTANCE NAME
            ManagementScope managementScope = new ManagementScope(@"\\.\root\MicrosoftIISv2");
            managementScope.Connect();
            ObjectQuery queryObject = new ObjectQuery("SELECT Name FROM IISWebServerSetting WHERE ServerComment = '" + webSiteName + "'");
            ManagementObjectSearcher searchObject = new ManagementObjectSearcher(managementScope, queryObject);
            var instanceNameCollection = searchObject.Get();
            var instanceName = (from i in instanceNameCollection.Cast<ManagementObject>() select i).FirstOrDefault();

            // USE IIS CERT OBJ TO IMPORT CERT - THIS IS A COM OBJECT
            var IISCertObj = new CERTOBJLib.IISCertObjClass();
            IISCertObj.InstanceName = instanceName["Name"].ToString();
            IISCertObj.Import(certificateFilePath, certificatePassword, false, true); // OVERWRITE EXISTING
        }

    }
}

要删除证书引用,请使用以下方法...

public void UnRegisterCertificateWithIIS6(string webSiteName)
        {
            // USE WMI TO DERIVE THE INSTANCE NAME
            ManagementScope managementScope = new ManagementScope(@"\\.\root\MicrosoftIISv2");
            managementScope.Connect();
            ObjectQuery queryObject = new ObjectQuery("SELECT Name FROM IISWebServerSetting WHERE ServerComment = '" + webSiteName + "'");
            ManagementObjectSearcher searchObject = new ManagementObjectSearcher(managementScope, queryObject);

            foreach (var instanceName in searchObject.Get())
            {
                var IISCertObj = new CERTOBJLib.IISCertObjClass();
                IISCertObj.InstanceName = instanceName["Name"].ToString();

                // THE REMOVE CERT CALL COMPLETES SUCCESSFULLY, BUT FOR WHATEVER REASON, IT ERRORS OUT.
                // SWALLOW THE ERROR.
                try
                {
                    IISCertObj.RemoveCert(false, true);
                }
                catch (Exception ex)
                {

                }
            }
        }

注意:如果收到错误“Interop type 'CERTOBJLib.IISCertObjClass” ' 无法嵌入。请改用适用的接口。”,这意味着跳过了步骤 2。确保参考对象未嵌入。

OK, this question is already answered, but the awarded answer is not for IIS6, but rather IIS7 and greater. The namespace Microsoft.Web.Administration is not available for IIS6. We hobbled together a series of technologies, all in .NET 4.0 to make this work.

Steps...

  1. Add reference to COM component IIS CertObj 1.0 Type Library
  2. On the added reference CERTOBJLib, in the properties sheet, set
    'Embed Interop Types' to false
  3. Create a class with the following method...

using System.Linq;
using System.Management;
namespace CertStuff
{
    public class CertificateInstaller
    {
public void RegisterCertificateWithIIS6(string webSiteName, string certificateFilePath, string certificatePassword)
        {
            // USE WMI TO DERIVE THE INSTANCE NAME
            ManagementScope managementScope = new ManagementScope(@"\\.\root\MicrosoftIISv2");
            managementScope.Connect();
            ObjectQuery queryObject = new ObjectQuery("SELECT Name FROM IISWebServerSetting WHERE ServerComment = '" + webSiteName + "'");
            ManagementObjectSearcher searchObject = new ManagementObjectSearcher(managementScope, queryObject);
            var instanceNameCollection = searchObject.Get();
            var instanceName = (from i in instanceNameCollection.Cast<ManagementObject>() select i).FirstOrDefault();

            // USE IIS CERT OBJ TO IMPORT CERT - THIS IS A COM OBJECT
            var IISCertObj = new CERTOBJLib.IISCertObjClass();
            IISCertObj.InstanceName = instanceName["Name"].ToString();
            IISCertObj.Import(certificateFilePath, certificatePassword, false, true); // OVERWRITE EXISTING
        }

    }
}

to remove the cert reference, use the following method...

public void UnRegisterCertificateWithIIS6(string webSiteName)
        {
            // USE WMI TO DERIVE THE INSTANCE NAME
            ManagementScope managementScope = new ManagementScope(@"\\.\root\MicrosoftIISv2");
            managementScope.Connect();
            ObjectQuery queryObject = new ObjectQuery("SELECT Name FROM IISWebServerSetting WHERE ServerComment = '" + webSiteName + "'");
            ManagementObjectSearcher searchObject = new ManagementObjectSearcher(managementScope, queryObject);

            foreach (var instanceName in searchObject.Get())
            {
                var IISCertObj = new CERTOBJLib.IISCertObjClass();
                IISCertObj.InstanceName = instanceName["Name"].ToString();

                // THE REMOVE CERT CALL COMPLETES SUCCESSFULLY, BUT FOR WHATEVER REASON, IT ERRORS OUT.
                // SWALLOW THE ERROR.
                try
                {
                    IISCertObj.RemoveCert(false, true);
                }
                catch (Exception ex)
                {

                }
            }
        }

NOTE: if you receive error "Interop type 'CERTOBJLib.IISCertObjClass' cannot be embedded. Use the applicable interface instead.", this means step 2 was skipped. Ensure the reference object is NOT embedded.

墨落画卷 2024-12-16 17:37:11

要使用 .Net 4.7 和 IIS 10 执行此操作,您可以传递以下标志:

X509Certificate2 certificate = new X509Certificate2(path, "password", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable| X509KeyStorageFlags.MachineKeySet);

如果您将证书存储在 CurrentUser 存储中而不是 LocalMachine 存储中,请执行以下操作:

X509Certificate2 certificate = new X509Certificate2(path, "password", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable| X509KeyStorageFlags.UserKeySet);

密钥集标志指示以下内容:

//
// Summary:
//     Private keys are stored in the current user store rather than the local computer
//     store. This occurs even if the certificate specifies that the keys should go
//     in the local computer store.
UserKeySet = 1,
//
// Summary:
//     Private keys are stored in the local computer store rather than the current user
//     store.
MachineKeySet = 2,

私钥需要与证书的其余部分位于同一位置才能与 IIS 一起使用。

To do this with .Net 4.7 and IIS 10, you can pass the following flags:

X509Certificate2 certificate = new X509Certificate2(path, "password", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable| X509KeyStorageFlags.MachineKeySet);

If you are storing the cert in the CurrentUser store rather than in the LocalMachine store, do the following:

X509Certificate2 certificate = new X509Certificate2(path, "password", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable| X509KeyStorageFlags.UserKeySet);

The Key set flags indicate the following:

//
// Summary:
//     Private keys are stored in the current user store rather than the local computer
//     store. This occurs even if the certificate specifies that the keys should go
//     in the local computer store.
UserKeySet = 1,
//
// Summary:
//     Private keys are stored in the local computer store rather than the current user
//     store.
MachineKeySet = 2,

The private key needs to be in the same place as the rest of the certificate for it to work with IIS.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文