通过ServerManager类对iis进行相对应的操作(包括建立站点,程序池,绑定域名之类,这里不详细解释,网上有很多这方面的资料),我就想既然可以手动在iis创建域名并绑定ssl证书,那应该也有对应的实现方法,果然找到了里面的一个方法,贴上代码先
ServerManager sm = new ServerManager();
string bindingInformation = "*:" + port + ":" + bindingDomainName;
sm.Sites[webName].Bindings.Add(bindingInformation, certificateHash, certificateStoreName);
bindingInformation应该不用解释,一眼就看到是绑定的端口和域名, certificateHash和certificateStoreName又是什么呢?certificateHash参数类型是byte[],而certificateStoreName参数类型是string,通过直接百度翻译得到的结果是证书散列和证书,正在思考他们的来源时,突然想到购买ssl证书之后提供给我们的相关文件和秘钥,应该和这里大有关联,通过查询一些资料,得知certificateHash(证书散列)是通过.pfx文件获取而来的,而certificateStoreName则是证书名称,这里贴上完整的代码
// <summary> /// 增加绑定域名(ssl) /// </summary> /// <param name="webName">站点名称</param> /// <param name="port">端口</param> /// <param name="bindingDomainName">绑定域名</param> public void AddHostHeaderSSL(string webName, string port, string bindingDomainName) { //**pfxPath**是指提供给你的.pfx文件的路径,购买ssl之后他会提供给你相关的文件,里面有多个文件 //一般包含apache文件夹,iis文件夹,nginx文件夹,我使用的是iis部署,所以.pfx文件在iis文件夹里面 //**certPwd**是指购买ssl之后提供给你的秘钥 string pfx = Directory.GetFiles(pfxPath, "*.pfx", SearchOption.AllDirectories).FirstOrDefault(); var store = new X509Store(StoreName.AuthRoot, StoreLocation.LocalMachine); store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite); var certificate = new X509Certificate2(pfx, certPwd, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); store.Add(certificate); store.Close(); var certificateStoreName = store.Name; //绑定的证书名称 var certificateHash = certificate.GetCertHash(); //证书内容 ServerManager sm = new ServerManager(); string bindingInformation = "*:" + port + ":" + bindingDomainName; sm.Sites[webName].Bindings.Add(bindingInformation, certificateHash, certificateStoreName); sm.CommitChanges(); }
至此,动态绑定ssl证书的功能就实现了
以下示例演示CertificateHash属性。如果协议标识符为“https”,则显示证书哈希和证书库名称。此代码示例是为Binding类提供的更大示例的一部分。
if (binding.Protocol == "https"){ // There is a CertificateHash and // CertificateStoreName for the https protocol only. bindingdisplay = bindingdisplay + "\n CertificateHash: " + binding.CertificateHash + ": "; // Display the hash. foreach (System.Byte certhashbyte in binding.CertificateHash) { bindingdisplay = bindingdisplay + certhashbyte.ToString() + " "; } bindingdisplay = bindingdisplay + "\n CertificateStoreName: " + binding.CertificateStoreName;}
vb.net
If (binding.Protocol = "https") Then ' There is a CertificateHash and ' CertificateStoreName for the https protocol only. bindingdisplay = (bindingdisplay + (""& vbLf&" CertificateHash: " _ + (binding.CertificateHash + ": "))) ' Display the hash. For Each certhashbyte As Byte In binding.CertificateHash bindingdisplay = (bindingdisplay _ + (certhashbyte.ToString + " ")) Next bindingdisplay = (bindingdisplay + (""& vbLf&" CertificateStoreName: " + binding.CertificateStoreName)) End If
如对本文有疑问,请提交到交流论坛,广大热心网友会为你解答!! 点击进入论坛