[c#] 使用数字证书来访问https

方式一:从当前浏览器中取得证书,让用户来进行选择。

         X509Store x509Store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
         x509Store.Open(OpenFlags.ReadOnly | OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
         // 打开本地浏览器中的数字证书列表
         certs = X509Certificate2UI.SelectFromCollection(x509Store.Certificates, “请选择”, “数字证书选择列表!”, 
                       X509SelectionFlag.SingleSelection, certForm.Handle);

            // remoteWebServSSL为一个SoapHttpClientProtocol对象,VS自动生成的
            remoteWebServSSL.Service srv = new remoteWebServSSL.Service();
            srv.ClientCertificates.Add(certs[0]);
           
            // 调用Webservice 的一个测试方法
            MessageBox.Show(“The Web Service say: ” + srv.HelloWorld());

方式二:从数字证书备份文件中加载。

            remoteWebServSSL.Service srv = new remoteWebServSSL.Service();
            srv.ClientCertificates.Add(
                new System.Security.Cryptography.X509Certificates.X509Certificate2(@”c:mycert.pfx”, “password”));
           
            MessageBox.Show(“The Web Service say: ” + srv.HelloWorld());

访问https的网页:

HttpWebRequest req = (HttpWebRequest)System.Net.WebRequest.Create(“https://www.who.com/”);
req.Method = “POST”;        // Post method
req.ContentType = “application/octet-stream”;   // content type
//You can also use ContentType = “text/xml”; 
req.Headers.Add(“sender-id”, strSenderID);  
// Some Header information which you would like to send 
// with the request
req.ContentLength = 1000; 
req.KeepAlive = false;
req.UserAgent = null;
req.Timeout = 99999;
req.ReadWriteTimeout = 99999;
req.ServicePoint.MaxIdleTime = 99999;
req.ClientCertificates.Add(cert);

HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();

两种方式基本一样,目的都是从不同的方式取得客户的个人数字证书来与服务器进行交互。